Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Removed redundencies

sassanix3e2390beefc7
diff --git a/frontend/src/auth-redirect.js b/frontend/src/auth-redirect.js
deleted file mode 100644
index da9fd43..0000000
--- a/frontend/src/auth-redirect.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * Authentication Redirect Script
- *
- * This script handles redirects based on authentication status:
- * - Redirects unauthenticated users from protected pages to login
- * - Redirects authenticated users from login/register to index
- *
- * Usage:
- * Include this script at the very beginning of your HTML with:
- * <script src="auth-redirect.js" data-protected="true|false"></script>
- *
- * Set data-protected="true" for pages that require authentication (index, status, settings)
- * Set data-protected="false" for auth pages (login, register)
- */
-
-(function() {
- // Wait for DOM to be ready enough to execute script
- const executeRedirect = () => {
- try {
- // Get current script element
- const currentScript = document.currentScript;
-
- // Check if isProtected attribute is set
- const isProtected = currentScript.getAttribute('data-protected') === 'true';
-
- // Check authentication status
- const isAuthenticated = !!localStorage.getItem('auth_token');
- const currentPath = window.location.pathname;
-
- console.log('Auth redirect check - Protected page:', isProtected);
- console.log('Auth redirect check - Is authenticated:', isAuthenticated);
- console.log('Auth redirect check - Current path:', currentPath);
-
- // Handle protected pages (index, status, settings)
- if (isProtected && !isAuthenticated) {
- console.log('Access to protected page without authentication, redirecting to login');
- window.location.href = 'login.html';
- return;
- }
-
- // Handle auth pages (login, register)
- if (!isProtected && isAuthenticated) {
- console.log('Already authenticated, redirecting from auth page to index');
- window.location.href = 'index.html';
- return;
- }
-
- console.log('No redirect needed');
- } catch (error) {
- console.error('Error in auth-redirect.js:', error);
- }
- };
-
- // Execute immediately
- executeRedirect();
-})();
\ No newline at end of file
diff --git a/frontend/src/chart.js b/frontend/src/chart.js
deleted file mode 100644
index 47cbcd9..0000000
--- a/frontend/src/chart.js
+++ /dev/null
@@ -1,14 +0,0 @@
-/*!
- * Chart.js v4.4.9
- * https://www.chartjs.org
- * (c) 2025 Chart.js Contributors
- * Released under the MIT License
- */
-!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Zo},get Decimation(){return ta},get Filler(){return xa},get Legend(){return va},get SubTitle(){return Sa},get Title(){return wa},get Tooltip(){return Wa}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;a<r;a++)e.call(i,t[a],a);else if(o(t))for(l=Object.keys(t),r=l.length,a=0;a<r;a++)e.call(i,t[l[a]],l[a])}function f(t,e){let i,s,n,o;if(!t||!e||t.length!==e.length)return!1;for(i=0,s=t.length;i<s;++i)if(n=t[i],o=e[i],n.datasetIndex!==o.datasetIndex||n.index!==o.index)return!1;return!0}function g(t){if(n(t))return t.map(g);if(o(t)){const e=Object.create(null),i=Object.keys(t),s=i.length;let n=0;for(;n<s;++n)e[i[n]]=g(t[i[n]]);return e}return t}function p(t){return-1===["__proto__","prototype","constructor"].indexOf(t)}function m(t,e,i,s){if(!p(t))return;const n=e[t],a=i[t];o(n)&&o(a)?x(n,a,s):e[t]=g(a)}function x(t,e,i){const s=n(e)?e:[e],a=s.length;if(!o(t))return t;const r=(i=i||{}).merger||m;let l;for(let e=0;e<a;++e){if(l=s[e],!o(l))continue;const n=Object.keys(l);for(let e=0,s=n.length;e<s;++e)r(n[e],t,l,i)}return t}function b(t,e){return x(t,e,{merger:_})}function _(t,e,i){if(!p(t))return;const s=e[t],n=i[t];o(s)&&o(n)?b(s,n):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=g(n))}const y={"":t=>t,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)<i}function B(t){const e=Math.round(t);t=V(t,e,t/1e3)?e:t;const i=Math.pow(10,Math.floor(z(t))),s=t/i;return(s<=1?1:s<=2?2:s<=5?5:10)*i}function W(t){const e=[],i=Math.sqrt(t);let s;for(s=1;s<i;s++)t%s==0&&(e.push(s),e.push(t/s));return i===(0|i)&&e.push(i),e.sort(((t,e)=>t-e)).pop(),e}function N(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;s<n;s++)o=t[s][i],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function $(t){return t*(C/180)}function Y(t){return t*(180/C)}function U(t){if(!a(t))return;let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function X(t,e){const i=e.x-t.x,s=e.y-t.y,n=Math.sqrt(i*i+s*s);let o=Math.atan2(s,i);return o<-.5*C&&(o+=O),{angle:o,distance:n}}function q(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function K(t,e){return(t-e+A)%O-C}function G(t){return(t%O+O)%O}function Z(t,e,i,s){const n=G(t),o=G(e),a=G(i),r=G(o-n),l=G(a-n),h=G(n-o),c=G(n-a);return n===o||n===a||s&&o===a||r>l&&h<c}function J(t,e,i){return Math.max(e,Math.min(i,t))}function Q(t){return J(t,-32768,32767)}function tt(t,e,i,s=1e-6){return t>=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]<e);let s,n=t.length-1,o=0;for(;n-o>1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return n<i||n===i&&t[s+1][e]===i}:s=>t[s][e]<i),st=(t,e,i)=>et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;s<n&&t[s]<e;)s++;for(;n>s&&t[n-1]>i;)n--;return s>0||n<t.length?t.slice(s,n):t}const ot=["push","pop","shift","splice","unshift"];function at(t,e){t._chartjs?t._chartjs.listeners.push(e):(Object.defineProperty(t,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),ot.forEach((e=>{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{"function"==typeof t[i]&&t[i](...e)})),n}})})))}function rt(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ot.forEach((e=>{delete t[e]})),delete t._chartjs)}function lt(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const ht="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function ct(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,ht.call(window,(()=>{s=!1,t.apply(e,i)})))}}function dt(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const ut=t=>"start"===t?"left":"end"===t?"right":"center",ft=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,gt=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;function pt(t,e,i){const n=e.length;let o=0,a=n;if(t._sorted){const{iScale:r,vScale:l,_parsed:h}=t,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,d=r.axis,{min:u,max:f,minDefined:g,maxDefined:p}=r.getUserBounds();if(g){if(o=Math.min(it(h,d,u).lo,i?n:it(e,d,r.getPixelForValue(u)).lo),c){const t=h.slice(0,o+1).reverse().findIndex((t=>!s(t[l.axis])));o-=Math.max(0,t)}o=J(o,0,n-1)}if(p){let t=Math.max(it(h,r.axis,f,!0).hi+1,i?0:it(e,d,r.getPixelForValue(f),!0).hi+1);if(c){const e=h.slice(t-1).findIndex((t=>!s(t[l.axis])));t+=Math.max(0,e)}a=J(t,o,n)-o}else a=n-o}return{start:o,count:a}}function mt(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}class xt{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=ht.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,"progress")),n.length||(i.running=!1,this._notify(s,i,t,"complete"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var bt=new xt;
-/*!
- * @kurkle/color v0.3.2
- * https://github.com/kurkle/color#readme
- * (c) 2023 Jukka Kurkela
- * Released under the MIT License
- */function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e<i?6:0):e===n?(i-t)/s+2:(t-e)/s+4}(e,i,s,h,n),r=60*r+.5),[0|r,l||0,a]}function zt(t,e,i,s){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,i,s)).map(Mt)}function Ft(t,e,i){return zt(Lt,t,e,i)}function Vt(t){return(t%360+360)%360}function Bt(t){const e=Tt.exec(t);let i,s=255;if(!e)return;e[5]!==i&&(s=e[6]?vt(+e[5]):Mt(+e[5]));const n=Vt(+e[2]),o=+e[3]/100,a=+e[4]/100;return i="hwb"===e[1]?function(t,e,i){return zt(Rt,t,e,i)}(n,o,a):"hsv"===e[1]?function(t,e,i){return zt(Et,t,e,i)}(n,o,a):Ft(n,o,a),{r:i[0],g:i[1],b:i[2],a:s}}const Wt={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},Nt={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};let Ht;function jt(t){Ht||(Ht=function(){const t={},e=Object.keys(Nt),i=Object.keys(Wt);let s,n,o,a,r;for(s=0;s<e.length;s++){for(a=r=e[s],n=0;n<i.length;n++)o=i[n],r=r.replace(o,Wt[o]);o=parseInt(Nt[a],16),t[r]=[o>>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=Ft(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function qt(t,e){return t?Object.assign(e||{},t):t}function Kt(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Mt(t[3]))):(e=qt(t,{r:0,g:0,b:0,a:1})).a=Mt(e.a),e}function Gt(t){return"r"===t.charAt(0)?function(t){const e=$t.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=e[8]?vt(t):yt(255*t,0,255)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?vt(i):yt(i,0,255)),s=255&(e[4]?vt(s):yt(s,0,255)),n=255&(e[6]?vt(n):yt(n,0,255)),{r:i,g:s,b:n,a:o}}}(t):Bt(t)}class Zt{constructor(t){if(t instanceof Zt)return t;const e=typeof t;let i;var s,n,o;"object"===e?i=Kt(t):"string"===e&&(o=(s=t).length,"#"===s[0]&&(4===o||5===o?n={r:255&17*St[s[1]],g:255&17*St[s[2]],b:255&17*St[s[3]],a:5===o?17*St[s[4]]:255}:7!==o&&9!==o||(n={r:St[s[1]]<<4|St[s[2]],g:St[s[3]]<<4|St[s[4]],b:St[s[5]]<<4|St[s[6]],a:9===o?St[s[7]]<<4|St[s[8]]:255})),i=n||jt(t)||Gt(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=qt(this._rgb);return t&&(t.a=wt(t.a)),t}set rgb(t){this._rgb=Kt(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${wt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?At(this._rgb):void 0}hslString(){return this._valid?function(t){if(!t)return;const e=It(t),i=e[0],s=kt(e[1]),n=kt(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${wt(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):void 0}mix(t,e){if(t){const i=this.rgb,s=t.rgb;let n;const o=e===n?.5:e,a=2*o-1,r=i.a-s.a,l=((a*r==-1?a:(a+r)/(1+a*r))+1)/2;n=1-l,i.r=255&l*i.r+n*s.r+.5,i.g=255&l*i.g+n*s.g+.5,i.b=255&l*i.b+n*s.b+.5,i.a=o*i.a+(1-o)*s.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,i){const s=Ut(wt(t.r)),n=Ut(wt(t.g)),o=Ut(wt(t.b));return{r:Mt(Yt(s+i*(Ut(wt(e.r))-s))),g:Mt(Yt(n+i*(Ut(wt(e.g))-n))),b:Mt(Yt(o+i*(Ut(wt(e.b))-o))),a:t.a+i*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new Zt(this.rgb)}alpha(t){return this._rgb.a=Mt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=_t(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Xt(this._rgb,2,t),this}darken(t){return Xt(this._rgb,2,-t),this}saturate(t){return Xt(this._rgb,1,t),this}desaturate(t){return Xt(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=It(t);i[0]=Vt(i[0]+e),i=Ft(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function Jt(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function Qt(t){return Jt(t)?t:new Zt(t)}function te(t){return Jt(t)?t:new Zt(t).saturate(.5).darken(.1).hexString()}const ee=["x","y","borderWidth","radius","tension"],ie=["color","borderColor","backgroundColor"];const se=new Map;function ne(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=se.get(i);return s||(s=new Intl.NumberFormat(t,e),se.set(i,s)),s}(e,i).format(t)}const oe={values:t=>n(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n="scientific"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=z(Math.abs(o)),r=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),ne(t,s,l)},logarithmic(t,e,i){if(0===t)return"0";const s=i[e].significand||t/Math.pow(10,Math.floor(z(t)));return[1,2,3,5,10,15].includes(s)||e>.8*i.length?oe.numeric.call(this,t,e,i):""}};var ae={formatters:oe};const re=Object.create(null),le=Object.create(null);function he(t,e){if(!e)return t;const i=e.split(".");for(let e=0,s=i.length;e<s;++e){const s=i[e];t=t[s]||(t[s]=Object.create(null))}return t}function ce(t,e,i){return"string"==typeof e?x(he(t,e),i):x(he(t,""),e)}class de{constructor(t,e){this.animation=void 0,this.backgroundColor="rgba(0,0,0,0.1)",this.borderColor="rgba(0,0,0,0.1)",this.color="#666",this.datasets={},this.devicePixelRatio=t=>t.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>te(e.backgroundColor),this.hoverBorderColor=(t,e)=>te(e.borderColor),this.hoverColor=(t,e)=>te(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return ce(this,t,e)}get(t){return he(this,t)}describe(t,e){return ce(le,t,e)}override(t,e){return ce(re,t,e)}route(t,e,i,s){const n=he(this,t),a=he(this,i),r="_"+e;Object.defineProperties(n,{[r]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[r],e=a[s];return o(t)?Object.assign({},e,t):l(t,e)},set(t){this[r]=t}}})}apply(t){t.forEach((t=>t(this)))}}var ue=new de({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:ie},numbers:{type:"number",properties:ee}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ae.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function fe(){return"undefined"!=typeof window&&"undefined"!=typeof document}function ge(t){let e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e}function pe(t,e,i){let s;return"string"==typeof t?(s=parseInt(t,10),-1!==t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}const me=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function xe(t,e){return me(t).getPropertyValue(e)}const be=["top","right","bottom","left"];function _e(t,e,i){const s={};i=i?"-"+i:"";for(let n=0;n<4;n++){const o=be[n];s[o]=parseFloat(t[e+"-"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}const ye=(t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot);function ve(t,e){if("native"in t)return t;const{canvas:i,currentDevicePixelRatio:s}=e,n=me(i),o="border-box"===n.boxSizing,a=_e(n,"padding"),r=_e(n,"border","width"),{x:l,y:h,box:c}=function(t,e){const i=t.touches,s=i&&i.length?i[0]:t,{offsetX:n,offsetY:o}=s;let a,r,l=!1;if(ye(n,o,t.target))a=n,r=o;else{const t=e.getBoundingClientRect();a=s.clientX-t.left,r=s.clientY-t.top,l=!0}return{x:a,y:r,box:l}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const Me=t=>Math.round(10*t)/10;function we(t,e,i,s){const n=me(t),o=_e(n,"margin"),a=pe(n.maxWidth,t,"clientWidth")||T,r=pe(n.maxHeight,t,"clientHeight")||T,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=t&&ge(t);if(o){const t=o.getBoundingClientRect(),a=me(o),r=_e(a,"border","width"),l=_e(a,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=pe(a.maxWidth,o,"clientWidth"),n=pe(a.maxHeight,o,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||T,maxHeight:n||T}}(t,e,i);let{width:h,height:c}=l;if("content-box"===n.boxSizing){const t=_e(n,"border","width"),e=_e(n,"padding");h-=e.width+t.width,c-=e.height+t.height}h=Math.max(0,h-o.width),c=Math.max(0,s?h/s:c-o.height),h=Me(Math.min(h,a,l.maxWidth)),c=Me(Math.min(c,r,l.maxHeight)),h&&!c&&(c=Me(h/2));return(void 0!==e||void 0!==i)&&s&&l.height&&c>l.height&&(c=l.height,h=Me(Math.floor(c*s))),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Math.floor(t.height*s),o=Math.floor(t.width*s);t.height=Math.floor(t.height),t.width=Math.floor(t.width);const a=t.canvas;return a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`),(t.currentDevicePixelRatio!==s||a.height!==n||a.width!==o)&&(t.currentDevicePixelRatio=s,a.height=n,a.width=o,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};fe()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch(t){}return t}();function Pe(t,e){const i=xe(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function De(t){return!t||s(t.size)||s(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Ce(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function Oe(t,e,i,s){let o=(s=s||{}).data=s.data||{},a=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(o=s.data={},a=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let r=0;const l=i.length;let h,c,d,u,f;for(h=0;h<l;h++)if(u=i[h],null==u||n(u)){if(n(u))for(c=0,d=u.length;c<d;c++)f=u[c],null==f||n(f)||(r=Ce(t,o,a,r,f))}else r=Ce(t,o,a,r,u);t.restore();const g=a.length/2;if(g>i.length){for(h=0;h<g;h++)delete o[a[h]];a.splice(0,g)}return r}function Ae(t,e,i){const s=t.currentDevicePixelRatio,n=0!==i?Math.max(i/2,.5):0;return Math.round((e-n)*s)/s+n}function Te(t,e){(e||t)&&((e=e||t.getContext("2d")).save(),e.resetTransform(),e.clearRect(0,0,t.width,t.height),e.restore())}function Le(t,e,i,s){Ee(t,e,i,s,null)}function Ee(t,e,i,s,n){let o,a,r,l,h,c,d,u;const f=e.pointStyle,g=e.rotation,p=e.radius;let m=(g||0)*L;if(f&&"object"==typeof f&&(o=f.toString(),"[object HTMLImageElement]"===o||"[object HTMLCanvasElement]"===o))return t.save(),t.translate(i,s),t.rotate(m),t.drawImage(f,-f.width/2,-f.height/2,f.width,f.height),void t.restore();if(!(isNaN(p)||p<=0)){switch(t.beginPath(),f){default:n?t.ellipse(i,s,n/2,p,0,0,O):t.arc(i,s,p,0,O),t.closePath();break;case"triangle":c=n?n/2:p,t.moveTo(i+Math.sin(m)*c,s-Math.cos(m)*p),m+=I,t.lineTo(i+Math.sin(m)*c,s-Math.cos(m)*p),m+=I,t.lineTo(i+Math.sin(m)*c,s-Math.cos(m)*p),t.closePath();break;case"rectRounded":h=.516*p,l=p-h,a=Math.cos(m+R)*l,d=Math.cos(m+R)*(n?n/2-h:l),r=Math.sin(m+R)*l,u=Math.sin(m+R)*(n?n/2-h:l),t.arc(i-d,s-r,h,m-C,m-E),t.arc(i+u,s-a,h,m-E,m),t.arc(i+d,s+r,h,m,m+E),t.arc(i-u,s+a,h,m+E,m+C),t.closePath();break;case"rect":if(!g){l=Math.SQRT1_2*p,c=n?n/2:l,t.rect(i-c,s-l,2*c,2*l);break}m+=R;case"rectRot":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+u,s-a),t.lineTo(i+d,s+r),t.lineTo(i-u,s+a),t.closePath();break;case"crossRot":m+=R;case"cross":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a);break;case"star":d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a),m+=R,d=Math.cos(m)*(n?n/2:p),a=Math.cos(m)*p,r=Math.sin(m)*p,u=Math.sin(m)*(n?n/2:p),t.moveTo(i-d,s-r),t.lineTo(i+d,s+r),t.moveTo(i+u,s-a),t.lineTo(i-u,s+a);break;case"line":a=n?n/2:Math.cos(m)*p,r=Math.sin(m)*p,t.moveTo(i-a,s-r),t.lineTo(i+a,s+r);break;case"dash":t.moveTo(i,s),t.lineTo(i+Math.cos(m)*(n?n/2:p),s+Math.sin(m)*p);break;case!1:t.closePath()}t.fill(),e.borderWidth>0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.x<e.right+i&&t.y>e.top-i&&t.y<e.bottom+i}function Ie(t,e){t.save(),t.beginPath(),t.rect(e.left,e.top,e.right-e.left,e.bottom-e.top),t.clip()}function ze(t){t.restore()}function Fe(t,e,i,s,n){if(!e)return t.lineTo(i.x,i.y);if("middle"===n){const s=(e.x+i.x)/2;t.lineTo(s,e.y),t.lineTo(s,i.y)}else"after"===n!=!!s?t.lineTo(e.x,i.y):t.lineTo(i.x,e.y);t.lineTo(i.x,i.y)}function Ve(t,e,i,s){if(!e)return t.lineTo(i.x,i.y);t.bezierCurveTo(s?e.cp1x:e.cp2x,s?e.cp1y:e.cp2y,s?i.cp2x:i.cp1x,s?i.cp2y:i.cp1y,i.x,i.y)}function Be(t,e,i,s,n){if(n.strikethrough||n.underline){const o=t.measureText(s),a=e-o.actualBoundingBoxLeft,r=e+o.actualBoundingBoxRight,l=i-o.actualBoundingBoxAscent,h=i+o.actualBoundingBoxDescent,c=n.strikethrough?(l+h)/2:h;t.strokeStyle=t.fillStyle,t.beginPath(),t.lineWidth=n.decorationWidth||2,t.moveTo(a,c),t.lineTo(r,c),t.stroke()}}function We(t,e){const i=t.fillStyle;t.fillStyle=e.color,t.fillRect(e.left,e.top,e.width,e.height),t.fillStyle=i}function Ne(t,e,i,o,a,r={}){const l=n(e)?e:[e],h=r.strokeWidth>0&&""!==r.strokeColor;let c,d;for(t.save(),t.font=a.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),s(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,r),c=0;c<l.length;++c)d=l[c],r.backdrop&&We(t,r.backdrop),h&&(r.strokeColor&&(t.strokeStyle=r.strokeColor),s(r.strokeWidth)||(t.lineWidth=r.strokeWidth),t.strokeText(d,i,o,r.maxWidth)),t.fillText(d,i,o,r.maxWidth),Be(t,i,o,d,r),o+=Number(a.lineHeight);t.restore()}function He(t,e){const{x:i,y:s,w:n,h:o,radius:a}=e;t.arc(i+a.topLeft,s+a.topLeft,a.topLeft,1.5*C,C,!0),t.lineTo(i,s+o-a.bottomLeft),t.arc(i+a.bottomLeft,s+o-a.bottomLeft,a.bottomLeft,C,E,!0),t.lineTo(i+n-a.bottomRight,s+o),t.arc(i+n-a.bottomRight,s+o-a.bottomRight,a.bottomRight,E,0,!0),t.lineTo(i+n,s+a.topRight),t.arc(i+n-a.topRight,s+a.topRight,a.topRight,0,-E,!0),t.lineTo(i+a.topLeft,s)}function je(t,e=[""],i,s,n=(()=>t[0])){const o=i||t;void 0===s&&(s=ti("_fallback",t));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:s,_getTarget:n,override:i=>je([i,...t],e,o,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>qe(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=ti(Ue(o,t),i),void 0!==n)return Xe(t,n)?Je(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(t,e,i,s){const a={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ye(t,s),setContext:e=>$e(t,e,i,s),override:n=>$e(t.override(n),e,i,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>qe(t,e,(()=>function(t,e,i){const{_proxy:s,_context:a,_subProxy:r,_descriptors:l}=t;let h=s[e];S(h)&&l.isScriptable(e)&&(h=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error("Recursion detected: "+Array.from(r).join("->")+"->"+t);r.add(t);let l=e(o,a||s);r.delete(t),Xe(t,l)&&(l=Je(n._scopes,n,t,l));return l}(e,h,t,i));n(h)&&h.length&&(h=function(t,e,i,s){const{_proxy:n,_context:a,_subProxy:r,_descriptors:l}=i;if(void 0!==a.index&&s(t))return e[a.index%e.length];if(o(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const o of i){const i=Je(s,n,t,o);e.push($e(i,a,r&&r[t],l))}}return e}(e,h,t,l.isIndexable));Xe(e,h)&&(h=$e(h,a,r&&r[e],l));return h}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function Ye(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:S(i)?i:()=>i,isIndexable:S(s)?s:()=>s}}const Ue=(t,e)=>t?t+w(e):e,Xe=(t,e)=>o(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function qe(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e)||"constructor"===e)return t[e];const s=i();return t[e]=s,s}function Ke(t,e,i){return S(t)?t(e,i):t}const Ge=(t,e)=>!0===t?e:"string"==typeof t?M(e,t):void 0;function Ze(t,e,i,s,n){for(const o of e){const e=Ge(i,o);if(e){t.add(e);const o=Ke(e._fallback,i,n);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}return!1}function Je(t,e,i,s){const a=e._rootScopes,r=Ke(e._fallback,i,s),l=[...t,...a],h=new Set;h.add(s);let c=Qe(h,l,i,r||i,s);return null!==c&&((void 0===r||r===i||(c=Qe(h,l,r,c,s),null!==c))&&je(Array.from(h),[""],a,r,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const a=s[e];if(n(a)&&o(i))return i;return a||{}}(e,i,s))))}function Qe(t,e,i,s,n){for(;i;)i=Ze(t,e,i,s,n);return i}function ti(t,e){for(const i of e){if(!i)continue;const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith("_"))))e.add(t);return Array.from(e)}(t._scopes)),e}function ii(t,e,i,s){const{iScale:n}=t,{key:o="r"}=this._parsing,a=new Array(s);let r,l,h,c;for(r=0,l=s;r<l;++r)h=r+i,c=e[h],a[r]={r:n.parse(M(c,o),h)};return a}const si=Number.EPSILON||1e-14,ni=(t,e)=>e<t.length&&!t[e].skip&&t[e],oi=t=>"x"===t?"y":"x";function ai(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=q(o,n),l=q(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function ri(t,e="x"){const i=oi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=ni(t,0);for(a=0;a<s;++a)if(r=l,l=h,h=ni(t,a+1),l){if(h){const t=h[e]-l[e];n[a]=0!==t?(h[i]-l[i])/t:0}o[a]=r?h?F(n[a-1])!==F(n[a])?0:(n[a-1]+n[a])/2:n[a-1]:n[a]}!function(t,e,i){const s=t.length;let n,o,a,r,l,h=ni(t,0);for(let c=0;c<s-1;++c)l=h,h=ni(t,c+1),l&&h&&(V(e[c],0,si)?i[c]=i[c+1]=0:(n=i[c]/e[c],o=i[c+1]/e[c],r=Math.pow(n,2)+Math.pow(o,2),r<=9||(a=3/Math.sqrt(r),i[c]=n*a*e[c],i[c+1]=o*a*e[c])))}(t,n,o),function(t,e,i="x"){const s=oi(i),n=t.length;let o,a,r,l=ni(t,0);for(let h=0;h<n;++h){if(a=r,r=l,l=ni(t,h+1),!r)continue;const n=r[i],c=r[s];a&&(o=(n-a[i])/3,r[`cp1${i}`]=n-o,r[`cp1${s}`]=c-o*e[h]),l&&(o=(l[i]-n)/3,r[`cp2${i}`]=n+o,r[`cp2${s}`]=c+o*e[h])}}(t,o,e)}function li(t,e,i){return Math.max(Math.min(t,i),e)}function hi(t,e,i,s,n){let o,a,r,l;if(e.spanGaps&&(t=t.filter((t=>!t.skip))),"monotone"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o<a;++o)r=t[o],l=ai(i,r,t[Math.min(o+1,a-(s?0:1))%a],e.tension),r.cp1x=l.previous.x,r.cp1y=l.previous.y,r.cp2x=l.next.x,r.cp2y=l.next.y,i=r}e.capBezierPoints&&function(t,e){let i,s,n,o,a,r=Re(t[0],e);for(i=0,s=t.length;i<s;++i)a=o,o=r,r=i<s-1&&Re(t[i+1],e),o&&(n=t[i],a&&(n.cp1x=li(n.cp1x,e.left,e.right),n.cp1y=li(n.cp1y,e.top,e.bottom)),r&&(n.cp2x=li(n.cp2x,e.left,e.right),n.cp2y=li(n.cp2y,e.top,e.bottom)))}(t,i)}const ci=t=>0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*O/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*O/i)+1,fi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*E),easeOutSine:t=>Math.sin(t*E),easeInOutSine:t=>-.5*(Math.cos(C*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){const e=.1125;return ci(t)?t:t<.5?.5*di(2*t,e,.45):.5+.5*ui(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-fi.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*fi.easeInBounce(2*t):.5*fi.easeOutBounce(2*t-1)+.5};function gi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:"middle"===s?i<.5?t.y:e.y:"after"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function mi(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=gi(t,n,i),r=gi(n,o,i),l=gi(o,e,i),h=gi(a,r,i),c=gi(r,l,i);return gi(h,c,i)}const xi=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,bi=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function _i(t,e){const i=(""+t).match(xi);if(!i||"normal"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case"px":return t;case"%":t/=100}return e*t}const yi=t=>+t||0;function vi(t,e){const i={},s=o(e),n=s?Object.keys(e):e,a=o(t)?s?i=>l(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=yi(a(t));return i}function Mi(t){return vi(t,{top:"y",right:"x",bottom:"y",left:"x"})}function wi(t){return vi(t,["topLeft","topRight","bottomLeft","bottomRight"])}function ki(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Si(t,e){t=t||{},e=e||ue.font;let i=l(t.size,e.size);"string"==typeof i&&(i=parseInt(i,10));let s=l(t.style,e.style);s&&!(""+s).match(bi)&&(console.warn('Invalid font style specified: "'+s+'"'),s=void 0);const n={family:l(t.family,e.family),lineHeight:_i(l(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:l(t.weight,e.weight),string:""};return n.string=De(n),n}function Pi(t,e,i,s){let o,a,r,l=!0;for(o=0,a=t.length;o<a;++o)if(r=t[o],void 0!==r&&(void 0!==e&&"function"==typeof r&&(r=r(e),l=!1),void 0!==i&&n(r)&&(r=r[i%r.length],l=!1),void 0!==r))return s&&!l&&(s.cacheable=!1),r}function Di(t,e,i){const{min:s,max:n}=t,o=c(e,(n-s)/2),a=(t,e)=>i&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ci(t,e){return Object.assign(Object.create(t),e)}function Oi(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ai(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(i=t.canvas.style,s=[i.getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function Ti(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Li(t){return"angle"===t?{between:Z,compare:K,normalize:G}:{between:tt,compare:(t,e)=>t-e,normalize:t=>t}}function Ei({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Ri(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Li(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Li(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;h<c&&a(r(e[d%l][s]),n,o);++h)d--,u--;d%=l,u%=l}return u<d&&(u+=l),{start:d,end:u,loop:f,style:t.style}}(t,e,i),g=[];let p,m,x,b=!1,_=null;const y=()=>b||l(n,x,p)&&0!==r(n,x),v=()=>!b||0===r(o,p)||l(o,x,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==x&&(b=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Ei({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,x=p));return null!==_&&g.push(Ei({start:_,end:d,loop:u,count:a,style:f})),g}function Ii(t,e){const i=[],s=t.segments;for(let n=0;n<s.length;n++){const o=Ri(s[n],t.points,e);o.length&&i.push(...o)}return i}function zi(t,e){const i=t.points,s=t.options.spanGaps,n=i.length;if(!n)return[];const o=!!t._loop,{start:a,end:r}=function(t,e,i,s){let n=0,o=e-1;if(i&&!s)for(;n<e&&!t[n].skip;)n++;for(;n<e&&t[n].skip;)n++;for(n%=e,i&&(o+=n);o>n&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Fi(t,[{start:a,end:r,loop:o}],i,e);return Fi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,r<a?r+n:r,!!t._fullLoop&&0===a&&r===n-1),i,e)}function Fi(t,e,i,s){return s&&s.setContext&&i?function(t,e,i,s){const n=t._chart.getContext(),o=Vi(t.options),{_datasetIndex:a,options:{spanGaps:r}}=t,l=i.length,h=[];let c=o,d=e[0].start,u=d;function f(t,e,s,n){const o=r?-1:1;if(t!==e){for(t+=l;i[t%l].skip;)t-=o;for(;i[e%l].skip;)e+=o;t%l!=e%l&&(h.push({start:t%l,end:e%l,loop:s,style:n}),c=n,d=e%l)}}for(const t of e){d=r?d:t.start;let e,o=i[d%l];for(u=d+1;u<=t.end;u++){const r=i[u%l];e=Vi(s.setContext(Ci(n,{type:"segment",p0:o,p1:r,p0DataIndex:(u-1)%l,p1DataIndex:u%l,datasetIndex:a}))),Bi(e,c)&&f(d,u-1,t.loop,c),o=r,c=e}d<u-1&&f(d,u-1,t.loop,c)}return h}(t,e,i,s):e}function Vi(t){return{backgroundColor:t.backgroundColor,borderCapStyle:t.borderCapStyle,borderDash:t.borderDash,borderDashOffset:t.borderDashOffset,borderJoinStyle:t.borderJoinStyle,borderWidth:t.borderWidth,borderColor:t.borderColor}}function Bi(t,e){if(!e)return!1;const i=[],s=function(t,e){return Jt(e)?(i.includes(e)||i.push(e),i.indexOf(e)):e};return JSON.stringify(t,s)!==JSON.stringify(e,s)}function Wi(t,e,i){return t.options.clip?t[i]:e[i]}function Ni(t,e){const i=e._clip;if(i.disabled)return!1;const s=function(t,e){const{xScale:i,yScale:s}=t;return i&&s?{left:Wi(i,e,"left"),right:Wi(i,e,"right"),top:Wi(s,e,"top"),bottom:Wi(s,e,"bottom")}:e}(e,t.chartArea);return{left:!1===i.left?0:s.left-(!0===i.left?0:i.left),right:!1===i.right?t.width:s.right+(!0===i.right?0:i.right),top:!1===i.top?0:s.top-(!0===i.top?0:i.top),bottom:!1===i.bottom?t.height:s.bottom+(!0===i.bottom?0:i.bottom)}}var Hi=Object.freeze({__proto__:null,HALF_PI:E,INFINITY:T,PI:C,PITAU:A,QUARTER_PI:R,RAD_PER_DEG:L,TAU:O,TWO_THIRDS_PI:I,_addGrace:Di,_alignPixel:Ae,_alignStartEnd:ft,_angleBetween:Z,_angleDiff:K,_arrayUnique:lt,_attachContext:$e,_bezierCurveTo:Ve,_bezierInterpolation:mi,_boundSegment:Ri,_boundSegments:Ii,_capitalize:w,_computeSegments:zi,_createResolver:je,_decimalPlaces:U,_deprecated:function(t,e,i,s){void 0!==e&&console.warn(t+': "'+i+'" is deprecated. Please use "'+s+'" instead')},_descriptors:Ye,_elementsEqual:f,_factorize:W,_filterBetween:nt,_getParentNode:ge,_getStartAndCountOfVisiblePoints:pt,_int16Range:Q,_isBetween:tt,_isClickEvent:D,_isDomSupported:fe,_isPointInArea:Re,_limitValue:J,_longestText:Oe,_lookup:et,_lookupByKey:it,_measureText:Ce,_merger:m,_mergerIf:_,_normalizeAngle:G,_parseObjectDataRadialScale:ii,_pointInLine:gi,_readValueToProps:vi,_rlookupByKey:st,_scaleRangesChanged:mt,_setMinAndMaxByKey:j,_splitKey:v,_steppedInterpolation:pi,_steppedLineTo:Fe,_textX:gt,_toLeftRightCenter:ut,_updateBezierControlPoints:hi,addRoundedRectPath:He,almostEquals:V,almostWhole:H,callback:d,clearCanvas:Te,clipArea:Ie,clone:g,color:Qt,createContext:Ci,debounce:dt,defined:k,distanceBetweenPoints:q,drawPoint:Le,drawPointLegend:Ee,each:u,easingEffects:fi,finiteOrDefault:r,fontString:function(t,e,i){return e+" "+t+"px "+i},formatNumber:ne,getAngleFromPoint:X,getDatasetClipArea:Ni,getHoverColor:te,getMaximumSize:we,getRelativePosition:ve,getRtlAdapter:Oi,getStyle:xe,isArray:n,isFinite:a,isFunction:S,isNullOrUndef:s,isNumber:N,isObject:o,isPatternOrGradient:Jt,listenArrayEvents:at,log10:z,merge:x,mergeIf:b,niceNum:B,noop:e,overrideTextDirection:Ai,readUsedSize:Pe,renderText:Ne,requestAnimFrame:ht,resolve:Pi,resolveObjectKey:M,restoreTextDirection:Ti,retinaScale:ke,setsEqual:P,sign:F,splineCurve:ai,splineCurveMonotone:ri,supportsEventListenerOptions:Se,throttled:ct,toDegrees:Y,toDimension:c,toFont:Si,toFontString:De,toLineHeight:_i,toPadding:ki,toPercentage:h,toRadians:$,toTRBL:Mi,toTRBLCorners:wi,uid:i,unclipArea:ze,unlistenArrayEvents:rt,valueOrDefault:l});function ji(t,e,i,n){const{controller:o,data:a,_sorted:r}=t,l=o._cachedMeta.iScale,h=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null;if(l&&e===l.axis&&"r"!==e&&r&&a.length){const r=l._reversePixels?st:it;if(!n){const n=r(a,e,i);if(h){const{vScale:e}=o._cachedMeta,{_parsed:i}=t,a=i.slice(0,n.lo+1).reverse().findIndex((t=>!s(t[e.axis])));n.lo-=Math.max(0,a);const r=i.slice(n.hi).findIndex((t=>!s(t[e.axis])));n.hi+=Math.max(0,r)}return n}if(o._sharedOptions){const t=a[0],s="function"==typeof t.getRange&&t.getRange(e);if(s){const t=r(a,e,i-s),n=r(a,e,i+s);return{lo:t.lo,hi:n.hi}}}}return{lo:0,hi:a.length-1}}function $i(t,e,i,s,n){const o=t.getSortedVisibleDatasetMetas(),a=i[e];for(let t=0,i=o.length;t<i;++t){const{index:i,data:r}=o[t],{lo:l,hi:h}=ji(o[t],e,a,n);for(let t=l;t<=h;++t){const e=r[t];e.skip||s(e,i,t)}}}function Yi(t,e,i,s,n){const o=[];if(!n&&!t.isPointInArea(e))return o;return $i(t,i,e,(function(i,a,r){(n||Re(i,t.chartArea,0))&&i.inRange(e.x,e.y,s)&&o.push({element:i,datasetIndex:a,index:r})}),!0),o}function Ui(t,e,i,s,n,o){let a=[];const r=function(t){const e=-1!==t.indexOf("x"),i=-1!==t.indexOf("y");return function(t,s){const n=e?Math.abs(t.x-s.x):0,o=i?Math.abs(t.y-s.y):0;return Math.sqrt(Math.pow(n,2)+Math.pow(o,2))}}(i);let l=Number.POSITIVE_INFINITY;return $i(t,i,e,(function(i,h,c){const d=i.inRange(e.x,e.y,n);if(s&&!d)return;const u=i.getCenterPoint(n);if(!(!!o||t.isPointInArea(u))&&!d)return;const f=r(e,u);f<l?(a=[{element:i,datasetIndex:h,index:c}],l=f):f===l&&a.push({element:i,datasetIndex:h,index:c})})),a}function Xi(t,e,i,s,n,o){return o||t.isPointInArea(e)?"r"!==i||s?Ui(t,e,i,s,n,o):function(t,e,i,s){let n=[];return $i(t,i,e,(function(t,i,o){const{startAngle:a,endAngle:r}=t.getProps(["startAngle","endAngle"],s),{angle:l}=X(t,{x:e.x,y:e.y});Z(l,a,r)&&n.push({element:t,datasetIndex:i,index:o})})),n}(t,e,i,n):[]}function qi(t,e,i,s,n){const o=[],a="x"===i?"inXRange":"inYRange";let r=!1;return $i(t,i,e,((t,s,l)=>{t[a]&&t[a](e[i],n)&&(o.push({element:t,datasetIndex:s,index:l}),r=r||t.inRange(e.x,e.y,n))})),s&&!r?[]:o}var Ki={evaluateInteractionItems:$i,modes:{index(t,e,i,s){const n=ve(e,t),o=i.axis||"x",a=i.includeInvisible||!1,r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})})),l):[]},dataset(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;let r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a);if(r.length>0){const e=r[0].datasetIndex,i=t.getDatasetMeta(e).data;r=[];for(let t=0;t<i.length;++t)r.push({element:i[t],datasetIndex:e,index:t})}return r},point:(t,e,i,s)=>Yi(t,ve(e,t),i.axis||"xy",s,i.includeInvisible||!1),nearest(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;return Xi(t,n,o,i.intersect,s,a)},x:(t,e,i,s)=>qi(t,ve(e,t),"x",i.intersect,s),y:(t,e,i,s)=>qi(t,ve(e,t),"y",i.intersect,s)}};const Gi=["left","top","right","bottom"];function Zi(t,e){return t.filter((t=>t.pos===e))}function Ji(t,e){return t.filter((t=>-1===Gi.indexOf(t.pos)&&t.box.axis===e))}function Qi(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function ts(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!Gi.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o<a;++o){r=t[o];const{fullSize:a}=r.box,l=i[r.stack],h=l&&r.stackWeight/l.weight;r.horizontal?(r.width=h?h*s:a&&e.availableWidth,r.height=n):(r.width=s,r.height=h?h*n:a&&e.availableHeight)}return i}function es(t,e,i,s){return Math.max(t[i],e[i])+Math.max(t[s],e[s])}function is(t,e){t.top=Math.max(t.top,e.top),t.left=Math.max(t.left,e.left),t.bottom=Math.max(t.bottom,e.bottom),t.right=Math.max(t.right,e.right)}function ss(t,e,i,s){const{pos:n,box:a}=i,r=t.maxPadding;if(!o(n)){i.size&&(t[n]-=i.size);const e=s[i.stack]||{size:0,count:1};e.size=Math.max(e.size,i.horizontal?a.height:a.width),i.size=e.size/e.count,t[n]+=i.size}a.getPadding&&is(r,a.getPadding());const l=Math.max(0,e.outerWidth-es(r,t,"left","right")),h=Math.max(0,e.outerHeight-es(r,t,"top","bottom")),c=l!==t.w,d=h!==t.h;return t.w=l,t.h=h,i.horizontal?{same:c,other:d}:{same:d,other:c}}function ns(t,e){const i=e.maxPadding;function s(t){const s={left:0,top:0,right:0,bottom:0};return t.forEach((t=>{s[t]=Math.max(e[t],i[t])})),s}return s(t?["left","right"]:["top","bottom"])}function os(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;o<a;++o){r=t[o],l=r.box,l.update(r.width||e.w,r.height||e.h,ns(r.horizontal,e));const{same:a,other:d}=ss(e,i,r,s);h|=a&&n.length,c=c||d,l.fullSize||n.push(r)}return h&&os(n,e,i,s)||c}function as(t,e,i,s,n){t.top=i,t.left=e,t.right=e+s,t.bottom=i+n,t.width=s,t.height=n}function rs(t,e,i,s){const n=i.padding;let{x:o,y:a}=e;for(const r of t){const t=r.box,l=s[r.stack]||{count:1,placed:0,weight:1},h=r.stackWeight/l.weight||1;if(r.horizontal){const s=e.w*h,o=l.size||t.height;k(l.start)&&(a=l.start),t.fullSize?as(t,n.left,a,i.outerWidth-n.right-n.left,o):as(t,e.left+l.placed,a,s,o),l.start=a,l.placed+=s,a=t.bottom}else{const s=e.h*h,a=l.size||t.width;k(l.start)&&(o=l.start),t.fullSize?as(t,o,n.top,a,i.outerHeight-n.bottom-n.top):as(t,o,e.top+l.placed,a,s),l.start=o,l.placed+=s,o=t.right}}e.x=o,e.y=a}var ls={addBox(t,e){t.boxes||(t.boxes=[]),e.fullSize=e.fullSize||!1,e.position=e.position||"top",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw(t){e.draw(t)}}]},t.boxes.push(e)},removeBox(t,e){const i=t.boxes?t.boxes.indexOf(e):-1;-1!==i&&t.boxes.splice(i,1)},configure(t,e,i){e.fullSize=i.fullSize,e.position=i.position,e.weight=i.weight},update(t,e,i,s){if(!t)return;const n=ki(t.options.layout.padding),o=Math.max(e-n.width,0),a=Math.max(i-n.height,0),r=function(t){const e=function(t){const e=[];let i,s,n,o,a,r;for(i=0,s=(t||[]).length;i<s;++i)n=t[i],({position:o,options:{stack:a,stackWeight:r=1}}=n),e.push({index:i,box:n,pos:o,horizontal:n.isHorizontal(),weight:n.weight,stack:a&&o+a,stackWeight:r});return e}(t),i=Qi(e.filter((t=>t.box.fullSize)),!0),s=Qi(Zi(e,"left"),!0),n=Qi(Zi(e,"right")),o=Qi(Zi(e,"top"),!0),a=Qi(Zi(e,"bottom")),r=Ji(e,"x"),l=Ji(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Zi(e,"chartArea"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;u(t.boxes,(t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),f=Object.assign({},n);is(f,ki(s));const g=Object.assign({maxPadding:f,w:o,h:a,x:n.left,y:n.top},n),p=ts(l.concat(h),d);os(r.fullSize,g,d,p),os(l,g,d,p),os(h,g,d,p)&&os(l,g,d,p),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i("top"),t.x+=i("left"),i("right"),i("bottom")}(g),rs(r.leftAndTop,g,d,p),g.x+=g.w,g.y+=g.h,rs(r.rightAndBottom,g,d,p),t.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},u(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})}))}};class hs{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class cs extends hs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const ds="$chartjs",us={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},fs=t=>null===t||""===t;const gs=!!Se&&{passive:!0};function ps(t,e,i){t&&t.canvas&&t.canvas.removeEventListener(e,i,gs)}function ms(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function xs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.addedNodes,s),e=e&&!ms(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function bs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.removedNodes,s),e=e&&!ms(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const _s=new Map;let ys=0;function vs(){const t=window.devicePixelRatio;t!==ys&&(ys=t,_s.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function Ms(t,e,i){const s=t.canvas,n=s&&ge(s);if(!n)return;const o=ct(((t,e)=>{const s=n.clientWidth;i(t,e),s<n.clientWidth&&i()}),window),a=new ResizeObserver((t=>{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||o(i,s)}));return a.observe(n),function(t,e){_s.size||window.addEventListener("resize",vs),_s.set(t,e)}(t,o),a}function ws(t,e,i){i&&i.disconnect(),"resize"===e&&function(t){_s.delete(t),_s.size||window.removeEventListener("resize",vs)}(t)}function ks(t,e,i){const s=t.canvas,n=ct((e=>{null!==t.ctx&&i(function(t,e){const i=us[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t);return function(t,e,i){t&&t.addEventListener(e,i,gs)}(s,e,n),n}class Ss extends hs{acquireContext(t,e){const i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute("height"),n=t.getAttribute("width");if(t[ds]={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||"block",i.boxSizing=i.boxSizing||"border-box",fs(n)){const e=Pe(t,"width");void 0!==e&&(t.width=e)}if(fs(s))if(""===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,"height");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e[ds])return!1;const i=e[ds].initial;["height","width"].forEach((t=>{const n=i[t];s(n)?e.removeAttribute(t):e.setAttribute(t,n)}));const n=i.style||{};return Object.keys(n).forEach((t=>{e.style[t]=n[t]})),e.width=e.width,delete e[ds],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:xs,detach:bs,resize:Ms}[e]||ks;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:ws,detach:ws,resize:ws}[e]||ps)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return we(t,e,i,s)}isAttached(t){const e=t&&ge(t);return!(!e||!e.isConnected)}}function Ps(t){return!fe()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?cs:Ss}var Ds=Object.freeze({__proto__:null,BasePlatform:hs,BasicPlatform:cs,DomPlatform:Ss,_detectPlatform:Ps});const Cs="transparent",Os={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=Qt(t||Cs),n=s.valid&&Qt(e||Cs);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class As{constructor(t,e,i,s){const n=e[i];s=Pi([t.to,s,n,t.from]);const o=Pi([t.from,n,s]);this._active=!0,this._fn=t.fn||Os[t.type||typeof o],this._easing=fi[t.easing]||fi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=Pi([t.to,e,s,t.from]),this._from=Pi([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e<i),!this._active)return this._target[s]=a,void this._notify(!0);e<0?this._target[s]=n:(r=e/i%2,r=o&&r>1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t<i.length;t++)i[t][e]()}}class Ts{constructor(t,e){this._chart=t,this._properties=new Map,this.configure(e)}configure(t){if(!o(t))return;const e=Object.keys(ue.animation),i=this._properties;Object.getOwnPropertyNames(t).forEach((s=>{const a=t[s];if(!o(a))return;const r={};for(const t of e)r[t]=a[t];(n(a.properties)&&a.properties||[s]).forEach((t=>{t!==s&&i.has(t)||i.set(t,r)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e<s.length;e++){const n=t[s[e]];n&&n.active()&&i.push(n.wait())}return Promise.all(i)}(t.options.$animations,i).then((()=>{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if("$"===l.charAt(0))continue;if("options"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new As(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(bt.add(this._chart,i),!0):void 0}}function Ls(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function Es(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n<o;++n)i.push(s[n].index);return i}function Rs(t,e,i,s={}){const n=t.keys,o="single"===s.mode;let r,l,h,c;if(null===e)return;let d=!1;for(r=0,l=n.length;r<l;++r){if(h=+n[r],h===i){if(d=!0,s.all)continue;break}c=t.values[h],a(c)&&(o||0===e||F(e)===F(c))&&(e+=c)}return d||s.all?e:0}function Is(t,e){const i=t&&t.options.stacked;return i||void 0===i&&void 0!==e.stack}function zs(t,e,i){const s=t[e]||(t[e]={});return s[i]||(s[i]={})}function Fs(t,e,i,s){for(const n of e.getMatchingVisibleMetas(s).reverse()){const e=t[n.index];if(i&&e>0||!i&&e<0)return n.index}return null}function Vs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;t<d;++t){const i=e[t],{[l]:o,[h]:d}=i;u=(i._stacks||(i._stacks={}))[h]=zs(n,c,o),u[r]=d,u._top=Fs(u,a,!0,s.type),u._bottom=Fs(u,a,!1,s.type);(u._visualValues||(u._visualValues={}))[r]=d}}function Bs(t,e){const i=t.scales;return Object.keys(i).filter((t=>i[t].axis===e)).shift()}function Ws(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;if(!e||void 0===e[s]||void 0===e[s][i])return;delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i]}}}const Ns=t=>"reset"===t||"none"===t,Hs=(t,e)=>e?t:Object.assign({},t);class js{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Is(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Ws(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,n=e.xAxisID=l(i.xAxisID,Bs(t,"x")),o=e.yAxisID=l(i.yAxisID,Bs(t,"y")),a=e.rAxisID=l(i.rAxisID,Bs(t,"r")),r=e.indexAxis,h=e.iAxisID=s(r,n,o,a),c=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(h),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&rt(this._data,this),t._stacked&&Ws(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(o(e)){const t=this._cachedMeta;this._data=function(t,e){const{iScale:i,vScale:s}=e,n="x"===i.axis?"x":"y",o="x"===s.axis?"x":"y",a=Object.keys(t),r=new Array(a.length);let l,h,c;for(l=0,h=a.length;l<h;++l)c=a[l],r[l]={[n]:c,[o]:t[c]};return r}(e,t)}else if(i!==e){if(i){rt(i,this);const t=this._cachedMeta;Ws(t),t._parsed=[]}e&&Object.isExtensible(e)&&at(e,this),this._syncList=[],this._data=e}}addElements(){const t=this._cachedMeta;this._dataCheck(),this.datasetElementType&&(t.dataset=new this.datasetElementType)}buildOrUpdateElements(t){const e=this._cachedMeta,i=this.getDataset();let s=!1;this._dataCheck();const n=e._stacked;e._stacked=Is(e.vScale,e),e.stack!==i.stack&&(s=!0,Ws(e),e.stack=i.stack),this._resyncElements(t),(s||n!==e._stacked)&&(Vs(this,e._parsed),e._stacked=Is(e.vScale,e))}configure(){const t=this.chart.config,e=t.datasetScopeKeys(this._type),i=t.getOptionScopes(this.getDataset(),e,!0);this.options=t.createResolver(i,this.getContext()),this._parsing=this.options.parsing,this._cachedDataOpts={}}parse(t,e){const{_cachedMeta:i,_data:s}=this,{iScale:a,_stacked:r}=i,l=a.axis;let h,c,d,u=0===t&&e===s.length||i._sorted,f=t>0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,d=s;else{d=n(s[t])?this.parseArrayData(i,s,t,e):o(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const a=()=>null===c[l]||f&&c[l]<f[l];for(h=0;h<e;++h)i._parsed[h+t]=c=d[h],u&&(a()&&(u=!1),f=c);i._sorted=u}r&&Vs(this,d)}parsePrimitiveData(t,e,i,s){const{iScale:n,vScale:o}=t,a=n.axis,r=o.axis,l=n.getLabels(),h=n===o,c=new Array(s);let d,u,f;for(d=0,u=s;d<u;++d)f=d+i,c[d]={[a]:h||n.parse(l[f],f),[r]:o.parse(e[f],f)};return c}parseArrayData(t,e,i,s){const{xScale:n,yScale:o}=t,a=new Array(s);let r,l,h,c;for(r=0,l=s;r<l;++r)h=r+i,c=e[h],a[r]={x:n.parse(c[0],h),y:o.parse(c[1],h)};return a}parseObjectData(t,e,i,s){const{xScale:n,yScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l=new Array(s);let h,c,d,u;for(h=0,c=s;h<c;++h)d=h+i,u=e[d],l[h]={x:n.parse(M(u,a),d),y:o.parse(M(u,r),d)};return l}getParsed(t){return this._cachedMeta._parsed[t]}getDataElement(t){return this._cachedMeta.data[t]}applyStack(t,e,i){const s=this.chart,n=this._cachedMeta,o=e[t.axis];return Rs({keys:Es(s,!0),values:e._stacks[t.axis]._visualValues},o,n.index,{mode:i})}updateRangeFromParsed(t,e,i,s){const n=i[e.axis];let o=null===n?NaN:n;const a=s&&i._stacks[e.axis];s&&a&&(s.values=a,o=Rs(s,n,this._cachedMeta.index)),t.min=Math.min(t.min,o),t.max=Math.max(t.max,o)}getMinMax(t,e){const i=this._cachedMeta,s=i._parsed,n=i._sorted&&t===i.iScale,o=s.length,r=this._getOtherScale(t),l=((t,e,i)=>t&&!e.hidden&&e._stacked&&{keys:Es(i,!0),values:null})(e,i,this.chart),h={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:c,max:d}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(r);let u,f;function g(){f=s[u];const e=f[r.axis];return!a(f[t.axis])||c>e||d<e}for(u=0;u<o&&(g()||(this.updateRangeFromParsed(h,t,f,l),!n));++u);if(n)for(u=o-1;u>=0;--u)if(!g()){this.updateRangeFromParsed(h,t,f,l);break}return h}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s<n;++s)o=e[s][t.axis],a(o)&&i.push(o);return i}getMaxOverflow(){return!1}getLabelAndValue(t){const e=this._cachedMeta,i=e.iScale,s=e.vScale,n=this.getParsed(t);return{label:i?""+i.getLabelForValue(n[i.axis]):"",value:s?""+s.getLabelForValue(n[s.axis]):""}}_update(t){const e=this._cachedMeta;this.update(t||"default"),e._clip=function(t){let e,i,s,n;return o(t)?(e=t.top,i=t.right,s=t.bottom,n=t.left):e=i=s=n=t,{top:e,right:i,bottom:s,left:n,disabled:!1===t}}(l(this.options.clip,function(t,e,i){if(!1===i)return!1;const s=Ls(t,i),n=Ls(e,i);return{top:n.end,right:s.end,bottom:n.start,left:s.start}}(e.xScale,e.yScale,this.getMaxOverflow())))}update(t){}draw(){const t=this._ctx,e=this.chart,i=this._cachedMeta,s=i.data||[],n=e.chartArea,o=[],a=this._drawStart||0,r=this._drawCount||s.length-a,l=this.options.drawActiveElementsOnTop;let h;for(i.dataset&&i.dataset.draw(t,n,a,r),h=a;h<a+r;++h){const e=s[h];e.hidden||(e.active&&l?o.push(e):e.draw(t,n))}for(h=0;h<o.length;++h)o[h].draw(t,n)}getStyle(t,e){const i=e?"active":"default";return void 0===t&&this._cachedMeta.dataset?this.resolveDatasetElementOptions(i):this.resolveDataElementOptions(t||0,i)}getContext(t,e,i){const s=this.getDataset();let n;if(t>=0&&t<this._cachedMeta.data.length){const e=this._cachedMeta.data[t];n=e.$context||(e.$context=function(t,e,i){return Ci(t,{active:!1,dataIndex:e,parsed:void 0,raw:void 0,element:i,index:e,mode:"default",type:"data"})}(this.getContext(),t,e)),n.parsed=this.getParsed(t),n.raw=s.data[t],n.index=n.dataIndex=t}else n=this.$context||(this.$context=function(t,e){return Ci(t,{active:!1,dataset:void 0,datasetIndex:e,index:e,mode:"default",type:"dataset"})}(this.chart.getContext(),this.index)),n.dataset=s,n.index=n.datasetIndex=this.index;return n.active=!!e,n.mode=i,n}resolveDatasetElementOptions(t){return this._resolveElementOptions(this.datasetElementType.id,t)}resolveDataElementOptions(t,e){return this._resolveElementOptions(this.dataElementType.id,e,t)}_resolveElementOptions(t,e="default",i){const s="active"===e,n=this._cachedDataOpts,o=t+"-"+e,a=n[o],r=this.enableOptionSharing&&k(i);if(a)return Hs(a,r);const l=this.chart.config,h=l.datasetElementScopeKeys(this._type,t),c=s?[`${t}Hover`,"hover",t,""]:[t,""],d=l.getOptionScopes(this.getDataset(),h),u=Object.keys(ue.elements[t]),f=l.resolveNamedOptions(d,u,(()=>this.getContext(i,s,e)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Hs(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new Ts(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Ns(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const i=this.resolveDataElementOptions(t,e),s=this._sharedOptions,n=this.getSharedOptions(i),o=this.includeOptions(e,n)||n!==s;return this.updateSharedOptions(n,e,i),{sharedOptions:n,includeOptions:o}}updateElement(t,e,i,s){Ns(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Ns(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n<s&&this._removeElements(n,s-n)}_insertElements(t,e,i=!0){const s=this._cachedMeta,n=s.data,o=t+e;let a;const r=t=>{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a<o;++a)n[a]=new this.dataElementType;this._parsing&&r(s._parsed),this.parse(t,e),i&&this.updateElements(n,t,e,"reset")}updateElements(t,e,i,s){}_removeElements(t,e){const i=this._cachedMeta;if(this._parsing){const s=i._parsed.splice(t,e);i._stacked&&Ws(i,s)}i.data.splice(t,e)}_sync(t){if(this._parsing)this._syncList.push(t);else{const[e,i,s]=t;this[e](i,s)}this.chart._dataChanges.push([this.index,...t])}_onDataPush(){const t=arguments.length;this._sync(["_insertElements",this.getDataset().data.length-t,t])}_onDataPop(){this._sync(["_removeElements",this._cachedMeta.data.length-1,1])}_onDataShift(){this._sync(["_removeElements",0,1])}_onDataSplice(t,e){e&&this._sync(["_removeElements",t,e]);const i=arguments.length-2;i&&this._sync(["_insertElements",t,i])}_onDataUnshift(){this._sync(["_insertElements",0,arguments.length])}}class $s{static defaults={};static defaultRoutes=void 0;x;y;active=!1;options;$animations;tooltipPosition(t){const{x:e,y:i}=this.getProps(["x","y"],t);return{x:e,y:i}}hasValue(){return N(this.x)&&N(this.y)}getProps(t,e){const i=this.$animations;if(!e||!i)return this;const s={};return t.forEach((t=>{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}function Ys(t,e){const i=t.options.ticks,n=function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),o=Math.min(i.maxTicksLimit||n,n),a=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;i<s;i++)t[i].major&&e.push(i);return e}(e):[],r=a.length,l=a[0],h=a[r-1],c=[];if(r>o)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;n<t.length;n++)n===a&&(e.push(t[n]),o++,a=i[o*s])}(e,c,a,r/o),c;const d=function(t,e,i){const s=function(t){const e=t.length;let i,s;if(e<2)return!1;for(s=t[0],i=1;i<e;++i)if(t[i]-t[i-1]!==s)return!1;return s}(t),n=e.length/i;if(!s)return Math.max(n,1);const o=W(s);for(let t=0,e=o.length-1;t<e;t++){const e=o[t];if(e>n)return e}return Math.max(n,1)}(a,e,o);if(r>0){let t,i;const n=r>1?Math.round((h-l)/(r-1)):null;for(Us(e,c,d,s(n)?0:l-n,l),t=0,i=r-1;t<i;t++)Us(e,c,d,a[t],a[t+1]);return Us(e,c,d,h,s(n)?e.length:h+n),c}return Us(e,c,d),c}function Us(t,e,i,s,n){const o=l(s,0),a=Math.min(l(n,t.length),t.length);let r,h,c,d=0;for(i=Math.ceil(i),n&&(r=n-s,i=r/Math.floor(r/i)),c=o;c<0;)d++,c=Math.round(o+d*i);for(h=Math.max(o,0);h<a;h++)h===c&&(e.push(t[h]),d++,c=Math.round(o+d*i))}const Xs=(t,e,i)=>"top"===e||"left"===e?t[e]+i:t[e]-i,qs=(t,e)=>Math.min(e||t,t);function Ks(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;o<n;o+=s)i.push(t[Math.floor(o)]);return i}function Gs(t,e,i){const s=t.ticks.length,n=Math.min(e,s-1),o=t._startPixel,a=t._endPixel,r=1e-6;let l,h=t.getPixelForTick(n);if(!(i&&(l=1===s?Math.max(h-o,a-h):0===e?(t.getPixelForTick(1)-h)/2:(h-t.getPixelForTick(n-1))/2,h+=n<e?l:-l,h<o-r||h>a+r)))return h}function Zs(t){return t.drawTicks?t.tickLength:0}function Js(t,e){if(!t.display)return 0;const i=Si(t.font,e),s=ki(t.padding);return(n(t.text)?t.text.length:1)*i.lineHeight+s.height}function Qs(t,e,i){let s=ut(t);return(i&&"right"!==e||!i&&"right"===e)&&(s=(t=>"left"===t?"right":"right"===t?"left":t)(s)),s}class tn extends $s{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=r(t,Number.POSITIVE_INFINITY),e=r(e,Number.NEGATIVE_INFINITY),i=r(i,Number.POSITIVE_INFINITY),s=r(s,Number.NEGATIVE_INFINITY),{min:r(t,i),max:r(e,s),minDefined:a(t),maxDefined:a(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;r<l;++r)e=a[r].controller.getMinMax(this,t),n||(i=Math.min(i,e.min)),o||(s=Math.max(s,e.max));return i=o&&i>s?s:i,s=n&&i>s?i:s,{min:r(i,r(s,i)),max:r(s,r(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Di(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a<this.ticks.length;this._convertTicksToLabels(r?Ks(this.ticks,a):this.ticks),this.configure(),this.beforeCalculateLabelRotation(),this.calculateLabelRotation(),this.afterCalculateLabelRotation(),o.display&&(o.autoSkip||"auto"===o.source)&&(this.ticks=Ys(this,this.ticks),this._labelSizes=null,this.afterAutoSkip()),r&&this._convertTicksToLabels(this.ticks),this.beforeFit(),this.fit(),this.afterFit(),this.afterUpdate()}configure(){let t,e,i=this.options.reverse;this.isHorizontal()?(t=this.left,e=this.right):(t=this.top,e=this.bottom,i=!i),this._startPixel=t,this._endPixel=e,this._reversePixels=i,this._length=e-t,this._alignToPixels=this.options.alignToPixels}afterUpdate(){d(this.options.afterUpdate,[this])}beforeSetDimensions(){d(this.options.beforeSetDimensions,[this])}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=0,this.right=this.width):(this.height=this.maxHeight,this.top=0,this.bottom=this.height),this.paddingLeft=0,this.paddingTop=0,this.paddingRight=0,this.paddingBottom=0}afterSetDimensions(){d(this.options.afterSetDimensions,[this])}_callHooks(t){this.chart.notifyPlugins(t,this.getContext()),d(this.options[t],[this])}beforeDataLimits(){this._callHooks("beforeDataLimits")}determineDataLimits(){}afterDataLimits(){this._callHooks("afterDataLimits")}beforeBuildTicks(){this._callHooks("beforeBuildTicks")}buildTicks(){return[]}afterBuildTicks(){this._callHooks("afterBuildTicks")}beforeTickToLabelConversion(){d(this.options.beforeTickToLabelConversion,[this])}generateTickLabels(t){const e=this.options.ticks;let i,s,n;for(i=0,s=t.length;i<s;i++)n=t[i],n.label=d(e.callback,[n.value,i,t],this)}afterTickToLabelConversion(){d(this.options.afterTickToLabelConversion,[this])}beforeCalculateLabelRotation(){d(this.options.beforeCalculateLabelRotation,[this])}calculateLabelRotation(){const t=this.options,e=t.ticks,i=qs(this.ticks.length,t.ticks.maxTicksLimit),s=e.minRotation||0,n=e.maxRotation;let o,a,r,l=s;if(!this._isVisible()||!e.display||s>=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=J(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Zs(t.grid)-e.padding-Js(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(J((h.highest.height+6)/o,-1,1)),Math.asin(J(a/r,-1,1))-Math.asin(J(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){d(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){d(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=Js(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Zs(n)+o):(t.height=this.maxHeight,t.width=Zs(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=$(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l="top"!==a&&"x"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):"start"===n?d=e.width:"end"===n?c=t.width:"inner"!==n&&(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;"start"===n?(i=0,s=t.height):"end"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){d(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e<i;e++)s(t[e].label)&&(t.splice(e,1),i--,e--);this.afterTickToLabelConversion()}_getLabelSizes(){let t=this._labelSizes;if(!t){const e=this.options.ticks.sampleSize;let i=this.ticks;e<i.length&&(i=Ks(i,e)),this._labelSizes=t=this._computeLabelSizes(i,i.length,this.options.ticks.maxTicksLimit)}return t}_computeLabelSizes(t,e,i){const{ctx:o,_longestTextCache:a}=this,r=[],l=[],h=Math.floor(e/qs(e,i));let c,d,f,g,p,m,x,b,_,y,v,M=0,w=0;for(c=0;c<e;c+=h){if(g=t[c].label,p=this._resolveTickFontOptions(c),o.font=m=p.string,x=a[m]=a[m]||{data:{},gc:[]},b=p.lineHeight,_=y=0,s(g)||n(g)){if(n(g))for(d=0,f=g.length;d<f;++d)v=g[d],s(v)||n(v)||(_=Ce(o,x.data,x.gc,_,v),y+=b)}else _=Ce(o,x.data,x.gc,_,g),y=b;r.push(_),l.push(y),M=Math.max(_,M),w=Math.max(y,w)}!function(t,e){u(t,(t=>{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n<s;++n)delete t.data[i[n]];i.splice(0,s)}}))}(a,e);const k=r.indexOf(M),S=l.indexOf(w),P=t=>({width:r[t]||0,height:l[t]||0});return{first:P(0),last:P(e-1),widest:P(k),highest:P(S),widths:r,heights:l}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return Q(this._alignToPixels?Ae(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&t<e.length){const i=e[t];return i.$context||(i.$context=function(t,e,i){return Ci(t,{tick:i,index:e,type:"tick"})}(this.getContext(),t,i))}return this.$context||(this.$context=Ci(this.chart.getContext(),{scale:this,type:"scale"}))}_tickSize(){const t=this.options.ticks,e=$(this.labelRotation),i=Math.abs(Math.cos(e)),s=Math.abs(Math.sin(e)),n=this._getLabelSizes(),o=t.autoSkipPadding||0,a=n?n.widest.width+o:0,r=n?n.highest.height+o:0;return this.isHorizontal()?r*i>a*s?a/i:r/s:r*s<a*i?r/i:a/s}_isVisible(){const t=this.options.display;return"auto"!==t?!!t:this.getMatchingVisibleMetas().length>0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:a,border:r}=s,h=n.offset,c=this.isHorizontal(),d=this.ticks.length+(h?1:0),u=Zs(n),f=[],g=r.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,x=function(t){return Ae(i,t,p)};let b,_,y,v,M,w,k,S,P,D,C,O;if("top"===a)b=x(this.bottom),w=this.bottom-u,S=b-m,D=x(t.top)+m,O=t.bottom;else if("bottom"===a)b=x(this.top),D=t.top,O=x(t.bottom)-m,w=b+m,S=this.top+u;else if("left"===a)b=x(this.right),M=this.right-u,k=b-m,P=x(t.left)+m,C=t.right;else if("right"===a)b=x(this.left),P=t.left,C=x(t.right)-m,M=b+m,k=this.left+u;else if("x"===e){if("center"===a)b=x((t.top+t.bottom)/2+.5);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}D=t.top,O=t.bottom,w=b+m,S=w+u}else if("y"===e){if("center"===a)b=x((t.left+t.right)/2);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}M=b-m,k=M-u,P=t.left,C=t.right}const A=l(s.ticks.maxTicksLimit,d),T=Math.max(1,Math.ceil(d/A));for(_=0;_<d;_+=T){const t=this.getContext(_),e=n.setContext(t),s=r.setContext(t),o=e.lineWidth,a=e.color,l=s.dash||[],d=s.dashOffset,u=e.tickWidth,g=e.tickColor,p=e.tickBorderDash||[],m=e.tickBorderDashOffset;y=Gs(this,_,h),void 0!==y&&(v=Ae(i,y,o),c?M=k=P=C=v:w=S=D=O=v,f.push({tx1:M,ty1:w,tx2:k,ty2:S,x1:P,y1:D,x2:C,y2:O,width:o,color:a,borderDash:l,borderDashOffset:d,tickWidth:u,tickColor:g,tickBorderDash:p,tickBorderDashOffset:m}))}return this._ticksLength=d,this._borderValue=b,f}_computeLabelItems(t){const e=this.axis,i=this.options,{position:s,ticks:a}=i,r=this.isHorizontal(),l=this.ticks,{align:h,crossAlign:c,padding:d,mirror:u}=a,f=Zs(i.grid),g=f+d,p=u?-d:g,m=-$(this.labelRotation),x=[];let b,_,y,v,M,w,k,S,P,D,C,O,A="middle";if("top"===s)w=this.bottom-p,k=this._getXAxisLabelAlignment();else if("bottom"===s)w=this.top+p,k=this._getXAxisLabelAlignment();else if("left"===s){const t=this._getYAxisLabelAlignment(f);k=t.textAlign,M=t.x}else if("right"===s){const t=this._getYAxisLabelAlignment(f);k=t.textAlign,M=t.x}else if("x"===e){if("center"===s)w=(t.top+t.bottom)/2+g;else if(o(s)){const t=Object.keys(s)[0],e=s[t];w=this.chart.scales[t].getPixelForValue(e)+g}k=this._getXAxisLabelAlignment()}else if("y"===e){if("center"===s)M=(t.left+t.right)/2-g;else if(o(s)){const t=Object.keys(s)[0],e=s[t];M=this.chart.scales[t].getPixelForValue(e)}k=this._getYAxisLabelAlignment(f).textAlign}"y"===e&&("start"===h?A="top":"end"===h&&(A="bottom"));const T=this._getLabelSizes();for(b=0,_=l.length;b<_;++b){y=l[b],v=y.label;const t=a.setContext(this.getContext(b));S=this.getPixelForTick(b)+a.labelOffset,P=this._resolveTickFontOptions(b),D=P.lineHeight,C=n(v)?v.length:1;const e=C/2,i=t.color,o=t.textStrokeColor,h=t.textStrokeWidth;let d,f=k;if(r?(M=S,"inner"===k&&(f=b===_-1?this.options.reverse?"left":"right":0===b?this.options.reverse?"right":"left":"center"),O="top"===s?"near"===c||0!==m?-C*D+D/2:"center"===c?-T.highest.height/2-e*D+D:-T.highest.height+D/2:"near"===c||0!==m?D/2:"center"===c?T.highest.height/2-e*D:T.highest.height-C*D,u&&(O*=-1),0===m||t.showLabelBackdrop||(M+=D/2*Math.sin(m))):(w=S,O=(1-C)*D/2),t.showLabelBackdrop){const e=ki(t.backdropPadding),i=T.heights[b],s=T.widths[b];let n=O-e.top,o=0-e.left;switch(A){case"middle":n-=i/2;break;case"bottom":n-=i}switch(k){case"center":o-=s/2;break;case"right":o-=s;break;case"inner":b===_-1?o-=s:b>0&&(o-=s/2)}d={left:o,top:n,width:s+e.width,height:i+e.height,color:t.backdropColor}}x.push({label:v,font:P,textOffset:O,options:{rotation:m,color:i,strokeColor:o,strokeWidth:h,textAlign:f,textBaseline:A,translation:[M,w],backdrop:d}})}return x}_getXAxisLabelAlignment(){const{position:t,ticks:e}=this.options;if(-$(this.labelRotation))return"top"===t?"left":"right";let i="center";return"start"===e.align?i="left":"end"===e.align?i="right":"inner"===e.align&&(i="inner"),i}_getYAxisLabelAlignment(t){const{position:e,ticks:{crossAlign:i,mirror:s,padding:n}}=this.options,o=t+n,a=this._getLabelSizes().widest.width;let r,l;return"left"===e?s?(l=this.right+n,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l+=a)):(l=this.right-o,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l=this.left)):"right"===e?s?(l=this.left+n,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l-=a)):(l=this.left+o,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l=this.right)):r="right",{textAlign:r,x:l}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,e=this.options.position;return"left"===e||"right"===e?{top:0,left:this.left,bottom:t.height,right:this.right}:"top"===e||"bottom"===e?{top:this.top,left:0,bottom:this.bottom,right:t.width}:void 0}drawBackground(){const{ctx:t,options:{backgroundColor:e},left:i,top:s,width:n,height:o}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,s,n,o),t.restore())}getLineWidthForValue(t){const e=this.options.grid;if(!this._isVisible()||!e.display)return 0;const i=this.ticks.findIndex((e=>e.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n<o;++n){const t=s[n];e.drawOnChartArea&&a({x:t.x1,y:t.y1},{x:t.x2,y:t.y2},t),e.drawTicks&&a({x:t.tx1,y:t.ty1},{x:t.tx2,y:t.ty2},{color:t.tickColor,width:t.tickWidth,borderDash:t.tickBorderDash,borderDashOffset:t.tickBorderDashOffset})}}drawBorder(){const{chart:t,ctx:e,options:{border:i,grid:s}}=this,n=i.setContext(this.getContext()),o=i.display?n.width:0;if(!o)return;const a=s.setContext(this.getContext(0)).lineWidth,r=this._borderValue;let l,h,c,d;this.isHorizontal()?(l=Ae(t,this.left,o)-o/2,h=Ae(t,this.right,a)+a/2,c=d=r):(c=Ae(t,this.top,o)-o/2,d=Ae(t,this.bottom,a)+a/2,l=h=r),e.save(),e.lineWidth=n.width,e.strokeStyle=n.color,e.beginPath(),e.moveTo(l,c),e.lineTo(h,d),e.stroke(),e.restore()}drawLabels(t){if(!this.options.ticks.display)return;const e=this.ctx,i=this._computeLabelArea();i&&Ie(e,i);const s=this.getLabelItems(t);for(const t of s){const i=t.options,s=t.font;Ne(e,t.label,0,t.textOffset,s,i)}i&&ze(e)}drawTitle(){const{ctx:t,options:{position:e,title:i,reverse:s}}=this;if(!i.display)return;const a=Si(i.font),r=ki(i.padding),l=i.align;let h=a.lineHeight/2;"bottom"===e||"center"===e||o(e)?(h+=r.bottom,n(i.text)&&(h+=a.lineHeight*(i.text.length-1))):h+=r.top;const{titleX:c,titleY:d,maxWidth:u,rotation:f}=function(t,e,i,s){const{top:n,left:a,bottom:r,right:l,chart:h}=t,{chartArea:c,scales:d}=h;let u,f,g,p=0;const m=r-n,x=l-a;if(t.isHorizontal()){if(f=ft(s,a,l),o(i)){const t=Object.keys(i)[0],s=i[t];g=d[t].getPixelForValue(s)+m-e}else g="center"===i?(c.bottom+c.top)/2+m-e:Xs(t,i,e);u=l-a}else{if(o(i)){const t=Object.keys(i)[0],s=i[t];f=d[t].getPixelForValue(s)-x+e}else f="center"===i?(c.left+c.right)/2-x+e:Xs(t,i,e);g=ft(s,r,n),p="left"===i?-E:E}return{titleX:f,titleY:g,maxWidth:u,rotation:p}}(this,h,e,l);Ne(t,i.text,0,0,a,{color:i.color,maxWidth:u,rotation:f,textAlign:Qs(l,e,s),textBaseline:"middle",translation:[c,d]})}draw(t){this._isVisible()&&(this.drawBackground(),this.drawGrid(t),this.drawBorder(),this.drawTitle(),this.drawLabels(t))}_layers(){const t=this.options,e=t.ticks&&t.ticks.z||0,i=l(t.grid&&t.grid.z,-1),s=l(t.border&&t.border.z,0);return this._isVisible()&&this.draw===tn.prototype.draw?[{z:i,draw:t=>{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let n,o;for(n=0,o=e.length;n<o;++n){const o=e[n];o[i]!==this.id||t&&o.type!==t||s.push(o)}return s}_resolveTickFontOptions(t){return Si(this.options.ticks.setContext(this.getContext(t)).font)}_maxDigits(){const t=this._resolveTickFontOptions(0).lineHeight;return(this.isHorizontal()?this.width:this.height)/t}}class en{constructor(t,e,i){this.type=t,this.scope=e,this.override=i,this.items=Object.create(null)}isForType(t){return Object.prototype.isPrototypeOf.call(this.type.prototype,t.prototype)}register(t){const e=Object.getPrototypeOf(t);let i;(function(t){return"id"in t&&"defaults"in t})(e)&&(i=this.register(e));const s=this.items,n=t.id,o=this.scope+"."+n;if(!n)throw new Error("class does not have id: "+t);return n in s||(s[n]=t,function(t,e,i){const s=x(Object.create(null),[i?ue.get(i):{},ue.get(e),t.defaults]);ue.set(e,s),t.defaultRoutes&&function(t,e){Object.keys(e).forEach((i=>{const s=i.split("."),n=s.pop(),o=[t].concat(s).join("."),a=e[i].split("."),r=a.pop(),l=a.join(".");ue.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&ue.describe(e,t.descriptors)}(t,o,i),this.override&&ue.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in ue[s]&&(delete ue[s][i],this.override&&delete re[i])}}class sn{constructor(){this.controllers=new en(js,"datasets",!0),this.elements=new en($s,"elements"),this.plugins=new en(Object,"plugins"),this.scales=new en(tn,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):u(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=w(t);d(i["before"+s],[],i),e[t](i),d(i["after"+s],[],i)}_getRegistryForType(t){for(let e=0;e<this._typedRegistries.length;e++){const i=this._typedRegistries[e];if(i.isForType(t))return i}return this.plugins}_get(t,e,i){const s=e.get(t);if(void 0===s)throw new Error('"'+t+'" is not a registered '+i+".");return s}}var nn=new sn;class on{constructor(){this._init=[]}notify(t,e,i,s){"beforeInit"===e&&(this._init=this._createDescriptors(t,!0),this._notify(this._init,t,"install"));const n=s?this._descriptors(t).filter(s):this._descriptors(t),o=this._notify(n,t,e,i);return"afterDestroy"===e&&(this._notify(n,t,"stop"),this._notify(this._init,t,"uninstall")),o}_notify(t,e,i,s){s=s||{};for(const n of t){const t=n.plugin;if(!1===d(t[i],[e,s,n.options],t)&&s.cancelable)return!1}return!0}invalidate(){s(this._cache)||(this._oldCache=this._cache,this._cache=void 0)}_descriptors(t){if(this._cache)return this._cache;const e=this._cache=this._createDescriptors(t);return this._notifyStateChanges(t),e}_createDescriptors(t,e){const i=t&&t.config,s=l(i.options&&i.options.plugins,{}),n=function(t){const e={},i=[],s=Object.keys(nn.plugins.items);for(let t=0;t<s.length;t++)i.push(nn.getPlugin(s[t]));const n=t.plugins||[];for(let t=0;t<n.length;t++){const s=n[t];-1===i.indexOf(s)&&(i.push(s),e[s.id]=!0)}return{plugins:i,localIds:e}}(i);return!1!==s||e?function(t,{plugins:e,localIds:i},s,n){const o=[],a=t.getContext();for(const r of e){const e=r.id,l=an(s[e],n);null!==l&&o.push({plugin:r,options:rn(t.config,{plugin:r,local:i[e]},l,a)})}return o}(t,n,s,e):[]}_notifyStateChanges(t){const e=this._oldCache||[],i=this._cache,s=(t,e)=>t.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function an(t,e){return e||!1!==t?!0===t?{}:t:null}function rn(t,{plugin:e,local:i},s,n){const o=t.pluginScopeKeys(e),a=t.getOptionScopes(s,o);return i&&e.defaults&&a.push(e.defaults),t.createResolver(a,n,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function ln(t,e){const i=ue.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function hn(t){if("x"===t||"y"===t||"r"===t)return t}function cn(t,...e){if(hn(t))return t;for(const s of e){const e=s.axis||("top"===(i=s.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||t.length>1&&hn(t[0].toLowerCase());if(e)return e}var i;throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function dn(t,e,i){if(i[e+"AxisID"]===t)return{axis:e}}function un(t,e){const i=re[t.type]||{scales:{}},s=e.scales||{},n=ln(t.type,e),a=Object.create(null);return Object.keys(s).forEach((e=>{const r=s[e];if(!o(r))return console.error(`Invalid scale configuration for scale: ${e}`);if(r._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const l=cn(e,r,function(t,e){if(e.data&&e.data.datasets){const i=e.data.datasets.filter((e=>e.xAxisID===t||e.yAxisID===t));if(i.length)return dn(t,"x",i[0])||dn(t,"y",i[0])}return{}}(e,t),ue.scales[r.type]),h=function(t,e){return t===e?"_index_":"_value_"}(l,n),c=i.scales||{};a[e]=b(Object.create(null),[{axis:l},r,c[l],c[h]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,o=i.indexAxis||ln(n,e),r=(re[n]||{}).scales||{};Object.keys(r).forEach((t=>{const e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,o),n=i[e+"AxisID"]||e;a[n]=a[n]||Object.create(null),b(a[n],[{axis:e},s[n],r[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];b(e,[ue.scales[e.type],ue.scale])})),a}function fn(t){const e=t.options||(t.options={});e.plugins=l(e.plugins,{}),e.scales=un(t,e)}function gn(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const pn=new Map,mn=new Set;function xn(t,e){let i=pn.get(t);return i||(i=e(),pn.set(t,i),mn.add(i)),i}const bn=(t,e,i)=>{const s=M(e,i);void 0!==s&&t.add(s)};class _n{constructor(t){this._config=function(t){return(t=t||{}).data=gn(t.data),fn(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=gn(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),fn(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return xn(t,(()=>[[`datasets.${t}`,""]]))}datasetAnimationScopeKeys(t,e){return xn(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]]))}datasetElementScopeKeys(t,e){return xn(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]]))}pluginScopeKeys(t){const e=t.id;return xn(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>bn(r,t,e)))),e.forEach((t=>bn(r,s,t))),e.forEach((t=>bn(r,re[n]||{},t))),e.forEach((t=>bn(r,ue,t))),e.forEach((t=>bn(r,le,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),mn.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,re[e]||{},ue.datasets[e]||{},{type:e},ue,le]}resolveNamedOptions(t,e,i,s=[""]){const o={$shared:!0},{resolver:a,subPrefixes:r}=yn(this._resolverCache,t,s);let l=a;if(function(t,e){const{isScriptable:i,isIndexable:s}=Ye(t);for(const o of e){const e=i(o),a=s(o),r=(a||e)&&t[o];if(e&&(S(r)||vn(r))||a&&n(r))return!0}return!1}(a,e)){o.$shared=!1;l=$e(a,i=S(i)?i():i,this.createResolver(t,i,r))}for(const t of e)o[t]=l[t];return o}createResolver(t,e,i=[""],s){const{resolver:n}=yn(this._resolverCache,t,i);return o(e)?$e(n,e,void 0,s):n}}function yn(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:je(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes("hover")))},s.set(n,o)}return o}const vn=t=>o(t)&&Object.getOwnPropertyNames(t).some((e=>S(t[e])));const Mn=["top","bottom","left","right","chartArea"];function wn(t,e){return"top"===t||"bottom"===t||-1===Mn.indexOf(t)&&"x"===e}function kn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function Sn(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),d(i&&i.onComplete,[t],e)}function Pn(t){const e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function Dn(t){return fe()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Cn={},On=t=>{const e=Dn(t);return Object.values(Cn).filter((t=>t.canvas===e)).pop()};function An(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}class Tn{static defaults=ue;static instances=Cn;static overrides=re;static registry=nn;static version="4.4.9";static getChart=On;static register(...t){nn.add(...t),Ln()}static unregister(...t){nn.remove(...t),Ln()}constructor(t,e){const s=this.config=new _n(e),n=Dn(t),o=On(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||Ps(n)),this.platform.updateConfig(s);const r=this.platform.acquireContext(n,a.aspectRatio),l=r&&r.canvas,h=l&&l.height,c=l&&l.width;this.id=i(),this.ctx=r,this.canvas=l,this.width=c,this.height=h,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new on,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=dt((t=>this.update(t)),a.resizeDelay||0),this._dataChanges=[],Cn[this.id]=this,r&&l?(bt.listen(this,"complete",Sn),bt.listen(this,"progress",Pn),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return s(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return nn}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Te(this.canvas,this.ctx),this}stop(){return bt.stop(this),this}resize(t,e){bt.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),d(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){u(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=cn(t,i),n="r"===s,o="x"===s;return{options:i,dposition:n?"chartArea":o?"bottom":"left",dtype:n?"radialLinear":o?"category":"linear"}})))),u(n,(e=>{const n=e.options,o=n.id,a=cn(o,n),r=l(n.type,e.dtype);void 0!==n.position&&wn(n.position,a)===wn(e.dposition)||(n.position=e.dposition),s[o]=!0;let h=null;if(o in i&&i[o].type===r)h=i[o];else{h=new(nn.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[h.id]=h}h.init(n,t)})),u(s,((t,e)=>{t||delete i[e]})),u(i,(t=>{ls.configure(this,t,t.options),ls.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;t<i;++t)this._destroyDatasetMeta(t);t.splice(e,i-e)}this._sortedMetasets=t.slice(0).sort(kn("order","index"))}_removeUnreferencedMetasets(){const{_metasets:t,data:{datasets:e}}=this;t.length>e.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i<s;i++){const s=e[i];let n=this.getDatasetMeta(i);const o=s.type||this.config.type;if(n.type&&n.type!==o&&(this._destroyDatasetMeta(i),n=this.getDatasetMeta(i)),n.type=o,n.indexAxis=s.indexAxis||ln(o,this.options),n.order=s.order||0,n.index=i,n.label=""+s.label,n.visible=this.isDatasetVisible(i),n.controller)n.controller.updateIndex(i),n.controller.linkScales();else{const e=nn.getController(o),{datasetElementType:s,dataElementType:a}=ue.datasets[o];Object.assign(e,{dataElementType:nn.getElement(a),datasetElementType:s&&nn.getElement(s)}),n.controller=new e(this,i),t.push(n.controller)}}return this._updateMetasets(),t}_resetElements(){u(this.data.datasets,((t,e)=>{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let t=0,e=this.data.datasets.length;t<e;t++){const{controller:e}=this.getDatasetMeta(t),i=!s&&-1===n.indexOf(e);e.buildOrUpdateElements(i),o=Math.max(+e.getMaxOverflow(),o)}o=this._minPadding=i.layout.autoPadding?o:0,this._updateLayout(o),s||u(n,(t=>{t.reset()})),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(kn("z","_idx"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){u(this.scales,(t=>{ls.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);P(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){An(t,s,"_removeElements"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+","+t.splice(1).join(",")))),s=i(0);for(let t=1;t<e;t++)if(!P(s,i(t)))return;return Array.from(s).map((t=>t.split(","))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;ls.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],u(this.boxes,(t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t<e;++t)this.getDatasetMeta(t).controller.configure();for(let e=0,i=this.data.datasets.length;e<i;++e)this._updateDataset(e,S(t)?t({datasetIndex:e}):t);this.notifyPlugins("afterDatasetsUpdate",{mode:t})}}_updateDataset(t,e){const i=this.getDatasetMeta(t),s={meta:i,index:t,mode:e,cancelable:!0};!1!==this.notifyPlugins("beforeDatasetUpdate",s)&&(i.controller._update(e),s.cancelable=!1,this.notifyPlugins("afterDatasetUpdate",s))}render(){!1!==this.notifyPlugins("beforeRender",{cancelable:!0})&&(bt.has(this)?this.attached&&!bt.running(this)&&bt.start(this):(this.draw(),Sn({chart:this})))}draw(){let t;if(this._resizeBeforeDraw){const{width:t,height:e}=this._resizeBeforeDraw;this._resizeBeforeDraw=null,this._resize(t,e)}if(this.clear(),this.width<=0||this.height<=0)return;if(!1===this.notifyPlugins("beforeDraw",{cancelable:!0}))return;const e=this._layers;for(t=0;t<e.length&&e[t].z<=0;++t)e[t].draw(this.chartArea);for(this._drawDatasets();t<e.length;++t)e[t].draw(this.chartArea);this.notifyPlugins("afterDraw")}_getSortedDatasetMetas(t){const e=this._sortedMetasets,i=[];let s,n;for(s=0,n=e.length;s<n;++s){const n=e[s];t&&!n.visible||i.push(n)}return i}getSortedVisibleDatasetMetas(){return this._getSortedDatasetMetas(!0)}_drawDatasets(){if(!1===this.notifyPlugins("beforeDatasetsDraw",{cancelable:!0}))return;const t=this.getSortedVisibleDatasetMetas();for(let e=t.length-1;e>=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,i={meta:t,index:t.index,cancelable:!0},s=Ni(this,t);!1!==this.notifyPlugins("beforeDatasetDraw",i)&&(s&&Ie(e,s),t.controller.draw(),s&&ze(e),i.cancelable=!1,this.notifyPlugins("afterDatasetDraw",i))}isPointInArea(t){return Re(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,s){const n=Ki.modes[e];return"function"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ci(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return"boolean"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?"show":"hide",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);k(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),bt.remove(this),t=0,e=this.data.datasets.length;t<e;++t)this._destroyDatasetMeta(t)}destroy(){this.notifyPlugins("beforeDestroy");const{canvas:t,ctx:e}=this;this._stop(),this.config.clearCache(),t&&(this.unbindEvents(),Te(t,e),this.platform.releaseContext(e),this.canvas=null,this.ctx=null),delete Cn[this.id],this.notifyPlugins("afterDestroy")}toBase64Image(...t){return this.canvas.toDataURL(...t)}bindEvents(){this.bindUserEvents(),this.options.responsive?this.bindResponsiveEvents():this.attached=!0}bindUserEvents(){const t=this._listeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};u(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s("attach",a),this.attached=!0,this.resize(),i("resize",n),i("detach",o)};o=()=>{this.attached=!1,s("resize",n),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){u(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},u(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?"set":"remove";let n,o,a,r;for("dataset"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller["_"+s+"DatasetHoverStyle"]()),a=0,r=t.length;a<r;++a){o=t[a];const e=o&&this.getDatasetMeta(o.datasetIndex).controller;e&&e[s+"HoverStyle"](o.element,o.datasetIndex,o.index)}}getActiveElements(){return this._active||[]}setActiveElements(t){const e=this._active||[],i=t.map((({datasetIndex:t,index:e})=>{const i=this.getDatasetMeta(t);if(!i)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:i.data[e],index:e}}));!f(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return 1===this._plugins._cache.filter((e=>e.plugin.id===t)).length}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=D(t),l=function(t,e,i,s){return i&&"mouseout"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,d(n.onHover,[t,a,this],this),r&&d(n.onClick,[t,a,this],this));const h=!f(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}function Ln(){return u(Tn.instances,(t=>t._plugins.invalidate()))}function En(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class Rn{static override(t){Object.assign(Rn.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return En()}parse(){return En()}format(){return En()}add(){return En()}diff(){return En()}startOf(){return En()}endOf(){return En()}}var In={_date:Rn};function zn(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;e<n;e++)s=s.concat(i[e].controller.getAllParsedValues(t));t._cache.$bar=lt(s.sort(((t,e)=>t-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(k(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;s<n;++s)o=e.getPixelForValue(i[s]),l();for(a=void 0,s=0,n=e.ticks.length;s<n;++s)o=e.getPixelForTick(s),l();return r}function Fn(t,e,i,s){return n(t)?function(t,e,i,s){const n=i.parse(t[0],s),o=i.parse(t[1],s),a=Math.min(n,o),r=Math.max(n,o);let l=a,h=r;Math.abs(a)>Math.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function Vn(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;h<c;++h)u=e[h],d={},d[n.axis]=r||n.parse(a[h],h),l.push(Fn(u,d,o,h));return l}function Bn(t){return t&&void 0!==t.barStart&&void 0!==t.barEnd}function Wn(t,e,i,s){let n=e.borderSkipped;const o={};if(!n)return void(t.borderSkipped=o);if(!0===n)return void(t.borderSkipped={top:!0,right:!0,bottom:!0,left:!0});const{start:a,end:r,reverse:l,top:h,bottom:c}=function(t){let e,i,s,n,o;return t.horizontal?(e=t.base>t.x,i="left",s="right"):(e=t.base<t.y,i="bottom",s="top"),e?(n="end",o="start"):(n="start",o="end"),{start:i,end:s,reverse:e,top:n,bottom:o}}(t);"middle"===n&&i&&(t.enableBorderRadius=!0,(i._top||0)===s?n=h:(i._bottom||0)===s?n=c:(o[Nn(c,a,r,l)]=!0,n=h)),o[Nn(n,a,r,l)]=!0,t.borderSkipped=o}function Nn(t,e,i,s){var n,o,a;return s?(a=i,t=Hn(t=(n=t)===(o=e)?a:n===a?o:n,i,e)):t=Hn(t,e,i),t}function Hn(t,e,i){return"start"===t?e:"end"===t?i:t}function jn(t,{inflateAmount:e},i){t.inflateAmount="auto"===e?1===i?.33:0:e}class $n extends js{static id="doughnut";static defaults={datasetElementType:!1,dataElementType:"arc",animation:{animateRotate:!0,animateScale:!1},animations:{numbers:{type:"number",properties:["circumference","endAngle","innerRadius","outerRadius","startAngle","x","y","offset","borderWidth","spacing"]}},cutout:"50%",rotation:0,circumference:360,radius:"100%",spacing:0,indexAxis:"r"};static descriptors={_scriptable:t=>"spacing"!==t,_indexable:t=>"spacing"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,a,r=t=>+i[t];if(o(i[t])){const{key:t="value"}=this._parsing;r=e=>+M(i[e],t)}for(n=t,a=t+e;n<a;++n)s._parsed[n]=r(n)}}_getRotation(){return $(this.options.rotation-90)}_getCircumference(){return $(this.options.circumference)}_getRotationExtents(){let t=O,e=-O;for(let i=0;i<this.chart.data.datasets.length;++i)if(this.chart.isDatasetVisible(i)&&this.chart.getDatasetMeta(i).type===this._type){const s=this.chart.getDatasetMeta(i).controller,n=s._getRotation(),o=s._getCircumference();t=Math.min(t,n),e=Math.max(e,n+o)}return{rotation:t,circumference:e-t}}update(t){const e=this.chart,{chartArea:i}=e,s=this._cachedMeta,n=s.data,o=this.getMaxBorderWidth()+this.getMaxOffset(n)+this.options.spacing,a=Math.max((Math.min(i.width,i.height)-o)/2,0),r=Math.min(h(this.options.cutout,a),1),l=this._getRingWeight(this.index),{circumference:d,rotation:u}=this._getRotationExtents(),{ratioX:f,ratioY:g,offsetX:p,offsetY:m}=function(t,e,i){let s=1,n=1,o=0,a=0;if(e<O){const r=t,l=r+e,h=Math.cos(r),c=Math.sin(r),d=Math.cos(l),u=Math.sin(l),f=(t,e,s)=>Z(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>Z(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(E,c,u),x=g(C,h,d),b=g(C+E,c,u);s=(p-x)/2,n=(m-b)/2,o=-(p+x)/2,a=-(m+b)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(u,d,r),x=(i.width-o)/f,b=(i.height-o)/g,_=Math.max(Math.min(x,b)/2,0),y=c(this.options.radius,_),v=(y-Math.max(y*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=p*y,this.offsetY=m*y,s.total=this.calculateTotal(),this.outerRadius=y-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/O)}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:f,includeOptions:g}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p<e;++p)m+=this._circumference(p,n);for(p=e;p<e+i;++p){const e=this._circumference(p,n),i=t[p],o={x:l+this.offsetX,y:h+this.offsetY,startAngle:m,endAngle:m+e,circumference:e,outerRadius:u,innerRadius:d};g&&(o.options=f||this.resolveDataElementOptions(p,i.active?"active":s)),m+=e,this.updateElement(i,p,o,s)}}calculateTotal(){const t=this._cachedMeta,e=t.data;let i,s=0;for(i=0;i<e.length;i++){const n=t._parsed[i];null===n||isNaN(n)||!this.chart.getDataVisibility(i)||e[i].hidden||(s+=Math.abs(n))}return s}calculateCircumference(t){const e=this._cachedMeta.total;return e>0&&!isNaN(t)?O*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t],i.options.locale);return{label:s[t]||"",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s<n;++s)if(i.isDatasetVisible(s)){o=i.getDatasetMeta(s),t=o.data,a=o.controller;break}if(!t)return 0;for(s=0,n=t.length;s<n;++s)r=a.resolveDataElementOptions(s),"inner"!==r.borderAlign&&(e=Math.max(e,r.borderWidth||0,r.hoverBorderWidth||0));return e}getMaxOffset(t){let e=0;for(let i=0,s=t.length;i<s;++i){const t=this.resolveDataElementOptions(i);e=Math.max(e,t.offset||0,t.hoverOffset||0)}return e}_getRingWeightOffset(t){let e=0;for(let i=0;i<t;++i)this.chart.isDatasetVisible(i)&&(e+=this._getRingWeight(i));return e}_getRingWeight(t){return Math.max(l(this.chart.data.datasets[t].weight,1),0)}_getVisibleDatasetWeightTotal(){return this._getRingWeightOffset(this.chart.data.datasets.length)||1}}class Yn extends js{static id="polarArea";static defaults={dataElementType:"arc",animation:{animateRotate:!0,animateScale:!0},animations:{numbers:{type:"number",properties:["x","y","startAngle","endAngle","innerRadius","outerRadius"]}},indexAxis:"r",startAngle:0};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data;if(e.labels.length&&e.datasets.length){const{labels:{pointStyle:i,color:s}}=t.legend.options;return e.labels.map(((e,n)=>{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:n}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach(((t,i)=>{const s=this.getParsed(i).r;!isNaN(s)&&this.chart.getDataVisibility(i)&&(s<e.min&&(e.min=s),s>e.max&&(e.max=s))})),e}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.options.animation,r=this._cachedMeta.rScale,l=r.xCenter,h=r.yCenter,c=r.getIndexAngle(0)-.5*C;let d,u=c;const f=360/this.countVisibleElements();for(d=0;d<e;++d)u+=this._computeAngle(d,s,f);for(d=e;d<e+i;d++){const e=t[d];let i=u,g=u+this._computeAngle(d,s,f),p=o.getDataVisibility(d)?r.getDistanceFromCenterForValue(this.getParsed(d).r):0;u=g,n&&(a.animateScale&&(p=0),a.animateRotate&&(i=g=c));const m={x:l,y:h,innerRadius:0,outerRadius:p,startAngle:i,endAngle:g,options:this.resolveDataElementOptions(d,e.active?"active":s)};this.updateElement(e,d,m,s)}}countVisibleElements(){const t=this._cachedMeta;let e=0;return t.data.forEach(((t,i)=>{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++})),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?$(this.resolveDataElementOptions(t,e).angle||i):0}}var Un=Object.freeze({__proto__:null,BarController:class extends js{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return Vn(t,e,i,s)}parseArrayData(t,e,i,s){return Vn(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:n,vScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l="x"===n.axis?a:r,h="x"===o.axis?a:r,c=[];let d,u,f,g;for(d=i,u=i+s;d<u;++d)g=e[d],f={},f[n.axis]=n.parse(M(g,l),d),c.push(Fn(M(g,h),f,o,d));return c}updateRangeFromParsed(t,e,i,s){super.updateRangeFromParsed(t,e,i,s);const n=i._custom;n&&e===this._cachedMeta.vScale&&(t.min=Math.min(t.min,n.min),t.max=Math.max(t.max,n.max))}getMaxOverflow(){return 0}getLabelAndValue(t){const e=this._cachedMeta,{iScale:i,vScale:s}=e,n=this.getParsed(t),o=n._custom,a=Bn(o)?"["+o.start+", "+o.end+"]":""+s.getLabelForValue(n[s.axis]);return{label:""+i.getLabelForValue(n[i.axis]),value:a}}initialize(){this.enableOptionSharing=!0,super.initialize();this._cachedMeta.stack=this.getDataset().stack}update(t){const e=this._cachedMeta;this.updateElements(e.data,0,e.data.length,t)}updateElements(t,e,i,n){const o="reset"===n,{index:a,_cachedMeta:{vScale:r}}=this,l=r.getBasePixel(),h=r.isHorizontal(),c=this._getRuler(),{sharedOptions:d,includeOptions:u}=this._getSharedOptions(e,n);for(let f=e;f<e+i;f++){const e=this.getParsed(f),i=o||s(e[r.axis])?{base:l,head:l}:this._calculateBarValuePixels(f),g=this._calculateBarIndexPixels(f,c),p=(e._stacks||{})[r.axis],m={horizontal:h,base:i.base,enableBorderRadius:!p||Bn(e._custom)||a===p._top||a===p._bottom,x:h?i.head:g.center,y:h?g.center:i.head,height:h?g.size:Math.abs(i.size),width:h?Math.abs(i.size):g.size};u&&(m.options=d||this.resolveDataElementOptions(f,t[f].active?"active":n));const x=m.options||t[f].options;Wn(m,x,p,a),jn(m,x,c.ratio),this.updateElement(t[f],f,m,n)}}_getStacks(t,e){const{iScale:i}=this._cachedMeta,n=i.getMatchingVisibleMetas(this._type).filter((t=>t.controller.options.grouped)),o=i.options.stacked,a=[],r=this._cachedMeta.controller.getParsed(e),l=r&&r[i.axis],h=t=>{const e=t._parsed.find((t=>t[i.axis]===l)),n=e&&e[t.vScale.axis];if(s(n)||isNaN(n))return!0};for(const i of n)if((void 0===e||!h(i))&&((!1===o||-1===a.indexOf(i.stack)||void 0===o&&void 0===i.stack)&&a.push(i.stack),i.index===t))break;return a.length||a.push(void 0),a}_getStackCount(t){return this._getStacks(void 0,t).length}_getStackIndex(t,e,i){const s=this._getStacks(t,i),n=void 0!==e?s.indexOf(e):-1;return-1===n?s.length-1:n}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let n,o;for(n=0,o=e.data.length;n<o;++n)s.push(i.getPixelForValue(this.getParsed(n)[i.axis],n));const a=t.barThickness;return{min:a||zn(e),pixels:s,start:i._startPixel,end:i._endPixel,stackCount:this._getStackCount(),scale:i,grouped:t.grouped,ratio:a?1:t.categoryPercentage*t.barPercentage}}_calculateBarValuePixels(t){const{_cachedMeta:{vScale:e,_stacked:i,index:n},options:{base:o,minBarLength:a}}=this,r=o||0,l=this.getParsed(t),h=l._custom,c=Bn(h);let d,u,f=l[e.axis],g=0,p=i?this.applyStack(e,l,i):f;p!==f&&(g=p-f,p=f),c&&(f=h.barStart,p=h.barEnd-h.barStart,0!==f&&F(f)!==F(h.barEnd)&&(g=0),g+=f);const m=s(o)||c?g:o;let x=e.getPixelForValue(m);if(d=this.chart.getDataVisibility(t)?e.getPixelForValue(g+p):x,u=d-x,Math.abs(u)<a){u=function(t,e,i){return 0!==t?F(t):(e.isHorizontal()?1:-1)*(e.min>=i?1:-1)}(u,e,r)*a,f===r&&(x-=u/2);const t=e.getPixelForDecimal(0),s=e.getPixelForDecimal(1),o=Math.min(t,s),h=Math.max(t,s);x=Math.max(Math.min(x,h),o),d=x+u,i&&!c&&(l._stacks[e.axis]._visualValues[n]=e.getValueForPixel(d)-e.getValueForPixel(x))}if(x===e.getPixelForValue(r)){const t=F(u)*e.getLineWidthForValue(r)/2;x+=t,u-=t}return{size:u,base:x,head:d,center:d+u/2}}_calculateBarIndexPixels(t,e){const i=e.scale,n=this.options,o=n.skipNull,a=l(n.maxBarThickness,1/0);let r,h;if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,l="flex"===n.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t<n.length-1?n[t+1]:null;const l=i.categoryPercentage;null===a&&(a=o-(null===r?e.end-e.start:r-o)),null===r&&(r=o+o-a);const h=o-(o-Math.min(a,r))/2*l;return{chunk:Math.abs(r-a)/2*l/s,ratio:i.barPercentage,start:h}}(t,e,n,i):function(t,e,i,n){const o=i.barThickness;let a,r;return s(o)?(a=e.min*i.categoryPercentage,r=i.barPercentage):(a=o*n,r=1),{chunk:a/n,ratio:r,start:e.pixels[t]-a/2}}(t,e,n,i),c=this._getStackIndex(this.index,this._cachedMeta.stack,o?t:void 0);r=l.start+l.chunk*c+l.chunk/2,h=Math.min(a,l.chunk*l.ratio)}else r=i.getPixelForValue(this.getParsed(t)[i.axis],t),h=Math.min(a,e.min*e.ratio);return{base:r-h/2,head:r+h/2,center:r,size:h}}draw(){const t=this._cachedMeta,e=t.vScale,i=t.data,s=i.length;let n=0;for(;n<s;++n)null===this.getParsed(n)[e.axis]||i[n].hidden||i[n].draw(this._ctx)}},BubbleController:class extends js{static id="bubble";static defaults={datasetElementType:!1,dataElementType:"point",animations:{numbers:{type:"number",properties:["x","y","borderWidth","radius"]}}};static overrides={scales:{x:{type:"linear"},y:{type:"linear"}}};initialize(){this.enableOptionSharing=!0,super.initialize()}parsePrimitiveData(t,e,i,s){const n=super.parsePrimitiveData(t,e,i,s);for(let t=0;t<n.length;t++)n[t]._custom=this.resolveDataElementOptions(t+i).radius;return n}parseArrayData(t,e,i,s){const n=super.parseArrayData(t,e,i,s);for(let t=0;t<n.length;t++){const s=e[i+t];n[t]._custom=l(s[2],this.resolveDataElementOptions(t+i).radius)}return n}parseObjectData(t,e,i,s){const n=super.parseObjectData(t,e,i,s);for(let t=0;t<n.length;t++){const s=e[i+t];n[t]._custom=l(s&&s.r&&+s.r,this.resolveDataElementOptions(t+i).radius)}return n}getMaxOverflow(){const t=this._cachedMeta.data;let e=0;for(let i=t.length-1;i>=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y),l=o._custom;return{label:i[t]||"",value:"("+a+", "+r+(l?", "+l:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a}=this._cachedMeta,{sharedOptions:r,includeOptions:l}=this._getSharedOptions(e,s),h=o.axis,c=a.axis;for(let d=e;d<e+i;d++){const e=t[d],i=!n&&this.getParsed(d),u={},f=u[h]=n?o.getPixelForDecimal(.5):o.getPixelForValue(i[h]),g=u[c]=n?a.getBasePixel():a.getPixelForValue(i[c]);u.skip=isNaN(f)||isNaN(g),l&&(u.options=r||this.resolveDataElementOptions(d,e.active?"active":s),n&&(u.options.radius=0)),this.updateElement(e,d,u,s)}}resolveDataElementOptions(t,e){const i=this.getParsed(t);let s=super.resolveDataElementOptions(t,e);s.$shared&&(s=Object.assign({},s,{$shared:!1}));const n=s.radius;return"active"!==e&&(s.radius=0),s.radius+=l(i&&i._custom,n),s}},DoughnutController:$n,LineController:class extends js{static id="line";static defaults={datasetElementType:"line",dataElementType:"point",showLine:!0,spanGaps:!1};static overrides={scales:{_index_:{type:"category"},_value_:{type:"linear"}}};initialize(){this.enableOptionSharing=!0,this.supportsDecimation=!0,super.initialize()}update(t){const e=this._cachedMeta,{dataset:i,data:s=[],_dataset:n}=e,o=this.chart._animationsDisabled;let{start:a,count:r}=pt(e,s,o);this._drawStart=a,this._drawCount=r,mt(e)&&(a=0,r=s.length),i._chart=this.chart,i._datasetIndex=this.index,i._decimated=!!n._decimated,i.points=s;const l=this.resolveDatasetElementOptions(t);this.options.showLine||(l.borderWidth=0),l.segment=this.options.segment,this.updateElement(i,void 0,{animated:!o,options:l},t),this.updateElements(s,a,r,t)}updateElements(t,e,i,n){const o="reset"===n,{iScale:a,vScale:r,_stacked:l,_dataset:h}=this._cachedMeta,{sharedOptions:c,includeOptions:d}=this._getSharedOptions(e,n),u=a.axis,f=r.axis,{spanGaps:g,segment:p}=this.options,m=N(g)?g:Number.POSITIVE_INFINITY,x=this.chart._animationsDisabled||o||"none"===n,b=e+i,_=t.length;let y=e>0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=x?g:{};if(i<e||i>=b){_.skip=!0;continue}const v=this.getParsed(i),M=s(v[f]),w=_[u]=a.getPixelForValue(v[u],i),k=_[f]=o||M?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,v,l):v[f],i);_.skip=isNaN(w)||isNaN(k)||M,_.stop=i>0&&Math.abs(v[u]-y[u])>m,p&&(_.parsed=v,_.raw=h.data[i]),d&&(_.options=c||this.resolveDataElementOptions(i,g.active?"active":n)),x||this.updateElement(g,i,_,n),y=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends $n{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:Yn,RadarController:class extends js{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this._cachedMeta.rScale,o="reset"===s;for(let a=e;a<e+i;a++){const e=t[a],i=this.resolveDataElementOptions(a,e.active?"active":s),r=n.getPointPositionForValue(a,this.getParsed(a).r),l=o?n.xCenter:r.x,h=o?n.yCenter:r.y,c={x:l,y:h,angle:r.angle,skip:isNaN(l)||isNaN(h),options:i};this.updateElement(e,a,c,s)}}},ScatterController:class extends js{static id="scatter";static defaults={datasetElementType:!1,dataElementType:"point",showLine:!1,fill:!1};static overrides={interaction:{mode:"point"},scales:{x:{type:"linear"},y:{type:"linear"}}};getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y);return{label:i[t]||"",value:"("+a+", "+r+")"}}update(t){const e=this._cachedMeta,{data:i=[]}=e,s=this.chart._animationsDisabled;let{start:n,count:o}=pt(e,i,s);if(this._drawStart=n,this._drawCount=o,mt(e)&&(n=0,o=i.length),this.options.showLine){this.datasetElementType||this.addElements();const{dataset:n,_dataset:o}=e;n._chart=this.chart,n._datasetIndex=this.index,n._decimated=!!o._decimated,n.points=i;const a=this.resolveDatasetElementOptions(t);a.segment=this.options.segment,this.updateElement(n,void 0,{animated:!s,options:a},t)}else this.datasetElementType&&(delete e.dataset,this.datasetElementType=!1);this.updateElements(i,n,o,t)}addElements(){const{showLine:t}=this.options;!this.datasetElementType&&t&&(this.datasetElementType=this.chart.registry.getElement("line")),super.addElements()}updateElements(t,e,i,n){const o="reset"===n,{iScale:a,vScale:r,_stacked:l,_dataset:h}=this._cachedMeta,c=this.resolveDataElementOptions(e,n),d=this.getSharedOptions(c),u=this.includeOptions(n,d),f=a.axis,g=r.axis,{spanGaps:p,segment:m}=this.options,x=N(p)?p:Number.POSITIVE_INFINITY,b=this.chart._animationsDisabled||o||"none"===n;let _=e>0&&this.getParsed(e-1);for(let c=e;c<e+i;++c){const e=t[c],i=this.getParsed(c),p=b?e:{},y=s(i[g]),v=p[f]=a.getPixelForValue(i[f],c),M=p[g]=o||y?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,i,l):i[g],c);p.skip=isNaN(v)||isNaN(M)||y,p.stop=c>0&&Math.abs(i[f]-_[f])>x,m&&(p.parsed=i,p.raw=h.data[c]),u&&(p.options=d||this.resolveDataElementOptions(c,e.active?"active":n)),b||this.updateElement(e,c,p,n),_=i}this.updateSharedOptions(d,n,c)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let i=e.length-1;i>=0;--i)t=Math.max(t,e[i].size(this.resolveDataElementOptions(i))/2);return t>0&&t}const i=t.dataset,s=i.options&&i.options.borderWidth||0;if(!e.length)return s;const n=e[0].size(this.resolveDataElementOptions(0)),o=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(s,n,o)/2}}});function Xn(t,e,i,s){const n=vi(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return J(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:J(n.innerStart,0,a),innerEnd:J(n.innerEnd,0,a)}}function qn(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function Kn(t,e,i,s,n,o){const{x:a,y:r,startAngle:l,pixelMargin:h,innerRadius:c}=e,d=Math.max(e.outerRadius+s+i-h,0),u=c>0?c+s+i+h:0;let f=0;const g=n-l;if(s){const t=((c>0?c-s:0)+(d>0?d-s:0))/2;f=(g-(0!==t?g*t/(t+s):g))/2}const p=(g-Math.max(.001,g*d-i/C)/d)/2,m=l+p+f,x=n-p-f,{outerStart:b,outerEnd:_,innerStart:y,innerEnd:v}=Xn(e,u,d,x-m),M=d-b,w=d-_,k=m+b/M,S=x-_/w,P=u+y,D=u+v,O=m+y/P,A=x-v/D;if(t.beginPath(),o){const e=(k+S)/2;if(t.arc(a,r,d,k,e),t.arc(a,r,d,e,S),_>0){const e=qn(w,S,a,r);t.arc(e.x,e.y,_,S,x+E)}const i=qn(D,x,a,r);if(t.lineTo(i.x,i.y),v>0){const e=qn(D,A,a,r);t.arc(e.x,e.y,v,x+E,A+Math.PI)}const s=(x-v/u+(m+y/u))/2;if(t.arc(a,r,u,x-v/u,s,!0),t.arc(a,r,u,s,m+y/u,!0),y>0){const e=qn(P,O,a,r);t.arc(e.x,e.y,y,O+Math.PI,m-E)}const n=qn(M,m,a,r);if(t.lineTo(n.x,n.y),b>0){const e=qn(M,k,a,r);t.arc(e.x,e.y,b,m-E,k)}}else{t.moveTo(a,r);const e=Math.cos(k)*d+a,i=Math.sin(k)*d+r;t.lineTo(e,i);const s=Math.cos(S)*d+a,n=Math.sin(S)*d+r;t.lineTo(s,n)}t.closePath()}function Gn(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r,options:l}=e,{borderWidth:h,borderJoinStyle:c,borderDash:d,borderDashOffset:u}=l,f="inner"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,f?(t.lineWidth=2*h,t.lineJoin=c||"round"):(t.lineWidth=h,t.lineJoin=c||"bevel");let g=e.endAngle;if(o){Kn(t,e,i,s,g,n);for(let e=0;e<o;++e)t.stroke();isNaN(r)||(g=a+(r%O||O))}f&&function(t,e,i){const{startAngle:s,pixelMargin:n,x:o,y:a,outerRadius:r,innerRadius:l}=e;let h=n/r;t.beginPath(),t.arc(o,a,r,s-h,i+h),l>n?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+E,s-E),t.closePath(),t.clip()}(t,e,g),o||(Kn(t,e,i,s,g,n),t.stroke())}function Zn(t,e,i=e){t.lineCap=l(i.borderCapStyle,e.borderCapStyle),t.setLineDash(l(i.borderDash,e.borderDash)),t.lineDashOffset=l(i.borderDashOffset,e.borderDashOffset),t.lineJoin=l(i.borderJoinStyle,e.borderJoinStyle),t.lineWidth=l(i.borderWidth,e.borderWidth),t.strokeStyle=l(i.borderColor,e.borderColor)}function Jn(t,e,i){t.lineTo(i.x,i.y)}function Qn(t,e,i={}){const s=t.length,{start:n=0,end:o=s-1}=i,{start:a,end:r}=e,l=Math.max(n,a),h=Math.min(o,r),c=n<a&&o<a||n>r&&o>r;return{count:s,start:l,loop:e.loop,ilen:h<l&&!c?s+h-l:h-l}}function to(t,e,i,s){const{points:n,options:o}=e,{count:a,start:r,loop:l,ilen:h}=Qn(n,i,s),c=function(t){return t.stepped?Fe:t.tension||"monotone"===t.cubicInterpolationMode?Ve:Jn}(o);let d,u,f,{move:g=!0,reverse:p}=s||{};for(d=0;d<=h;++d)u=n[(r+(p?h-d:d))%a],u.skip||(g?(t.moveTo(u.x,u.y),g=!1):c(t,f,u,p,o.stepped),f=u);return l&&(u=n[(r+(p?h:0))%a],c(t,f,u,p,o.stepped)),!!l}function eo(t,e,i,s){const n=e.points,{count:o,start:a,ilen:r}=Qn(n,i,s),{move:l=!0,reverse:h}=s||{};let c,d,u,f,g,p,m=0,x=0;const b=t=>(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[b(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[b(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(i<f?f=i:i>g&&(g=i),m=(x*m+e)/++x):(_(),t.lineTo(e,i),u=s,x=0,f=g=i),p=i}_()}function io(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i)?eo:to}const so="function"==typeof Path2D;function no(t,e,i,s){so&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Zn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=io(e);for(const r of n)Zn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class oo extends $s{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||"monotone"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;hi(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=zi(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Ii(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?pi:t.tension||"monotone"===t.cubicInterpolationMode?mi:gi}(i);let l,h;for(l=0,h=o.length;l<h;++l){const{start:h,end:c}=o[l],d=n[h],u=n[c];if(d===u){a.push(d);continue}const f=r(d,u,Math.abs((s-d[e])/(u[e]-d[e])),i.stepped);f[e]=t[e],a.push(f)}return 1===a.length?a[0]:a}pathSegment(t,e,i){return io(this)(t,this,e,i)}path(t,e,i){const s=this.segments,n=io(this);let o=this._loop;e=e||0,i=i||this.points.length-e;for(const a of s)o&=n(t,this,a,{start:e,end:e+i-1});return!!o}draw(t,e,i,s){const n=this.options||{};(this.points||[]).length&&n.borderWidth&&(t.save(),no(t,this,i,s),t.restore()),this.animated&&(this._pointsUpdated=!1,this._path=void 0)}}function ao(t,e,i,s){const n=t.options,{[i]:o}=t.getProps([i],s);return Math.abs(e-o)<n.radius+n.hitRadius}function ro(t,e){const{x:i,y:s,base:n,width:o,height:a}=t.getProps(["x","y","base","width","height"],e);let r,l,h,c,d;return t.horizontal?(d=a/2,r=Math.min(i,n),l=Math.max(i,n),h=s-d,c=s+d):(d=o/2,r=i-d,l=i+d,h=Math.min(s,n),c=Math.max(s,n)),{left:r,top:h,right:l,bottom:c}}function lo(t,e,i,s){return t?0:J(e,i,s)}function ho(t){const e=ro(t),i=e.right-e.left,s=e.bottom-e.top,n=function(t,e,i){const s=t.options.borderWidth,n=t.borderSkipped,o=Mi(s);return{t:lo(n.top,o.top,0,i),r:lo(n.right,o.right,0,e),b:lo(n.bottom,o.bottom,0,i),l:lo(n.left,o.left,0,e)}}(t,i/2,s/2),a=function(t,e,i){const{enableBorderRadius:s}=t.getProps(["enableBorderRadius"]),n=t.options.borderRadius,a=wi(n),r=Math.min(e,i),l=t.borderSkipped,h=s||o(n);return{topLeft:lo(!h||l.top||l.left,a.topLeft,0,r),topRight:lo(!h||l.top||l.right,a.topRight,0,r),bottomLeft:lo(!h||l.bottom||l.left,a.bottomLeft,0,r),bottomRight:lo(!h||l.bottom||l.right,a.bottomRight,0,r)}}(t,i/2,s/2);return{outer:{x:e.left,y:e.top,w:i,h:s,radius:a},inner:{x:e.left+n.l,y:e.top+n.t,w:i-n.l-n.r,h:s-n.t-n.b,radius:{topLeft:Math.max(0,a.topLeft-Math.max(n.t,n.l)),topRight:Math.max(0,a.topRight-Math.max(n.t,n.r)),bottomLeft:Math.max(0,a.bottomLeft-Math.max(n.b,n.l)),bottomRight:Math.max(0,a.bottomRight-Math.max(n.b,n.r))}}}}function co(t,e,i,s){const n=null===e,o=null===i,a=t&&!(n&&o)&&ro(t,s);return a&&(n||tt(e,a.left,a.right))&&(o||tt(i,a.top,a.bottom))}function uo(t,e){t.rect(e.x,e.y,e.w,e.h)}function fo(t,e,i={}){const s=t.x!==i.x?-e:0,n=t.y!==i.y?-e:0,o=(t.x+t.w!==i.x+i.w?e:0)-s,a=(t.y+t.h!==i.y+i.h?e:0)-n;return{x:t.x+s,y:t.y+n,w:t.w+o,h:t.h+a,radius:t.radius}}var go=Object.freeze({__proto__:null,ArcElement:class extends $s{static id="arc";static defaults={borderAlign:"center",borderColor:"#fff",borderDash:[],borderDashOffset:0,borderJoinStyle:void 0,borderRadius:0,borderWidth:2,offset:0,spacing:0,angle:void 0,circular:!0};static defaultRoutes={backgroundColor:"backgroundColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.getProps(["x","y"],i),{angle:n,distance:o}=X(s,{x:t,y:e}),{startAngle:a,endAngle:r,innerRadius:h,outerRadius:c,circumference:d}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),u=(this.options.spacing+this.options.borderWidth)/2,f=l(d,r-a),g=Z(n,a,r)&&a!==r,p=f>=O||g,m=tt(o,h+u,c+u);return p&&m}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/4,n=(e.spacing||0)/2,o=e.circular;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=i>O?Math.floor(i/O):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();const a=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(a)*s,Math.sin(a)*s);const r=s*(1-Math.sin(Math.min(C,i||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r}=e;let l=e.endAngle;if(o){Kn(t,e,i,s,l,n);for(let e=0;e<o;++e)t.fill();isNaN(r)||(l=a+(r%O||O))}Kn(t,e,i,s,l,n),t.fill()}(t,this,r,n,o),Gn(t,this,r,n,o),t.restore()}},BarElement:class extends $s{static id="bar";static defaults={borderSkipped:"start",borderWidth:0,borderRadius:0,inflateAmount:"auto",pointStyle:void 0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};constructor(t){super(),this.options=void 0,this.horizontal=void 0,this.base=void 0,this.width=void 0,this.height=void 0,this.inflateAmount=void 0,t&&Object.assign(this,t)}draw(t){const{inflateAmount:e,options:{borderColor:i,backgroundColor:s}}=this,{inner:n,outer:o}=ho(this),a=(r=o.radius).topLeft||r.topRight||r.bottomLeft||r.bottomRight?He:uo;var r;t.save(),o.w===n.w&&o.h===n.h||(t.beginPath(),a(t,fo(o,e,n)),t.clip(),a(t,fo(n,-e,o)),t.fillStyle=i,t.fill("evenodd")),t.beginPath(),a(t,fo(n,e)),t.fillStyle=s,t.fill(),t.restore()}inRange(t,e,i){return co(this,t,e,i)}inXRange(t,e){return co(this,t,null,e)}inYRange(t,e){return co(this,null,t,e)}getCenterPoint(t){const{x:e,y:i,base:s,horizontal:n}=this.getProps(["x","y","base","horizontal"],t);return{x:n?(e+s)/2:e,y:n?i:(i+s)/2}}getRange(t){return"x"===t?this.width/2:this.height/2}},LineElement:oo,PointElement:class extends $s{static id="point";parsed;skip;stop;static defaults={borderWidth:1,hitRadius:1,hoverBorderWidth:1,hoverRadius:4,pointStyle:"circle",radius:3,rotation:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};constructor(t){super(),this.options=void 0,this.parsed=void 0,this.skip=void 0,this.stop=void 0,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.options,{x:n,y:o}=this.getProps(["x","y"],i);return Math.pow(t-n,2)+Math.pow(e-o,2)<Math.pow(s.hitRadius+s.radius,2)}inXRange(t,e){return ao(this,t,"x",e)}inYRange(t,e){return ao(this,t,"y",e)}getCenterPoint(t){const{x:e,y:i}=this.getProps(["x","y"],t);return{x:e,y:i}}size(t){let e=(t=t||this.options||{}).radius||0;e=Math.max(e,e&&t.hoverRadius||0);return 2*(e+(e&&t.borderWidth||0))}draw(t,e){const i=this.options;this.skip||i.radius<.1||!Re(this,e,this.size(i)/2)||(t.strokeStyle=i.borderColor,t.lineWidth=i.borderWidth,t.fillStyle=i.backgroundColor,Le(t,i,this.x,this.y))}getRange(){const t=this.options||{};return t.radius+t.hitRadius}}});function po(t,e,i,s){const n=t.indexOf(e);if(-1===n)return((t,e,i,s)=>("string"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}function mo(t){const e=this.getLabels();return t>=0&&t<e.length?e[t]:t}function xo(t,e,{horizontal:i,minRotation:s}){const n=$(s),o=(i?Math.sin(n):Math.cos(n))||.001,a=.75*e*(""+t).length;return Math.min(e/o,a)}class bo extends tn{constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._endValue=void 0,this._valueRange=0}parse(t,e){return s(t)||("number"==typeof t||t instanceof Number)&&!isFinite(+t)?null:+t}handleTickRangeOptions(){const{beginAtZero:t}=this.options,{minDefined:e,maxDefined:i}=this.getUserBounds();let{min:s,max:n}=this;const o=t=>s=e?s:t,a=t=>n=i?n:t;if(t){const t=F(s),e=F(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=0===n?1:Math.abs(.05*n);a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const n=function(t,e){const i=[],{bounds:n,step:o,min:a,max:r,precision:l,count:h,maxTicks:c,maxDigits:d,includeBounds:u}=t,f=o||1,g=c-1,{min:p,max:m}=e,x=!s(a),b=!s(r),_=!s(h),y=(m-p)/(d+1);let v,M,w,k,S=B((m-p)/g/f)*f;if(S<1e-14&&!x&&!b)return[{value:p},{value:m}];k=Math.ceil(m/S)-Math.floor(p/S),k>g&&(S=B(k*S/g/f)*f),s(l)||(v=Math.pow(10,l),S=Math.ceil(S*v)/v),"ticks"===n?(M=Math.floor(p/S)*S,w=Math.ceil(m/S)*S):(M=p,w=m),x&&b&&o&&H((r-a)/o,S/1e3)?(k=Math.round(Math.min((r-a)/S,c)),S=(r-a)/k,M=a,w=r):_?(M=x?a:M,w=b?r:w,k=h-1,S=(w-M)/k):(k=(w-M)/S,k=V(k,Math.round(k),S/1e3)?Math.round(k):Math.ceil(k));const P=Math.max(U(S),U(M));v=Math.pow(10,s(l)?P:l),M=Math.round(M*v)/v,w=Math.round(w*v)/v;let D=0;for(x&&(u&&M!==a?(i.push({value:a}),M<a&&D++,V(Math.round((M+D*S)*v)/v,a,xo(a,y,t))&&D++):M<a&&D++);D<k;++D){const t=Math.round((M+D*S)*v)/v;if(b&&t>r)break;i.push({value:t})}return b&&u&&w!==r?i.length&&V(i[i.length-1].value,r,xo(r,y,t))?i[i.length-1].value=r:i.push({value:r}):b&&w!==r||i.push({value:w}),i}({maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&j(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}configure(){const t=this.ticks;let e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){const s=(i-e)/Math.max(t.length-1,1)/2;e-=s,i+=s}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ne(t,this.chart.options.locale,this.options.ticks.format)}}class _o extends bo{static id="linear";static defaults={ticks:{callback:ae.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?t:0,this.max=a(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,i=$(this.options.ticks.minRotation),s=(t?Math.sin(i):Math.cos(i))||.001,n=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,n.lineHeight/s))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const yo=t=>Math.floor(z(t)),vo=(t,e)=>Math.pow(10,yo(t)+e);function Mo(t){return 1===t/Math.pow(10,yo(t))}function wo(t,e,i){const s=Math.pow(10,i),n=Math.floor(t/s);return Math.ceil(e/s)-n}function ko(t,{min:e,max:i}){e=r(t.min,e);const s=[],n=yo(e);let o=function(t,e){let i=yo(e-t);for(;wo(t,e,i)>10;)i++;for(;wo(t,e,i)<10;)i--;return Math.min(i,yo(t))}(e,i),a=o<0?Math.pow(10,Math.abs(o)):1;const l=Math.pow(10,o),h=n>o?Math.pow(10,n):0,c=Math.round((e-h)*a)/a,d=Math.floor((e-h)/l/10)*l*10;let u=Math.floor((c-d)/Math.pow(10,o)),f=r(t.min,Math.round((h+d+u*Math.pow(10,o))*a)/a);for(;f<i;)s.push({value:f,major:Mo(f),significand:u}),u>=10?u=u<15?15:20:u++,u>=20&&(o++,u=2,a=o>=0?1:a),f=Math.round((h+d+u*Math.pow(10,o))*a)/a;const g=r(t.max,f);return s.push({value:g,major:Mo(g),significand:u}),s}class So extends tn{static id="logarithmic";static defaults={ticks:{callback:ae.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const i=bo.prototype.parse.apply(this,[t,e]);if(0!==i)return a(i)&&i>0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?Math.max(0,t):null,this.max=a(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!a(this._userMin)&&(this.min=t===vo(this.min,0)?vo(this.min,-1):vo(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t;i===s&&(i<=0?(n(1),o(10)):(n(vo(i,-1)),o(vo(s,1)))),i<=0&&n(vo(s,-1)),s<=0&&o(vo(i,1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=ko({min:this._userMin,max:this._userMax},this);return"ticks"===t.bounds&&j(e,this,"value"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?"0":ne(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=z(t),this._valueRange=z(this.max)-z(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(z(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function Po(t){const e=t.ticks;if(e.display&&t.display){const t=ki(e.backdropPadding);return l(e.font&&e.font.size,ue.font.size)+t.height}return 0}function Do(t,e,i,s,n){return t===s||t===n?{start:e-i/2,end:e+i/2}:t<s||t>n?{start:e-i,end:e}:{start:e,end:e+i}}function Co(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],o=[],a=t._pointLabels.length,r=t.options.pointLabels,l=r.centerPointLabels?C/a:0;for(let u=0;u<a;u++){const a=r.setContext(t.getPointLabelContext(u));o[u]=a.padding;const f=t.getPointPosition(u,t.drawingArea+o[u],l),g=Si(a.font),p=(h=t.ctx,c=g,d=n(d=t._pointLabels[u])?d:[d],{w:Oe(h,c.string,d),h:d.length*c.lineHeight});s[u]=p;const m=G(t.getIndexAngle(u)+l),x=Math.round(Y(m));Oo(i,e,m,Do(x,f.x,p.w,0,180),Do(x,f.y,p.h,90,270))}var h,c,d;t.setCenterPoint(e.l-i.l,i.r-e.r,e.t-i.t,i.b-e.b),t._pointLabelItems=function(t,e,i){const s=[],n=t._pointLabels.length,o=t.options,{centerPointLabels:a,display:r}=o.pointLabels,l={extra:Po(o)/2,additionalAngle:a?C/n:0};let h;for(let o=0;o<n;o++){l.padding=i[o],l.size=e[o];const n=Ao(t,o,l);s.push(n),"auto"===r&&(n.visible=To(n,h),n.visible&&(h=n))}return s}(t,s,o)}function Oo(t,e,i,s,n){const o=Math.abs(Math.sin(i)),a=Math.abs(Math.cos(i));let r=0,l=0;s.start<e.l?(r=(e.l-s.start)/o,t.l=Math.min(t.l,e.l-r)):s.end>e.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.start<e.t?(l=(e.t-n.start)/a,t.t=Math.min(t.t,e.t-l)):n.end>e.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function Ao(t,e,i){const s=t.drawingArea,{extra:n,additionalAngle:o,padding:a,size:r}=i,l=t.getPointPosition(e,s+n+a,o),h=Math.round(Y(G(l.angle+E))),c=function(t,e,i){90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e);return t}(l.y,r.h,h),d=function(t){if(0===t||180===t)return"center";if(t<180)return"left";return"right"}(h),u=function(t,e,i){"right"===i?t-=e:"center"===i&&(t-=e/2);return t}(l.x,r.w,d);return{visible:!0,x:l.x,y:c,textAlign:d,left:u,top:c,right:u+r.w,bottom:c+r.h}}function To(t,e){if(!e)return!0;const{left:i,top:s,right:n,bottom:o}=t;return!(Re({x:i,y:s},e)||Re({x:i,y:o},e)||Re({x:n,y:s},e)||Re({x:n,y:o},e))}function Lo(t,e,i){const{left:n,top:o,right:a,bottom:r}=i,{backdropColor:l}=e;if(!s(l)){const i=wi(e.borderRadius),s=ki(e.backdropPadding);t.fillStyle=l;const h=n-s.left,c=o-s.top,d=a-n+s.width,u=r-o+s.height;Object.values(i).some((t=>0!==t))?(t.beginPath(),He(t,{x:h,y:c,w:d,h:u,radius:i}),t.fill()):t.fillRect(h,c,d,u)}}function Eo(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,O);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;o<s;o++)i=t.getPointPosition(o,e),n.lineTo(i.x,i.y)}}class Ro extends bo{static id="radialLinear";static defaults={display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,lineWidth:1,borderDash:[],borderDashOffset:0},grid:{circular:!1},startAngle:0,ticks:{showLabelBackdrop:!0,callback:ae.formatters.numeric},pointLabels:{backdropColor:void 0,backdropPadding:2,display:!0,font:{size:10},callback:t=>t,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ki(Po(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=a(t)&&!isNaN(t)?t:0,this.max=a(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/Po(this.options))}generateTickLabels(t){bo.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map(((t,e)=>{const i=d(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:""})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?Co(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return G(t*(O/(this._pointLabels.length||1))+$(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(s(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(s(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t<e.length){const i=e[t];return function(t,e,i){return Ci(t,{label:i,index:e,type:"pointLabel"})}(this.getContext(),t,i)}}getPointPosition(t,e,i=0){const s=this.getIndexAngle(t)-E+i;return{x:Math.cos(s)*e+this.xCenter,y:Math.sin(s)*e+this.yCenter,angle:s}}getPointPositionForValue(t,e){return this.getPointPosition(t,this.getDistanceFromCenterForValue(e))}getBasePosition(t){return this.getPointPositionForValue(t||0,this.getBaseValue())}getPointLabelPosition(t){const{left:e,top:i,right:s,bottom:n}=this._pointLabelItems[t];return{left:e,top:i,right:s,bottom:n}}drawBackground(){const{backgroundColor:t,grid:{circular:e}}=this.options;if(t){const i=this.ctx;i.save(),i.beginPath(),Eo(this,this.getDistanceFromCenterForValue(this._endValue),e,this._pointLabels.length),i.closePath(),i.fillStyle=t,i.fill(),i.restore()}}drawGrid(){const t=this.ctx,e=this.options,{angleLines:i,grid:s,border:n}=e,o=this._pointLabels.length;let a,r,l;if(e.pointLabels.display&&function(t,e){const{ctx:i,options:{pointLabels:s}}=t;for(let n=e-1;n>=0;n--){const e=t._pointLabelItems[n];if(!e.visible)continue;const o=s.setContext(t.getPointLabelContext(n));Lo(i,o,e);const a=Si(o.font),{x:r,y:l,textAlign:h}=e;Ne(i,t._pointLabels[n],r,l+a.lineHeight/2,a,{color:o.color,textAlign:h,textBaseline:"middle"})}}(this,o),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e||0===e&&this.min<0){r=this.getDistanceFromCenterForValue(t.value);const i=this.getContext(e),a=s.setContext(i),l=n.setContext(i);!function(t,e,i,s,n){const o=t.ctx,a=e.circular,{color:r,lineWidth:l}=e;!a&&!s||!r||!l||i<0||(o.save(),o.strokeStyle=r,o.lineWidth=l,o.setLineDash(n.dash||[]),o.lineDashOffset=n.dashOffset,o.beginPath(),Eo(t,i,a,s),o.closePath(),o.stroke(),o.restore())}(this,a,r,o,l)}})),i.display){for(t.save(),a=o-1;a>=0;a--){const s=i.setContext(this.getPointLabelContext(a)),{color:n,lineWidth:o}=s;o&&n&&(t.lineWidth=o,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,r=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),l=this.getPointPosition(a,r),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach(((s,a)=>{if(0===a&&this.min>=0&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=Si(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=ki(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}Ne(t,s.label,0,-n,l,{color:r.color,strokeColor:r.textStrokeColor,strokeWidth:r.textStrokeWidth})})),t.restore()}drawTitle(){}}const Io={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},zo=Object.keys(Io);function Fo(t,e){return t-e}function Vo(t,e){if(s(e))return null;const i=t._adapter,{parser:n,round:o,isoWeekday:r}=t._parseOpts;let l=e;return"function"==typeof n&&(l=n(l)),a(l)||(l="string"==typeof n?i.parse(l,n):i.parse(l)),null===l?null:(o&&(l="week"!==o||!N(r)&&!0!==r?i.startOf(l,o):i.startOf(l,"isoWeek",r)),+l)}function Bo(t,e,i,s){const n=zo.length;for(let o=zo.indexOf(t);o<n-1;++o){const t=Io[zo[o]],n=t.steps?t.steps:Number.MAX_SAFE_INTEGER;if(t.common&&Math.ceil((i-e)/(n*t.size))<=s)return zo[o]}return zo[n-1]}function Wo(t,e,i){if(i){if(i.length){const{lo:s,hi:n}=et(i,e);t[i[s]>=e?i[s]:i[n]]=!0}}else t[e]=!0}function No(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a<o;++a)r=e[a],n[r]=a,s.push({value:r,major:!1});return 0!==o&&i?function(t,e,i,s){const n=t._adapter,o=+n.startOf(e[0].value,s),a=e[e.length-1].value;let r,l;for(r=o;r<=a;r=+n.add(r,1,s))l=i[r],l>=0&&(e[l].major=!0);return e}(t,s,n,i):s}class Ho extends tn{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const i=t.time||(t.time={}),s=this._adapter=new In._date(t.adapters.date);s.init(e),b(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:Vo(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||"day";let{min:s,max:n,minDefined:o,maxDefined:r}=this.getUserBounds();function l(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),r||isNaN(t.max)||(n=Math.max(n,t.max))}o&&r||(l(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||l(this.getMinMax(!1))),s=a(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=a(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s="labels"===i.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=nt(s,n,this.max);return this._unit=e.unit||(i.autoSkip?Bo(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=zo.length-1;o>=zo.indexOf(i);o--){const i=zo[o];if(Io[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return zo[i?zo.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(t){for(let e=zo.indexOf(t)+1,i=zo.length;e<i;++e)if(Io[zo[e]].common)return zo[e]}(this._unit):void 0,this.initOffsets(s),t.reverse&&o.reverse(),No(this,o,this._majorUnit)}afterAutoSkip(){this.options.offsetAfterAutoskip&&this.initOffsets(this.ticks.map((t=>+t.value)))}initOffsets(t=[]){let e,i,s=0,n=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),n=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);const o=t.length<3?.5:.25;s=J(s,0,o),n=J(n,0,o),this._offsets={start:s,end:n,factor:1/(s+1+n)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,n=s.time,o=n.unit||Bo(n.minUnit,e,i,this._getLabelCapacity(e)),a=l(s.ticks.stepSize,1),r="week"===o&&n.isoWeekday,h=N(r)||!0===r,c={};let d,u,f=e;if(h&&(f=+t.startOf(f,"isoWeek",r)),f=+t.startOf(f,h?"day":o),t.diff(i,e,o)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+o);const g="data"===s.ticks.source&&this.getDataTimestamps();for(d=f,u=0;d<i;d=+t.add(d,a,o),u++)Wo(c,d,g);return d!==i&&"ticks"!==s.bounds&&1!==u||Wo(c,d,g),Object.keys(c).sort(Fo).map((t=>+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){const i=this.options.time.displayFormats,s=this._unit,n=e||i[s];return this._adapter.format(t,n)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.ticks.callback;if(o)return d(o,[t,e,i],this);const a=n.time.displayFormats,r=this._unit,l=this._majorUnit,h=r&&a[r],c=l&&a[l],u=i[e],f=l&&c&&u&&u.major;return this._adapter.format(t,s||(f?c:h))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e<i;++e)s=t[e],s.label=this._tickFormatFunction(s.value,e,t)}getDecimalForValue(t){return null===t?NaN:(t-this.min)/(this.max-this.min)}getPixelForValue(t){const e=this._offsets,i=this.getDecimalForValue(t);return this.getPixelForDecimal((e.start+i)*e.factor)}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return this.min+i*(this.max-this.min)}_getLabelSize(t){const e=this.options.ticks,i=this.ctx.measureText(t).width,s=$(this.isHorizontal()?e.maxRotation:e.minRotation),n=Math.cos(s),o=Math.sin(s),a=this._resolveTickFontOptions(0).size;return{w:i*n+a*o,h:i*o+a*n}}_getLabelCapacity(t){const e=this.options.time,i=e.displayFormats,s=i[e.unit]||i.millisecond,n=this._tickFormatFunction(t,0,No(this,[t],this._majorUnit),s),o=this._getLabelSize(n),a=Math.floor(this.isHorizontal()?this.width/o.w:this.height/o.h)-1;return a>0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t<e;++t)i=i.concat(s[t].controller.getAllParsedValues(this));return this._cache.data=this.normalize(i)}getLabelTimestamps(){const t=this._cache.labels||[];let e,i;if(t.length)return t;const s=this.getLabels();for(e=0,i=s.length;e<i;++e)t.push(Vo(this,s[e]));return this._cache.labels=this._normalized?t:this.normalize(t)}normalize(t){return lt(t.sort(Fo))}}function jo(t,e,i){let s,n,o,a,r=0,l=t.length-1;i?(e>=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=it(t,"pos",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=it(t,"time",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}var $o=Object.freeze({__proto__:null,CategoryScale:class extends tn{static id="category";static defaults={ticks:{callback:mo}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(s(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:J(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:po(i,t,l(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){return mo.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return"number"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:_o,LogarithmicScale:So,RadialLinearScale:Ro,TimeScale:Ho,TimeSeriesScale:class extends Ho{static id="timeseries";static defaults=Ho.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=jo(e,this.min),this._tableRange=jo(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o<a;++o)l=t[o],l>=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;o<a;++o)h=s[o+1],r=s[o-1],l=s[o],Math.round((h+r)/2)!==l&&n.push({time:l,pos:o/(a-1)});return n}_generate(){const t=this.min,e=this.max;let i=super.getDataTimestamps();return i.includes(t)&&i.length||i.splice(0,0,t),i.includes(e)&&1!==i.length||i.push(e),i.sort(((t,e)=>t-e))}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),i=this.getLabelTimestamps();return t=e.length&&i.length?this.normalize(e.concat(i)):e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(jo(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return jo(this._table,i*this._tableRange+this._minPos,!0)}}});const Yo=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],Uo=Yo.map((t=>t.replace("rgb(","rgba(").replace(")",", 0.5)")));function Xo(t){return Yo[t%Yo.length]}function qo(t){return Uo[t%Uo.length]}function Ko(t){let e=0;return(i,s)=>{const n=t.getDatasetMeta(s).controller;n instanceof $n?e=function(t,e){return t.backgroundColor=t.data.map((()=>Xo(e++))),e}(i,e):n instanceof Yn?e=function(t,e){return t.backgroundColor=t.data.map((()=>qo(e++))),e}(i,e):n&&(e=function(t,e){return t.borderColor=Xo(e),t.backgroundColor=qo(e),++e}(i,e))}}function Go(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var Zo={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(!i.enabled)return;const{data:{datasets:s},options:n}=t.config,{elements:o}=n,a=Go(s)||(r=n)&&(r.borderColor||r.backgroundColor)||o&&Go(o)||"rgba(0,0,0,0.1)"!==ue.borderColor||"rgba(0,0,0,0.1)"!==ue.backgroundColor;var r;if(!i.forceOverride&&a)return;const l=Ko(t);s.forEach(l)}};function Jo(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function Qo(t){t.data.datasets.forEach((t=>{Jo(t)}))}var ta={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void Qo(t);const n=t.width;t.data.datasets.forEach(((e,o)=>{const{_data:a,indexAxis:r}=e,l=t.getDatasetMeta(o),h=a||e.data;if("y"===Pi([r,t.options.indexAxis]))return;if(!l.controller.supportsDecimation)return;const c=t.scales[l.xAxisID];if("linear"!==c.type&&"time"!==c.type)return;if(t.options.parsing)return;let{start:d,count:u}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=J(it(e,o.axis,a).lo,0,i-1)),s=h?J(it(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(l,h);if(u<=(i.threshold||4*n))return void Jo(e);let f;switch(s(a)&&(e._data=h,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case"lttb":f=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;c<o-2;c++){let s,n=0,o=0;const h=Math.floor((c+1)*r)+1+e,m=Math.min(Math.floor((c+2)*r)+1,i)+e,x=m-h;for(s=h;s<m;s++)n+=t[s].x,o+=t[s].y;n/=x,o/=x;const b=Math.floor(c*r)+1+e,_=Math.min(Math.floor((c+1)*r)+1,i)+e,{x:y,y:v}=t[p];for(u=f=-1,s=b;s<_;s++)f=.5*Math.abs((y-n)*(t[s].y-v)-(y-t[s].x)*(o-v)),f>u&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(h,d,u,n,i);break;case"min-max":f=function(t,e,i,n){let o,a,r,l,h,c,d,u,f,g,p=0,m=0;const x=[],b=e+i-1,_=t[e].x,y=t[b].x-_;for(o=e;o<e+i;++o){a=t[o],r=(a.x-_)/y*n,l=a.y;const e=0|r;if(e===h)l<f?(f=l,c=o):l>g&&(g=l,d=o),p=(m*p+a.x)/++m;else{const i=o-1;if(!s(c)&&!s(d)){const e=Math.min(c,d),s=Math.max(c,d);e!==u&&e!==i&&x.push({...t[e],x:p}),s!==u&&s!==i&&x.push({...t[s],x:p})}o>0&&i!==u&&x.push(t[i]),x.push(a),h=e,m=0,f=g=l,c=d=u=o}}return x}(h,d,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=f}))},destroy(t){Qo(t)}};function ea(t,e,i,s){if(s)return;let n=e[t],o=i[t];return"angle"===t&&(n=G(n),o=G(o)),{property:t,start:n,end:o}}function ia(t,e,i){for(;e>t;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function sa(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function na(t,e){let i=[],s=!1;return n(t)?(s=!0,i=t):i=function(t,e){const{x:i=null,y:s=null}=t||{},n=e.points,o=[];return e.segments.forEach((({start:t,end:e})=>{e=ia(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new oo({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function oa(t){return t&&!1!==t.fill}function aa(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!a(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function ra(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=l(i&&i.target,i);void 0===s&&(s=!!e.backgroundColor);if(!1===s||null===s)return!1;if(!0===s)return"origin";return s}(t);if(o(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return a(n)&&Math.floor(n)===n?function(t,e,i,s){"-"!==t&&"+"!==t||(i=e+i);if(i===e||i<0||i>=s)return!1;return i}(s[0],e,n,i):["origin","start","end","stack","shape"].indexOf(s)>=0&&s}function la(t,e,i){const s=[];for(let n=0;n<i.length;n++){const o=i[n],{first:a,last:r,point:l}=ha(o,e,"x");if(!(!l||a&&r))if(a)s.unshift(l);else if(t.push(l),!r)break}t.push(...s)}function ha(t,e,i){const s=t.interpolate(e,i);if(!s)return{};const n=s[i],o=t.segments,a=t.points;let r=!1,l=!1;for(let t=0;t<o.length;t++){const e=o[t],s=a[e.start][i],h=a[e.end][i];if(tt(n,s,h)){r=n===s,l=n===h;break}}return{first:r,last:l,point:s}}class ca{constructor(t){this.x=t.x,this.y=t.y,this.radius=t.radius}pathSegment(t,e,i){const{x:s,y:n,radius:o}=this;return e=e||{start:0,end:O},t.arc(s,n,o,e.end,e.start,!0),!i.bounds}interpolate(t){const{x:e,y:i,radius:s}=this,n=t.angle;return{x:e+Math.cos(n)*s,y:i+Math.sin(n)*s,angle:n}}}function da(t){const{chart:e,fill:i,line:s}=t;if(a(i))return function(t,e){const i=t.getDatasetMeta(e),s=i&&t.isDatasetVisible(e);return s?i.dataset:null}(e,i);if("stack"===i)return function(t){const{scale:e,index:i,line:s}=t,n=[],o=s.segments,a=s.points,r=function(t,e){const i=[],s=t.getMatchingVisibleMetas("line");for(let t=0;t<s.length;t++){const n=s[t];if(n.index===e)break;n.hidden||i.unshift(n.dataset)}return i}(e,i);r.push(na({x:null,y:e.bottom},s));for(let t=0;t<o.length;t++){const e=o[t];for(let t=e.start;t<=e.end;t++)la(n,a[t],r)}return new oo({points:n,options:{}})}(t);if("shape"===i)return!0;const n=function(t){const e=t.scale||{};if(e.getPointPositionForValue)return function(t){const{scale:e,fill:i}=t,s=e.options,n=e.getLabels().length,a=s.reverse?e.max:e.min,r=function(t,e,i){let s;return s="start"===t?i:"end"===t?e.options.reverse?e.min:e.max:o(t)?t.value:e.getBaseValue(),s}(i,e,a),l=[];if(s.grid.circular){const t=e.getPointPositionForValue(0,a);return new ca({x:t.x,y:t.y,radius:e.getDistanceFromCenterForValue(r)})}for(let t=0;t<n;++t)l.push(e.getPointPositionForValue(t,r));return l}(t);return function(t){const{scale:e={},fill:i}=t,s=function(t,e){let i=null;return"start"===t?i=e.bottom:"end"===t?i=e.top:o(t)?i=e.getPixelForValue(t.value):e.getBasePixel&&(i=e.getBasePixel()),i}(i,e);if(a(s)){const t=e.isHorizontal();return{x:t?s:null,y:t?null:s}}return null}(t)}(t);return n instanceof ca?n:na(n,s)}function ua(t,e,i){const s=da(e),{chart:n,index:o,line:a,scale:r,axis:l}=e,h=a.options,c=h.fill,d=h.backgroundColor,{above:u=d,below:f=d}=c||{},g=n.getDatasetMeta(o),p=Ni(n,g);s&&a.points.length&&(Ie(t,i),function(t,e){const{line:i,target:s,above:n,below:o,area:a,scale:r,clip:l}=e,h=i._loop?"angle":e.axis;t.save(),"x"===h&&o!==n&&(fa(t,s,a.top),ga(t,{line:i,target:s,color:n,scale:r,property:h,clip:l}),t.restore(),t.save(),fa(t,s,a.bottom));ga(t,{line:i,target:s,color:o,scale:r,property:h,clip:l}),t.restore()}(t,{line:a,target:s,above:u,below:f,area:i,scale:r,axis:l,clip:p}),ze(t))}function fa(t,e,i){const{segments:s,points:n}=e;let o=!0,a=!1;t.beginPath();for(const r of s){const{start:s,end:l}=r,h=n[s],c=n[ia(s,l,n)];o?(t.moveTo(h.x,h.y),o=!1):(t.lineTo(h.x,i),t.lineTo(h.x,h.y)),a=!!e.pathSegment(t,r,{move:a}),a?t.closePath():t.lineTo(c.x,i)}t.lineTo(e.first().x,i),t.closePath(),t.clip()}function ga(t,e){const{line:i,target:s,property:n,color:o,scale:a,clip:r}=e,l=function(t,e,i){const s=t.segments,n=t.points,o=e.points,a=[];for(const t of s){let{start:s,end:r}=t;r=ia(s,r,n);const l=ea(i,n[s],n[r],t.loop);if(!e.segments){a.push({source:t,target:l,start:n[s],end:n[r]});continue}const h=Ii(e,l);for(const e of h){const s=ea(i,o[e.start],o[e.end],e.loop),r=Ri(t,n,s);for(const t of r)a.push({source:t,target:e,start:{[i]:sa(l,s,"start",Math.max)},end:{[i]:sa(l,s,"end",Math.min)}})}}return a}(i,s,n);for(const{source:e,target:h,start:c,end:d}of l){const{style:{backgroundColor:l=o}={}}=e,u=!0!==s;t.save(),t.fillStyle=l,pa(t,a,r,u&&ea(n,c,d)),t.beginPath();const f=!!i.pathSegment(t,e);let g;if(u){f?t.closePath():ma(t,s,d,n);const e=!!s.pathSegment(t,h,{move:f,reverse:!0});g=f&&e,g||ma(t,s,c,n)}t.closePath(),t.fill(g?"evenodd":"nonzero"),t.restore()}}function pa(t,e,i,s){const n=e.chart.chartArea,{property:o,start:a,end:r}=s||{};if("x"===o||"y"===o){let e,s,l,h;"x"===o?(e=a,s=n.top,l=r,h=n.bottom):(e=n.left,s=a,l=n.right,h=r),t.beginPath(),i&&(e=Math.max(e,i.left),l=Math.min(l,i.right),s=Math.max(s,i.top),h=Math.min(h,i.bottom)),t.rect(e,s,l-e,h-s),t.clip()}}function ma(t,e,i,s){const n=e.interpolate(i,s);n&&t.lineTo(n.x,n.y)}var xa={id:"filler",afterDatasetsUpdate(t,e,i){const s=(t.data.datasets||[]).length,n=[];let o,a,r,l;for(a=0;a<s;++a)o=t.getDatasetMeta(a),r=o.dataset,l=null,r&&r.options&&r instanceof oo&&(l={visible:t.isDatasetVisible(a),index:a,fill:ra(r,a,s),chart:t,axis:o.controller.options.indexAxis,scale:o.vScale,line:r}),o.$filler=l,n.push(l);for(a=0;a<s;++a)l=n[a],l&&!1!==l.fill&&(l.fill=aa(n,a,i.propagate))},beforeDraw(t,e,i){const s="beforeDraw"===i.drawTime,n=t.getSortedVisibleDatasetMetas(),o=t.chartArea;for(let e=n.length-1;e>=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&i.fill&&ua(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if("beforeDatasetsDraw"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;oa(i)&&ua(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;oa(s)&&"beforeDatasetDraw"===i.drawTime&&ua(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const ba=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class _a extends $s{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=d(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=Si(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=ba(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,s,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign="left",n.textBaseline="middle";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const{itemWidth:p,itemHeight:m}=function(t,e,i,s,n){const o=function(t,e,i,s){let n=t.text;n&&"string"!=typeof n&&(n=n.reduce(((t,e)=>t.length>e.length?t:e)));return e+i.size/2+s.measureText(n).width}(s,t,e,i),a=function(t,e,i){let s=t;"string"!=typeof e.text&&(s=ya(e,i));return s}(n,s,e.lineHeight);return{itemWidth:o,itemHeight:a}}(i,e,n,t,s);o>0&&u+m+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:m},d=Math.max(d,p),u+=m+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:n}}=this,o=Oi(n,this.left,this.width);if(this.isHorizontal()){let n=0,a=ft(i,this.left+s,this.right-this.lineWidths[n]);for(const r of e)n!==r.row&&(n=r.row,a=ft(i,this.left+s,this.right-this.lineWidths[n])),r.top+=this.top+t+s,r.left=o.leftForLtr(o.x(a),r.width),a+=r.width+s}else{let n=0,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height);for(const r of e)r.col!==n&&(n=r.col,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height)),r.top=a,r.left+=this.left+s,r.left=o.leftForLtr(o.x(r.left),r.width),a+=r.height+s}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Ie(t,this),this._draw(),ze(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:n,labels:o}=t,a=ue.color,r=Oi(t.rtl,this.left,this.width),h=Si(o.font),{padding:c}=o,d=h.size,u=d/2;let f;this.drawTitle(),s.textAlign=r.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=h.string;const{boxWidth:g,boxHeight:p,itemHeight:m}=ba(o,d),x=this.isHorizontal(),b=this._computeTitleHeight();f=x?{x:ft(n,this.left+c,this.right-i[0]),y:this.top+c+b,line:0}:{x:this.left+c,y:ft(n,this.top+b+c,this.bottom-e[0].height),line:0},Ai(this.ctx,t.textDirection);const _=m+c;this.legendItems.forEach(((y,v)=>{s.strokeStyle=y.fontColor,s.fillStyle=y.fontColor;const M=s.measureText(y.text).width,w=r.textAlign(y.textAlign||(y.textAlign=o.textAlign)),k=g+u+M;let S=f.x,P=f.y;r.setWidth(this.width),x?v>0&&S+k+c>this.right&&(P=f.y+=_,f.line++,S=f.x=ft(n,this.left+c,this.right-i[f.line])):v>0&&P+_>this.bottom&&(S=f.x=S+e[f.line].width+c,f.line++,P=f.y=ft(n,this.top+b+c,this.bottom-e[f.line].height));if(function(t,e,i){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;s.save();const n=l(i.lineWidth,1);if(s.fillStyle=l(i.fillStyle,a),s.lineCap=l(i.lineCap,"butt"),s.lineDashOffset=l(i.lineDashOffset,0),s.lineJoin=l(i.lineJoin,"miter"),s.lineWidth=n,s.strokeStyle=l(i.strokeStyle,a),s.setLineDash(l(i.lineDash,[])),o.usePointStyle){const a={radius:p*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},l=r.xPlus(t,g/2);Ee(s,a,l,e+u,o.pointStyleWidth&&g)}else{const o=e+Math.max((d-p)/2,0),a=r.leftForLtr(t,g),l=wi(i.borderRadius);s.beginPath(),Object.values(l).some((t=>0!==t))?He(s,{x:a,y:o,w:g,h:p,radius:l}):s.rect(a,o,g,p),s.fill(),0!==n&&s.stroke()}s.restore()}(r.x(S),P,y),S=gt(w,S+g+u,x?S+k:this.right,t.rtl),function(t,e,i){Ne(s,i.text,t,e+m/2,h,{strikethrough:i.hidden,textAlign:r.textAlign(i.textAlign)})}(r.x(S),P,y),x)f.x+=k+c;else if("string"!=typeof y.text){const t=h.lineHeight;f.y+=ya(y,t)+c}else f.y+=_})),Ti(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=Si(e.font),s=ki(e.padding);if(!e.display)return;const n=Oi(t.rtl,this.left,this.width),o=this.ctx,a=e.position,r=i.size/2,l=s.top+r;let h,c=this.left,d=this.width;if(this.isHorizontal())d=Math.max(...this.lineWidths),h=this.top+l,c=ft(t.align,c,this.right-d);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);h=l+ft(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const u=ft(a,c,c+d);o.textAlign=n.textAlign(ut(a)),o.textBaseline="middle",o.strokeStyle=e.color,o.fillStyle=e.color,o.font=i.string,Ne(o,e.text,u,h,i)}_computeTitleHeight(){const t=this.options.title,e=Si(t.font),i=ki(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(tt(t,this.left,this.right)&&tt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;i<n.length;++i)if(s=n[i],tt(t,s.left,s.left+s.width)&&tt(e,s.top,s.top+s.height))return this.legendItems[i];return null}handleEvent(t){const e=this.options;if(!function(t,e){if(("mousemove"===t||"mouseout"===t)&&(e.onHover||e.onLeave))return!0;if(e.onClick&&("click"===t||"mouseup"===t))return!0;return!1}(t.type,e))return;const i=this._getLegendItemAt(t.x,t.y);if("mousemove"===t.type||"mouseout"===t.type){const o=this._hoveredItem,a=(n=i,null!==(s=o)&&null!==n&&s.datasetIndex===n.datasetIndex&&s.index===n.index);o&&!a&&d(e.onLeave,[t,o,this],this),this._hoveredItem=i,i&&!a&&d(e.onHover,[t,i,this],this)}else i&&d(e.onClick,[t,i,this],this);var s,n}}function ya(t,e){return e*(t.text?t.text.length:0)}var va={id:"legend",_element:_a,start(t,e,i){const s=t.legend=new _a({ctx:t.ctx,options:i,chart:t});ls.configure(t,s,i),ls.addBox(t,s)},stop(t){ls.removeBox(t,t.legend),delete t.legend},beforeUpdate(t,e,i){const s=t.legend;ls.configure(t,s,i),s.options=i},afterUpdate(t){const e=t.legend;e.buildLabels(),e.adjustHitBoxes()},afterEvent(t,e){e.replay||t.legend.handleEvent(e.event)},defaults:{display:!0,position:"top",align:"center",fullSize:!0,reverse:!1,weight:1e3,onClick(t,e,i){const s=e.datasetIndex,n=i.chart;n.isDatasetVisible(s)?(n.hide(s),e.hidden=!0):(n.show(s),e.hidden=!1)},onHover:null,onLeave:null,labels:{color:t=>t.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o,useBorderRadius:a,borderRadius:r}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const l=t.controller.getStyle(i?0:void 0),h=ki(l.borderWidth);return{text:e[t.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(h.width+h.height)/4,strokeStyle:l.borderColor,pointStyle:s||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:a&&(r||l.borderRadius),datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class Ma extends $s{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=n(i.text)?i.text.length:1;this._padding=ki(i.padding);const o=s*Si(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:n,options:o}=this,a=o.align;let r,l,h,c=0;return this.isHorizontal()?(l=ft(a,i,n),h=e+t,r=n-i):("left"===o.position?(l=i+t,h=ft(a,s,e),c=-.5*C):(l=n-t,h=ft(a,e,s),c=.5*C),r=s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=Si(e.font),s=i.lineHeight/2+this._padding.top,{titleX:n,titleY:o,maxWidth:a,rotation:r}=this._drawArgs(s);Ne(t,e.text,0,0,i,{color:e.color,maxWidth:a,rotation:r,textAlign:ut(e.align),textBaseline:"middle",translation:[n,o]})}}var wa={id:"title",_element:Ma,start(t,e,i){!function(t,e){const i=new Ma({ctx:t.ctx,options:e,chart:t});ls.configure(t,i,e),ls.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;ls.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const ka=new WeakMap;var Sa={id:"subtitle",start(t,e,i){const s=new Ma({ctx:t.ctx,options:i,chart:t});ls.configure(t,s,i),ls.addBox(t,s),ka.set(t,s)},stop(t){ls.removeBox(t,ka.get(t)),ka.delete(t)},beforeUpdate(t,e,i){const s=ka.get(t);ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Pa={average(t){if(!t.length)return!1;let e,i,s=new Set,n=0,o=0;for(e=0,i=t.length;e<i;++e){const i=t[e].element;if(i&&i.hasValue()){const t=i.tooltipPosition();s.add(t.x),n+=t.y,++o}}if(0===o||0===s.size)return!1;return{x:[...s].reduce(((t,e)=>t+e))/s.size,y:n/o}},nearest(t,e){if(!t.length)return!1;let i,s,n,o=e.x,a=e.y,r=Number.POSITIVE_INFINITY;for(i=0,s=t.length;i<s;++i){const s=t[i].element;if(s&&s.hasValue()){const t=q(e,s.getCenterPoint());t<r&&(r=t,n=s)}}if(n){const t=n.tooltipPosition();o=t.x,a=t.y}return{x:o,y:a}}};function Da(t,e){return e&&(n(e)?Array.prototype.push.apply(t,e):t.push(e)),t}function Ca(t){return("string"==typeof t||t instanceof String)&&t.indexOf("\n")>-1?t.split("\n"):t}function Oa(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Aa(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=Si(e.bodyFont),h=Si(e.titleFont),c=Si(e.footerFont),d=o.length,f=n.length,g=s.length,p=ki(e.padding);let m=p.height,x=0,b=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(b+=t.beforeBody.length+t.afterBody.length,d&&(m+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),b){m+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(b-g)*l.lineHeight+(b-1)*e.bodySpacing}f&&(m+=e.footerMarginTop+f*c.lineHeight+(f-1)*e.footerSpacing);let _=0;const y=function(t){x=Math.max(x,i.measureText(t).width+_)};return i.save(),i.font=h.string,u(t.title,y),i.font=l.string,u(t.beforeBody.concat(t.afterBody),y),_=e.displayColors?a+2+e.boxPadding:0,u(s,(t=>{u(t.before,y),u(t.lines,y),u(t.after,y)})),_=0,i.font=c.string,u(t.footer,y),i.restore(),x+=p.width,{width:x,height:m}}function Ta(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h="center";return"center"===s?h=n<=(r+l)/2?"left":"right":n<=o/2?h="left":n>=a-o/2&&(h="right"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return"left"===t&&n+o+a>e.width||"right"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h="center"),h}function La(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return i<s/2?"top":i>t.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||Ta(t,e,i,s),yAlign:s}}function Ea(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(a);let g=function(t,e){let{x:i,width:s}=t;return"right"===e?i-=s:"center"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return"top"===e?s+=i:s-="bottom"===e?n+i:n/2,s}(e,l,h);return"center"===l?"left"===r?g+=h:"right"===r&&(g-=h):"left"===r?g-=Math.max(c,u)+n:"right"===r&&(g+=Math.max(d,f)+n),{x:J(g,0,s.width-e.width),y:J(p,0,s.height-e.height)}}function Ra(t,e,i){const s=ki(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-s.right:t.x+s.left}function Ia(t){return Da([],Ca(t))}function za(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const Fa={beforeTitle:e,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex<s)return i[e.dataIndex]}return""},afterTitle:e,beforeBody:e,beforeLabel:e,label(t){if(this&&this.options&&"dataset"===this.options.mode)return t.label+": "+t.formattedValue||t.formattedValue;let e=t.dataset.label||"";e&&(e+=": ");const i=t.formattedValue;return s(i)||(e+=i),e},labelColor(t){const e=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{borderColor:e.borderColor,backgroundColor:e.backgroundColor,borderWidth:e.borderWidth,borderDash:e.borderDash,borderDashOffset:e.borderDashOffset,borderRadius:0}},labelTextColor(){return this.options.bodyColor},labelPointStyle(t){const e=t.chart.getDatasetMeta(t.datasetIndex).controller.getStyle(t.dataIndex);return{pointStyle:e.pointStyle,rotation:e.rotation}},afterLabel:e,afterBody:e,beforeFooter:e,footer:e,afterFooter:e};function Va(t,e,i,s){const n=t[e].call(i,s);return void 0===n?Fa[e].call(i,s):n}class Ba extends $s{static positioners=Pa;constructor(t){super(),this.opacity=0,this._active=[],this._eventPosition=void 0,this._size=void 0,this._cachedAnimations=void 0,this._tooltipItems=[],this.$animations=void 0,this.$context=void 0,this.chart=t.chart,this.options=t.options,this.dataPoints=void 0,this.title=void 0,this.beforeBody=void 0,this.body=void 0,this.afterBody=void 0,this.footer=void 0,this.xAlign=void 0,this.yAlign=void 0,this.x=void 0,this.y=void 0,this.height=void 0,this.width=void 0,this.caretX=void 0,this.caretY=void 0,this.labelColors=void 0,this.labelPointStyles=void 0,this.labelTextColors=void 0}initialize(t){this.options=t,this._cachedAnimations=void 0,this.$context=void 0}_resolveAnimations(){const t=this._cachedAnimations;if(t)return t;const e=this.chart,i=this.options.setContext(this.getContext()),s=i.enabled&&e.options.animation&&i.animations,n=new Ts(this.chart,s);return s._cacheable&&(this._cachedAnimations=Object.freeze(n)),n}getContext(){return this.$context||(this.$context=(t=this.chart.getContext(),e=this,i=this._tooltipItems,Ci(t,{tooltip:e,tooltipItems:i,type:"tooltip"})));var t,e,i}getTitle(t,e){const{callbacks:i}=e,s=Va(i,"beforeTitle",this,t),n=Va(i,"title",this,t),o=Va(i,"afterTitle",this,t);let a=[];return a=Da(a,Ca(s)),a=Da(a,Ca(n)),a=Da(a,Ca(o)),a}getBeforeBody(t,e){return Ia(Va(e.callbacks,"beforeBody",this,t))}getBody(t,e){const{callbacks:i}=e,s=[];return u(t,(t=>{const e={before:[],lines:[],after:[]},n=za(i,t);Da(e.before,Ca(Va(n,"beforeLabel",this,t))),Da(e.lines,Va(n,"label",this,t)),Da(e.after,Ca(Va(n,"afterLabel",this,t))),s.push(e)})),s}getAfterBody(t,e){return Ia(Va(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:i}=e,s=Va(i,"beforeFooter",this,t),n=Va(i,"footer",this,t),o=Va(i,"afterFooter",this,t);let a=[];return a=Da(a,Ca(s)),a=Da(a,Ca(n)),a=Da(a,Ca(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;a<r;++a)l.push(Oa(this.chart,e[a]));return t.filter&&(l=l.filter(((e,s,n)=>t.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=za(t.callbacks,e);s.push(Va(i,"labelColor",this,e)),n.push(Va(i,"labelPointStyle",this,e)),o.push(Va(i,"labelTextColor",this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=Pa[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Aa(this,i),a=Object.assign({},t,e),r=La(this.chart,i,a),l=Ea(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=wi(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,x,b,_,y;return"center"===n?(_=u+g/2,"left"===s?(p=d,m=p-o,b=_+o,y=_-o):(p=d+f,m=p+o,b=_-o,y=_+o),x=p):(m="left"===s?d+Math.max(r,h)+o:"right"===s?d+f-Math.max(l,c)-o:this.caretX,"top"===n?(b=u,_=b-o,p=m-o,x=m+o):(b=u+g,_=b+o,p=m+o,x=m-o),y=b),{x1:p,x2:m,x3:x,y1:b,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Oi(i.rtl,this.x,this.width);for(t.x=Ra(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",o=Si(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r<n;++r)e.fillText(s[r],l.x(t.x),t.y+o.lineHeight/2),t.y+=o.lineHeight+a,r+1===n&&(t.y+=i.titleMarginBottom-a)}}_drawColorBox(t,e,i,s,n){const a=this.labelColors[i],r=this.labelPointStyles[i],{boxHeight:l,boxWidth:h}=n,c=Si(n.bodyFont),d=Ra(this,"left",n),u=s.x(d),f=l<c.lineHeight?(c.lineHeight-l)/2:0,g=e.y+f;if(n.usePointStyle){const e={radius:Math.min(h,l)/2,pointStyle:r.pointStyle,rotation:r.rotation,borderWidth:1},i=s.leftForLtr(u,h)+h/2,o=g+l/2;t.strokeStyle=n.multiKeyBackground,t.fillStyle=n.multiKeyBackground,Le(t,e,i,o),t.strokeStyle=a.borderColor,t.fillStyle=a.backgroundColor,Le(t,e,i,o)}else{t.lineWidth=o(a.borderWidth)?Math.max(...Object.values(a.borderWidth)):a.borderWidth||1,t.strokeStyle=a.borderColor,t.setLineDash(a.borderDash||[]),t.lineDashOffset=a.borderDashOffset||0;const e=s.leftForLtr(u,h),i=s.leftForLtr(s.xPlus(u,1),h-2),r=wi(a.borderRadius);Object.values(r).some((t=>0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,He(t,{x:e,y:g,w:h,h:l,radius:r}),t.fill(),t.stroke(),t.fillStyle=a.backgroundColor,t.beginPath(),He(t,{x:i,y:g+1,w:h-2,h:l-2,radius:r}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,h,l),t.strokeRect(e,g,h,l),t.fillStyle=a.backgroundColor,t.fillRect(i,g+1,h-2,l-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=Si(i.bodyFont);let d=c.lineHeight,f=0;const g=Oi(i.rtl,this.x,this.width),p=function(i){e.fillText(i,g.x(t.x+f),t.y+d/2),t.y+=d+n},m=g.textAlign(o);let x,b,_,y,v,M,w;for(e.textAlign=o,e.textBaseline="middle",e.font=c.string,t.x=Ra(this,m,i),e.fillStyle=i.bodyColor,u(this.beforeBody,p),f=a&&"right"!==m?"center"===o?l/2+h:l+2+h:0,y=0,M=s.length;y<M;++y){for(x=s[y],b=this.labelTextColors[y],e.fillStyle=b,u(x.before,p),_=x.lines,a&&_.length&&(this._drawColorBox(e,t,y,g,i),d=Math.max(c.lineHeight,r)),v=0,w=_.length;v<w;++v)p(_[v]),d=c.lineHeight;u(x.after,p)}f=0,d=c.lineHeight,u(this.afterBody,p),t.y-=n}drawFooter(t,e,i){const s=this.footer,n=s.length;let o,a;if(n){const r=Oi(i.rtl,this.x,this.width);for(t.x=Ra(this,i.footerAlign,i),t.y+=i.footerMarginTop,e.textAlign=r.textAlign(i.footerAlign),e.textBaseline="middle",o=Si(i.footerFont),e.fillStyle=i.footerColor,e.font=o.string,a=0;a<n;++a)e.fillText(s[a],r.x(t.x),t.y+o.lineHeight/2),t.y+=o.lineHeight+i.footerSpacing}}drawBackground(t,e,i,s){const{xAlign:n,yAlign:o}=this,{x:a,y:r}=t,{width:l,height:h}=i,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(s.cornerRadius);e.fillStyle=s.backgroundColor,e.strokeStyle=s.borderColor,e.lineWidth=s.borderWidth,e.beginPath(),e.moveTo(a+c,r),"top"===o&&this.drawCaret(t,e,i,s),e.lineTo(a+l-d,r),e.quadraticCurveTo(a+l,r,a+l,r+d),"center"===o&&"right"===n&&this.drawCaret(t,e,i,s),e.lineTo(a+l,r+h-f),e.quadraticCurveTo(a+l,r+h,a+l-f,r+h),"bottom"===o&&this.drawCaret(t,e,i,s),e.lineTo(a+u,r+h),e.quadraticCurveTo(a,r+h,a,r+h-u),"center"===o&&"left"===n&&this.drawCaret(t,e,i,s),e.lineTo(a,r+c),e.quadraticCurveTo(a,r,a+c,r),e.closePath(),e.fill(),s.borderWidth>0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Pa[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Aa(this,t),a=Object.assign({},i,this._size),r=La(e,t,a),l=Ea(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=ki(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ai(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),Ti(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!f(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!f(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if("mouseout"===t.type)return[];if(!s)return e.filter((t=>this.chart.data.datasets[t.datasetIndex]&&void 0!==this.chart.getDatasetMeta(t.datasetIndex).controller.getParsed(t.index)));const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=Pa[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Wa={id:"tooltip",_element:Ba,positioners:Pa,afterInit(t,e,i){i&&(t.tooltip=new Ba({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const i={tooltip:e};if(!1===t.notifyPlugins("beforeTooltipDraw",{...i,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i)}},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:Fa},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};return Tn.register(Un,$o,go,t),Tn.helpers={...Hi},Tn._adapters=In,Tn.Animation=As,Tn.Animations=Ts,Tn.animator=bt,Tn.controllers=nn.controllers.items,Tn.DatasetController=js,Tn.Element=$s,Tn.elements=go,Tn.Interaction=Ki,Tn.layouts=ls,Tn.platforms=Ds,Tn.Scale=tn,Tn.Ticks=ae,Object.assign(Tn,Un,$o,go,t,Ds),Tn.Chart=Tn,"undefined"!=typeof window&&(window.Chart=Tn),Tn}));
-//# sourceMappingURL=chart.umd.js.map
diff --git a/frontend/src/file-utils.js b/frontend/src/file-utils.js
deleted file mode 100644
index fcaa07f..0000000
--- a/frontend/src/file-utils.js
+++ /dev/null
@@ -1,126 +0,0 @@
-/**
- * Utility functions for secure file handling
- */
-
-/**
- * Converts a file path to a secure API endpoint path
- * @param {string} path - The file path to convert
- * @returns {string} The secure API endpoint path
- */
-function secureFilePath(path) {
- if (!path) return '';
-
- if (path.startsWith('uploads/')) {
- return '/api/secure-file/' + path.substring(8);
- }
-
- if (path.startsWith('/uploads/')) {
- return '/api/secure-file/' + path.substring(9);
- }
-
- return path;
-}
-
-/**
- * Opens a file in a new tab with proper authentication
- * @param {string} path - The file path to open
- */
-function openSecureFile(path) {
- if (!path) return;
-
- const securePath = secureFilePath(path);
- console.log('Opening file:', securePath);
-
- // Try to get the token from different sources
- const token = localStorage.getItem('auth_token');
-
- if (!token) {
- console.error('No authentication token available');
- alert('You must be logged in to access files');
- return;
- }
-
- // Create a link with target="_blank" and click it programmatically
- const link = document.createElement('a');
- link.href = securePath;
- link.target = '_blank';
-
- // Add a click event listener to inject the token
- link.addEventListener('click', function(e) {
- // Prevent the default navigation
- e.preventDefault();
-
- // Make a fetch request with the Authorization header
- fetch(securePath, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- })
- .then(response => {
- if (!response.ok) {
- throw new Error(`HTTP error! Status: ${response.status}`);
- }
- return response.blob();
- })
- .then(blob => {
- // Create a URL for the blob and open it in a new window
- const url = URL.createObjectURL(blob);
- window.open(url, '_blank');
- })
- .catch(error => {
- console.error('Error opening file:', error);
- alert('Error opening file. Please try again or check if you are logged in.');
- });
- });
-
- // Trigger the click event
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
-}
-
-/**
- * Downloads a file using the secure file endpoint
- * @param {string} path - The file path to download
- * @param {string} filename - The name to save the file as
- */
-function downloadSecureFile(path, filename) {
- if (!path) return;
-
- const securePath = secureFilePath(path);
- const token = localStorage.getItem('auth_token');
-
- if (!token) {
- console.error('No authentication token available');
- alert('You must be logged in to download files');
- return;
- }
-
- fetch(securePath, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- })
- .then(response => {
- if (!response.ok) {
- throw new Error(`HTTP error! Status: ${response.status}`);
- }
- return response.blob();
- })
- .then(blob => {
- const url = window.URL.createObjectURL(blob);
- const a = document.createElement('a');
- a.style.display = 'none';
- a.href = url;
- a.download = filename || path.split('/').pop();
- document.body.appendChild(a);
- a.click();
- window.URL.revokeObjectURL(url);
- })
- .catch(error => {
- console.error('Error downloading file:', error);
- alert('Error downloading file. Please try again or check if you are logged in.');
- });
-}
\ No newline at end of file
diff --git a/frontend/src/footer-content.js b/frontend/src/footer-content.js
deleted file mode 100644
index 362d6ef..0000000
--- a/frontend/src/footer-content.js
+++ /dev/null
@@ -1,131 +0,0 @@
-/**
- * Footer Content Manager - Universal
- * Manages the "Powered by" footer content across all pages
- * Easy to customize footer text, links, and branding from one place
- */
-
-(function() {
- 'use strict';
-
- // === FOOTER CONFIGURATION ===
- // Edit these values to change footer content across all pages
- const FOOTER_CONFIG = {
- // Main footer text
- text: 'Powered by',
-
- // Link configuration
- link: {
- text: 'Warracker',
- url: 'https://warracker.com',
- target: '_blank',
- rel: 'noopener noreferrer'
- },
-
- // Optional: Additional links or text
- // Uncomment and customize as needed
- /*
- additionalContent: [
- { type: 'text', content: ' | ' },
- { type: 'link', text: 'Privacy Policy', url: '/privacy.html' },
- { type: 'text', content: ' | ' },
- { type: 'link', text: 'Terms of Service', url: '/terms.html' }
- ]
- */
- };
-
- // === FOOTER CONTENT GENERATION ===
- function generateFooterContent() {
- let footerHTML = `${FOOTER_CONFIG.text} `;
-
- // Add main link
- footerHTML += `<a href="${FOOTER_CONFIG.link.url}" target="${FOOTER_CONFIG.link.target}" rel="${FOOTER_CONFIG.link.rel}" id="warrackerFooterLink">${FOOTER_CONFIG.link.text}</a>`;
-
- // Add additional content if configured
- if (FOOTER_CONFIG.additionalContent) {
- FOOTER_CONFIG.additionalContent.forEach(item => {
- if (item.type === 'text') {
- footerHTML += item.content;
- } else if (item.type === 'link') {
- const target = item.target || '_self';
- const rel = item.rel || '';
- footerHTML += `<a href="${item.url}" target="${target}" rel="${rel}">${item.text}</a>`;
- }
- });
- }
-
- return footerHTML;
- }
-
- // === FOOTER INITIALIZATION ===
- function initFooterContent() {
- const footer = document.getElementById('warrackerFooter');
-
- if (!footer) {
- console.warn('Footer element with ID "warrackerFooter" not found');
- return;
- }
-
- // Generate and inject footer content
- const footerContent = generateFooterContent();
- footer.innerHTML = `<p>${footerContent}</p>`;
-
- console.log('Footer content initialized successfully');
- }
-
- // === DYNAMIC FOOTER CREATION ===
- // If no footer exists, create one
- function createFooterIfMissing() {
- let footer = document.getElementById('warrackerFooter');
-
- if (!footer) {
- footer = document.createElement('footer');
- footer.className = 'warracker-footer';
- footer.id = 'warrackerFooter';
-
- // Insert before closing body tag
- document.body.appendChild(footer);
- console.log('Footer element created dynamically');
- }
-
- return footer;
- }
-
- // === PUBLIC API ===
- // Expose functions for manual updates if needed
- window.FooterContent = {
- // Update footer content dynamically
- update: function(newConfig) {
- Object.assign(FOOTER_CONFIG, newConfig);
- initFooterContent();
- },
-
- // Get current configuration
- getConfig: function() {
- return { ...FOOTER_CONFIG };
- },
-
- // Reinitialize footer
- reinit: function() {
- initFooterContent();
- }
- };
-
- // === AUTO-INITIALIZATION ===
- function init() {
- // Ensure footer element exists
- createFooterIfMissing();
-
- // Initialize footer content
- initFooterContent();
- }
-
- // Initialize when DOM is ready
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- // DOM is already loaded
- init();
- }
-
- console.log('Footer Content Manager loaded');
-})();
\ No newline at end of file
diff --git a/frontend/src/footer-fix.js b/frontend/src/footer-fix.js
deleted file mode 100644
index 0fcbaaa..0000000
--- a/frontend/src/footer-fix.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * Footer Width Fix - Universal
- * Ensures the Warracker footer spans full width across all pages
- * Handles both light and dark themes automatically
- */
-
-(function() {
- 'use strict';
-
- // Apply footer styles based on theme
- function applyFooterStyles() {
- const footer = document.getElementById('warrackerFooter');
- const link = document.getElementById('warrackerFooterLink');
-
- if (!footer) return; // Exit if footer doesn't exist on this page
-
- // Detect dark mode
- const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark' ||
- document.documentElement.classList.contains('dark-mode') ||
- document.body.classList.contains('dark-mode');
-
- if (isDarkMode) {
- // Dark mode styles without viewport-width hacks (prevents horizontal scrollbar)
- footer.style.cssText = `
- width: 100% !important;
- margin-top: 50px !important;
- margin-left: 0 !important;
- margin-right: 0 !important;
- padding: 20px !important;
- text-align: center !important;
- border-top: 1px solid #444 !important;
- background-color: #2d2d2d !important;
- color: #e0e0e0 !important;
- font-size: 0.9rem !important;
- position: relative !important;
- box-sizing: border-box !important;
- `;
- if (link) {
- link.style.cssText = 'color: #4dabf7 !important; text-decoration: none !important; font-weight: 500 !important;';
- }
- } else {
- // Light mode styles without viewport-width hacks (prevents horizontal scrollbar)
- footer.style.cssText = `
- width: 100% !important;
- margin-top: 50px !important;
- margin-left: 0 !important;
- margin-right: 0 !important;
- padding: 20px !important;
- text-align: center !important;
- border-top: 1px solid #e0e0e0 !important;
- background-color: #ffffff !important;
- color: #333333 !important;
- font-size: 0.9rem !important;
- position: relative !important;
- box-sizing: border-box !important;
- `;
- if (link) {
- link.style.cssText = 'color: #3498db !important; text-decoration: none !important; font-weight: 500 !important;';
- }
- }
- }
-
- // Initialize footer styles when DOM is ready
- function initFooterFix() {
- applyFooterStyles();
-
- // Watch for theme changes on document.documentElement
- const observer = new MutationObserver(applyFooterStyles);
- observer.observe(document.documentElement, {
- attributes: true,
- attributeFilter: ['data-theme', 'class']
- });
-
- // Also watch body for theme changes (fallback)
- observer.observe(document.body, {
- attributes: true,
- attributeFilter: ['class']
- });
-
- // Listen for custom theme change events if they exist
- document.addEventListener('themeChanged', applyFooterStyles);
- window.addEventListener('themeChanged', applyFooterStyles);
- }
-
- // Auto-initialize when DOM is loaded
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', initFooterFix);
- } else {
- // DOM is already loaded
- initFooterFix();
- }
-
- // Expose function globally in case manual calls are needed
- window.applyFooterFix = applyFooterStyles;
-
- console.log('Footer Fix loaded - Footer will span full width on all pages');
-})();
\ No newline at end of file
diff --git a/frontend/src/js/i18n-debug.js b/frontend/src/js/i18n-debug.js
deleted file mode 100644
index d3684af..0000000
--- a/frontend/src/js/i18n-debug.js
+++ /dev/null
@@ -1,36 +0,0 @@
-// Debug script to test i18next CDN loading
-console.log('=== i18next Debug Script ===');
-
-// Check if CDN scripts are loaded
-setTimeout(() => {
- console.log('Checking i18next libraries:');
- console.log('- i18next:', typeof i18next !== 'undefined' ? 'LOADED' : 'NOT LOADED');
- console.log('- i18nextHttpBackend:', typeof i18nextHttpBackend !== 'undefined' ? 'LOADED' : 'NOT LOADED');
- console.log('- i18nextBrowserLanguageDetector:', typeof i18nextBrowserLanguageDetector !== 'undefined' ? 'LOADED' : 'NOT LOADED');
-
- // Test basic fetch to translation file
- fetch('/locales/en/translation.json')
- .then(response => {
- console.log('Translation file fetch status:', response.status);
- return response.json();
- })
- .then(data => {
- console.log('Translation file loaded successfully, keys:', Object.keys(data).slice(0, 5));
- })
- .catch(error => {
- console.error('Failed to load translation file:', error);
- });
-
- // Test API endpoint
- fetch('/api/locales')
- .then(response => {
- console.log('Locales API status:', response.status);
- return response.json();
- })
- .then(data => {
- console.log('Locales API response:', data);
- })
- .catch(error => {
- console.error('Failed to load locales API:', error);
- });
-}, 2000); // Wait 2 seconds for CDN scripts to load
\ No newline at end of file
diff --git a/frontend/src/js/i18n.js b/frontend/src/js/i18n.js
deleted file mode 100644
index f178ea3..0000000
--- a/frontend/src/js/i18n.js
+++ /dev/null
@@ -1,469 +0,0 @@
-/**
- * i18next Configuration and Initialization
- * Handles frontend localization with offline support
- */
-
-// Global i18n object to make translation functions available
-window.i18n = {};
-
-// Supported languages
-const SUPPORTED_LANGUAGES = ['en', 'fr', 'es', 'de', 'it', 'cs', 'nl', 'hi', 'fa', 'ar', 'ru', 'uk', 'zh_CN', 'zh_HK', 'ja', 'pt', 'ko', 'tr', 'pl', 'he'];
-const DEFAULT_LANGUAGE = 'en';
-const RTL_LANGUAGES = ['ar', 'fa', 'he']; // Arabic, Persian, and Hebrew are RTL languages
-
-/**
- * Initialize i18next with configuration
- */
-async function initializeI18n() {
- console.log('Initializing i18next...');
-
- // Debug: Check if required libraries are loaded
- if (typeof i18next === 'undefined') {
- console.error('i18next library not loaded');
- return;
- }
-
- console.log('i18next library loaded successfully');
-
- // Check optional libraries
- const hasHttpBackend = typeof i18nextHttpBackend !== 'undefined';
- const hasLanguageDetector = typeof i18nextBrowserLanguageDetector !== 'undefined';
-
- console.log('Optional libraries:', {
- httpBackend: hasHttpBackend,
- languageDetector: hasLanguageDetector
- });
-
- try {
- // Get current language from various sources
- const savedLanguage = getCurrentLanguage();
- console.log('Initial language detected:', savedLanguage);
-
- // Load translations manually since HttpBackend might not be available
- const translations = await loadTranslations(savedLanguage);
-
- // Configure i18next with or without plugins
- let i18nextInstance = i18next;
-
- if (hasLanguageDetector) {
- i18nextInstance = i18nextInstance.use(i18nextBrowserLanguageDetector);
- }
-
- await i18nextInstance.init({
- fallbackLng: DEFAULT_LANGUAGE,
- supportedLngs: SUPPORTED_LANGUAGES,
- debug: false,
-
- // Set initial language and resources
- lng: savedLanguage,
- resources: translations,
-
- // Language detection configuration (only if detector is available)
- ...(hasLanguageDetector && {
- detection: {
- order: ['cookie', 'localStorage', 'navigator', 'htmlTag'],
- lookupCookie: 'lang',
- lookupLocalStorage: 'preferred_language',
- caches: ['cookie', 'localStorage'],
- cookieOptions: {
- path: '/',
- maxAge: 365 * 24 * 60 * 60 // 1 year
- }
- }
- }),
-
- // Interpolation options
- interpolation: {
- escapeValue: false
- }
- });
-
- // Store translation function globally
- window.i18n.t = i18next.t.bind(i18next);
- window.i18n.changeLanguage = changeLanguage;
- window.i18n.getCurrentLanguage = getCurrentLanguage;
- window.i18n.getSupportedLanguages = () => SUPPORTED_LANGUAGES;
-
- // Initialize page translations
- translatePage();
-
- // Set initial page direction
- updatePageDirection(i18next.language);
-
- // Set up language change listener
- i18next.on('languageChanged', (lng) => {
- console.log('Language changed to:', lng);
- translatePage();
- updateLanguageAttribute(lng);
- updatePageDirection(lng);
- });
-
- console.log('i18next initialized successfully with language:', i18next.language);
-
- // Dispatch event to notify other scripts that i18n is ready
- window.dispatchEvent(new CustomEvent('i18nReady', {
- detail: {
- language: i18next.language,
- t: window.i18n.t
- }
- }));
-
- } catch (error) {
- console.error('Failed to initialize i18next:', error);
- // Fallback to default language without i18next
- window.i18n.t = (key) => key; // Return key as fallback
- window.i18n.changeLanguage = () => {};
- window.i18n.getCurrentLanguage = () => DEFAULT_LANGUAGE;
- window.i18n.getSupportedLanguages = () => SUPPORTED_LANGUAGES;
-
- // Still dispatch event so other scripts know i18n is "ready" (even with fallback)
- window.dispatchEvent(new CustomEvent('i18nReady', {
- detail: {
- language: DEFAULT_LANGUAGE,
- t: window.i18n.t,
- fallback: true
- }
- }));
- }
-}
-
-/**
- * Load translations for a specific language
- */
-async function loadTranslations(language) {
- console.log(`loadTranslations called for language: ${language}`);
- const translations = {};
-
- try {
- // Load primary language
- const url = `/locales/${language}/translation.json?v=${Date.now()}`;
- console.log(`Fetching translations from: ${url}`);
- const response = await fetch(url);
- console.log(`Fetch response status: ${response.status} for language: ${language}`);
-
- if (response.ok) {
- const data = await response.json();
- translations[language] = { translation: data };
- const keyCount = Object.keys(data).length;
- console.log(`Successfully loaded ${keyCount} translation keys for ${language}:`, Object.keys(data).slice(0, 5));
- } else {
- console.warn(`Failed to load translations for ${language}, status: ${response.status}`);
- console.warn(`Response text:`, await response.text().catch(() => 'Could not read response text'));
- }
- } catch (error) {
- console.error(`Error loading translations for ${language}:`, error);
- }
-
- // Always load fallback language if different
- if (language !== DEFAULT_LANGUAGE) {
- try {
- const fallbackUrl = `/locales/${DEFAULT_LANGUAGE}/translation.json?v=${Date.now()}`;
- console.log(`Loading fallback language from: ${fallbackUrl}`);
- const fallbackResponse = await fetch(fallbackUrl);
- console.log(`Fallback fetch response status: ${fallbackResponse.status}`);
-
- if (fallbackResponse.ok) {
- const fallbackData = await fallbackResponse.json();
- translations[DEFAULT_LANGUAGE] = { translation: fallbackData };
- const fallbackKeyCount = Object.keys(fallbackData).length;
- console.log(`Loaded ${fallbackKeyCount} fallback translation keys for ${DEFAULT_LANGUAGE}`);
- }
- } catch (error) {
- console.error(`Error loading fallback translations:`, error);
- }
- }
-
- console.log(`loadTranslations completed. Languages loaded: ${Object.keys(translations)}`);
- return translations;
-}
-
-/**
- * Get current language from storage or user preferences
- */
-function getCurrentLanguage() {
- // URL override (e.g., ?lang=tr)
- try {
- const params = new URLSearchParams(window.location.search);
- const urlLang = params.get('lang');
- if (urlLang && SUPPORTED_LANGUAGES.includes(urlLang)) {
- setCookie('lang', urlLang, 365);
- localStorage.setItem('preferred_language', urlLang);
- return urlLang;
- }
- } catch (e) {
- // Ignore URL parsing errors and continue
- }
- // Check cookie first
- const cookieLang = getCookie('lang');
- if (cookieLang && SUPPORTED_LANGUAGES.includes(cookieLang)) {
- return cookieLang;
- }
-
- // Check localStorage
- const storedLang = localStorage.getItem('preferred_language');
- if (storedLang && SUPPORTED_LANGUAGES.includes(storedLang)) {
- return storedLang;
- }
-
- // Check user preferences from API if authenticated
- const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
- if (userInfo.preferred_language && SUPPORTED_LANGUAGES.includes(userInfo.preferred_language)) {
- return userInfo.preferred_language;
- }
-
- // Fallback to browser language or default
- const browserLang = navigator.language?.split('-')[0];
- return SUPPORTED_LANGUAGES.includes(browserLang) ? browserLang : DEFAULT_LANGUAGE;
-}
-
-/**
- * Change language and persist preference
- */
-async function changeLanguage(language) {
- console.log('changeLanguage called with:', language);
-
- if (!SUPPORTED_LANGUAGES.includes(language)) {
- console.warn('Unsupported language:', language);
- return;
- }
-
- try {
- console.log('Loading translations for language:', language);
- // Load translations for the new language
- const translations = await loadTranslations(language);
- console.log('Translations loaded:', Object.keys(translations));
-
- // Add new language resources to i18next
- for (const [lng, resources] of Object.entries(translations)) {
- console.log('Adding resource bundle for language:', lng);
- i18next.addResourceBundle(lng, 'translation', resources.translation, true, true);
- }
-
- // Change language in i18next
- console.log('Changing i18next language to:', language);
- await i18next.changeLanguage(language);
- console.log('i18next language changed successfully to:', i18next.language);
-
- // Persist to cookie and localStorage
- setCookie('lang', language, 365);
- localStorage.setItem('preferred_language', language);
- console.log('Language preference saved to cookie and localStorage:', language);
-
- // Update user preference in backend if authenticated
- if (localStorage.getItem('auth_token')) {
- try {
- await saveLanguagePreference(language);
- console.log('Language preference saved to backend');
- } catch (error) {
- console.warn('Failed to save language preference to backend:', error);
- }
- }
-
- // Dispatch event for other components
- window.dispatchEvent(new CustomEvent('languageChanged', { detail: { language } }));
- console.log('languageChanged event dispatched for:', language);
-
- } catch (error) {
- console.error('Failed to change language:', error);
- throw error; // Re-throw to let calling code handle it
- }
-}
-
-/**
- * Save language preference to backend
- */
-async function saveLanguagePreference(language) {
- const token = localStorage.getItem('auth_token');
- if (!token) return;
-
- const response = await fetch('/api/auth/user/language-preference', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({ preferred_language: language })
- });
-
- if (!response.ok) {
- throw new Error('Failed to save language preference');
- }
-}
-
-/**
- * Translate all elements on the current page
- */
-function translatePage() {
- if (!window.i18n.t) {
- console.warn('Translation function not available, skipping translation');
- return;
- }
-
- console.log('Starting page translation...');
- let translatedCount = 0;
-
- // Update dynamic titles that are set by JavaScript
- updateDynamicTitles();
-
- // Translate elements with data-i18n attribute
- document.querySelectorAll('[data-i18n]').forEach(element => {
- const raw = element.getAttribute('data-i18n');
- let handled = false;
-
- // Support syntax like [placeholder]warranties.search_placeholder
- const attrMatch = raw && raw.match(/^\s*\[(\w+)\]\s*(.+)$/);
- if (attrMatch) {
- const attrName = attrMatch[1];
- const key = attrMatch[2];
- const translation = window.i18n.t(key);
- if (translation && translation !== key) {
- element.setAttribute(attrName, translation);
- translatedCount++;
- handled = true;
- }
- }
-
- if (!handled) {
- const key = raw;
- const translation = window.i18n.t(key);
- if (translation && translation !== key) {
- if (element.tagName === 'INPUT' && (element.type === 'text' || element.type === 'email' || element.type === 'password')) {
- element.placeholder = translation;
- } else if (element.hasAttribute('title')) {
- element.title = translation;
- } else {
- element.textContent = translation;
- }
- translatedCount++;
- } else {
- console.warn(`No translation found for key: ${key}`);
- }
- }
- });
-
- // Translate elements with data-i18n-html attribute (allows HTML content)
- document.querySelectorAll('[data-i18n-html]').forEach(element => {
- const key = element.getAttribute('data-i18n-html');
- const translation = window.i18n.t(key);
- element.innerHTML = translation;
- });
-
- // Translate elements with data-i18n-title attribute
- document.querySelectorAll('[data-i18n-title]').forEach(element => {
- const key = element.getAttribute('data-i18n-title');
- const translation = window.i18n.t(key);
- element.title = translation;
- });
-
- // Translate elements with data-i18n-placeholder attribute
- document.querySelectorAll('[data-i18n-placeholder]').forEach(element => {
- const key = element.getAttribute('data-i18n-placeholder');
- const translation = window.i18n.t(key);
- if (translation && translation !== key) {
- element.placeholder = translation;
- translatedCount++;
- }
- });
-
- console.log(`Page translation completed. Translated ${translatedCount} elements.`);
-
- // Re-process warranties to update status text and labels if warranties exist
- if (typeof warranties !== 'undefined' && warranties && warranties.length > 0) {
- console.log(`[i18n.js] Re-processing ${warranties.length} warranties after language change`);
- // Re-process each warranty to update status text with new language
- warranties = warranties.map(warranty => {
- if (typeof processWarrantyData === 'function') {
- return processWarrantyData(warranty);
- }
- return warranty;
- });
- // Re-render warranties with new translations
- if (typeof applyFilters === 'function') {
- applyFilters();
- }
- }
-}
-
-/**
- * Update dynamic titles that are set by JavaScript
- */
-function updateDynamicTitles() {
- // Update warranties panel title on index.html
- if (typeof updateWarrantiesPanelTitle === 'function' && typeof isGlobalView !== 'undefined') {
- updateWarrantiesPanelTitle(isGlobalView);
- }
-
- // Update dashboard title on status.html
- if (typeof updateDashboardTitle === 'function') {
- updateDashboardTitle();
- }
-
- // Re-process warranty cards if they exist (for dynamic status text)
- if (typeof processAllWarranties === 'function') {
- processAllWarranties();
- }
-}
-
-/**
- * Update HTML lang attribute
- */
-function updateLanguageAttribute(language) {
- document.documentElement.lang = language;
-}
-
-/**
- * Update page direction for RTL languages
- */
-function updatePageDirection(language) {
- const isRTL = RTL_LANGUAGES.includes(language);
- const htmlElement = document.documentElement;
- const bodyElement = document.body;
-
- if (isRTL) {
- htmlElement.dir = 'rtl';
- htmlElement.setAttribute('data-rtl', 'true');
- bodyElement.classList.add('rtl');
- console.log(`Applied RTL direction for language: ${language}`);
- } else {
- htmlElement.dir = 'ltr';
- htmlElement.removeAttribute('data-rtl');
- bodyElement.classList.remove('rtl');
- console.log(`Applied LTR direction for language: ${language}`);
- }
-}
-
-/**
- * Utility function to get cookie value
- */
-function getCookie(name) {
- const value = `; ${document.cookie}`;
- const parts = value.split(`; ${name}=`);
- if (parts.length === 2) return parts.pop().split(';').shift();
- return null;
-}
-
-/**
- * Utility function to set cookie
- */
-function setCookie(name, value, days) {
- const expires = new Date();
- expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
- document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`;
-}
-
-/**
- * Add translation helper for dynamic content
- */
-function t(key, options = {}) {
- return window.i18n.t ? window.i18n.t(key, options) : key;
-}
-
-// Expose translation function globally
-window.t = t;
-
-// Initialize when DOM is ready
-if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', initializeI18n);
-} else {
- initializeI18n();
-}
diff --git a/frontend/src/js/lib/i18next.min.js b/frontend/src/js/lib/i18next.min.js
deleted file mode 100644
index 1978709..0000000
--- a/frontend/src/js/lib/i18next.min.js
+++ /dev/null
@@ -1 +0,0 @@
-!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).i18next=e()}(this,(function(){"use strict";const t={type:"logger",log(t){this.output("log",t)},warn(t){this.output("warn",t)},error(t){this.output("error",t)},output(t,e){console&&console[t]&&console[t].apply(console,e)}};class e{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.init(t,e)}init(e){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.prefix=s.prefix||"i18next:",this.logger=e||t,this.options=s,this.debug=s.debug}log(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.forward(e,"log","",!0)}warn(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.forward(e,"warn","",!0)}error(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.forward(e,"error","")}deprecate(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(t,e,s,i){return i&&!this.debug?null:("string"==typeof t[0]&&(t[0]=`${s}${this.prefix} ${t[0]}`),this.logger[e](t))}create(t){return new e(this.logger,{prefix:`${this.prefix}:${t}:`,...this.options})}clone(t){return(t=t||this.options).prefix=t.prefix||this.prefix,new e(this.logger,t)}}var s=new e;class i{constructor(){this.observers={}}on(t,e){return t.split(" ").forEach((t=>{this.observers[t]=this.observers[t]||[],this.observers[t].push(e)})),this}off(t,e){this.observers[t]&&(e?this.observers[t]=this.observers[t].filter((t=>t!==e)):delete this.observers[t])}emit(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];if(this.observers[t]){[].concat(this.observers[t]).forEach((t=>{t(...s)}))}if(this.observers["*"]){[].concat(this.observers["*"]).forEach((e=>{e.apply(e,[t,...s])}))}}}function n(){let t,e;const s=new Promise(((s,i)=>{t=s,e=i}));return s.resolve=t,s.reject=e,s}function o(t){return null==t?"":""+t}function r(t,e,s){function i(t){return t&&t.indexOf("###")>-1?t.replace(/###/g,"."):t}function n(){return!t||"string"==typeof t}const o="string"!=typeof e?[].concat(e):e.split(".");for(;o.length>1;){if(n())return{};const e=i(o.shift());!t[e]&&s&&(t[e]=new s),t=Object.prototype.hasOwnProperty.call(t,e)?t[e]:{}}return n()?{}:{obj:t,k:i(o.shift())}}function a(t,e,s){const{obj:i,k:n}=r(t,e,Object);i[n]=s}function l(t,e){const{obj:s,k:i}=r(t,e);if(s)return s[i]}function u(t,e,s){for(const i in e)"__proto__"!==i&&"constructor"!==i&&(i in t?"string"==typeof t[i]||t[i]instanceof String||"string"==typeof e[i]||e[i]instanceof String?s&&(t[i]=e[i]):u(t[i],e[i],s):t[i]=e[i]);return t}function h(t){return t.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var c={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};function p(t){return"string"==typeof t?t.replace(/[&<>"'\/]/g,(t=>c[t])):t}const g=[" ",",","?","!",";"];function d(t,e){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:".";if(!t)return;if(t[e])return t[e];const i=e.split(s);let n=t;for(let t=0;t<i.length;++t){if(!n)return;if("string"==typeof n[i[t]]&&t+1<i.length)return;if(void 0===n[i[t]]){let o=2,r=i.slice(t,t+o).join(s),a=n[r];for(;void 0===a&&i.length>t+o;)o++,r=i.slice(t,t+o).join(s),a=n[r];if(void 0===a)return;if(null===a)return null;if(e.endsWith(r)){if("string"==typeof a)return a;if(r&&"string"==typeof a[r])return a[r]}const l=i.slice(t+o).join(s);return l?d(a,l,s):void 0}n=n[i[t]]}return n}function f(t){return t&&t.indexOf("_")>0?t.replace("_","-"):t}class m extends i{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{ns:["translation"],defaultNS:"translation"};super(),this.data=t||{},this.options=e,void 0===this.options.keySeparator&&(this.options.keySeparator="."),void 0===this.options.ignoreJSONStructure&&(this.options.ignoreJSONStructure=!0)}addNamespaces(t){this.options.ns.indexOf(t)<0&&this.options.ns.push(t)}removeNamespaces(t){const e=this.options.ns.indexOf(t);e>-1&&this.options.ns.splice(e,1)}getResource(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};const n=void 0!==i.keySeparator?i.keySeparator:this.options.keySeparator,o=void 0!==i.ignoreJSONStructure?i.ignoreJSONStructure:this.options.ignoreJSONStructure;let r=[t,e];s&&"string"!=typeof s&&(r=r.concat(s)),s&&"string"==typeof s&&(r=r.concat(n?s.split(n):s)),t.indexOf(".")>-1&&(r=t.split("."));const a=l(this.data,r);return a||!o||"string"!=typeof s?a:d(this.data&&this.data[t]&&this.data[t][e],s,n)}addResource(t,e,s,i){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{silent:!1};const o=void 0!==n.keySeparator?n.keySeparator:this.options.keySeparator;let r=[t,e];s&&(r=r.concat(o?s.split(o):s)),t.indexOf(".")>-1&&(r=t.split("."),i=e,e=r[1]),this.addNamespaces(e),a(this.data,r,i),n.silent||this.emit("added",t,e,s,i)}addResources(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{silent:!1};for(const i in s)"string"!=typeof s[i]&&"[object Array]"!==Object.prototype.toString.apply(s[i])||this.addResource(t,e,i,s[i],{silent:!0});i.silent||this.emit("added",t,e,s)}addResourceBundle(t,e,s,i,n){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{silent:!1},r=[t,e];t.indexOf(".")>-1&&(r=t.split("."),i=s,s=e,e=r[1]),this.addNamespaces(e);let h=l(this.data,r)||{};i?u(h,s,n):h={...h,...s},a(this.data,r,h),o.silent||this.emit("added",t,e,s)}removeResourceBundle(t,e){this.hasResourceBundle(t,e)&&delete this.data[t][e],this.removeNamespaces(e),this.emit("removed",t,e)}hasResourceBundle(t,e){return void 0!==this.getResource(t,e)}getResourceBundle(t,e){return e||(e=this.options.defaultNS),"v1"===this.options.compatibilityAPI?{...this.getResource(t,e)}:this.getResource(t,e)}getDataByLanguage(t){return this.data[t]}hasLanguageSomeTranslations(t){const e=this.getDataByLanguage(t);return!!(e&&Object.keys(e)||[]).find((t=>e[t]&&Object.keys(e[t]).length>0))}toJSON(){return this.data}}var y={processors:{},addPostProcessor(t){this.processors[t.name]=t},handle(t,e,s,i,n){return t.forEach((t=>{this.processors[t]&&(e=this.processors[t].process(e,s,i,n))})),e}};const v={};class b extends i{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};var i,n;super(),i=t,n=this,["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"].forEach((t=>{i[t]&&(n[t]=i[t])})),this.options=e,void 0===this.options.keySeparator&&(this.options.keySeparator="."),this.logger=s.create("translator")}changeLanguage(t){t&&(this.language=t)}exists(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}};if(null==t)return!1;const s=this.resolve(t,e);return s&&void 0!==s.res}extractFromKey(t,e){let s=void 0!==e.nsSeparator?e.nsSeparator:this.options.nsSeparator;void 0===s&&(s=":");const i=void 0!==e.keySeparator?e.keySeparator:this.options.keySeparator;let n=e.ns||this.options.defaultNS||[];const o=s&&t.indexOf(s)>-1,r=!(this.options.userDefinedKeySeparator||e.keySeparator||this.options.userDefinedNsSeparator||e.nsSeparator||function(t,e,s){e=e||"",s=s||"";const i=g.filter((t=>e.indexOf(t)<0&&s.indexOf(t)<0));if(0===i.length)return!0;const n=new RegExp(`(${i.map((t=>"?"===t?"\\?":t)).join("|")})`);let o=!n.test(t);if(!o){const e=t.indexOf(s);e>0&&!n.test(t.substring(0,e))&&(o=!0)}return o}(t,s,i));if(o&&!r){const e=t.match(this.interpolator.nestingRegexp);if(e&&e.length>0)return{key:t,namespaces:n};const o=t.split(s);(s!==i||s===i&&this.options.ns.indexOf(o[0])>-1)&&(n=o.shift()),t=o.join(i)}return"string"==typeof n&&(n=[n]),{key:t,namespaces:n}}translate(t,e,s){if("object"!=typeof e&&this.options.overloadTranslationOptionHandler&&(e=this.options.overloadTranslationOptionHandler(arguments)),"object"==typeof e&&(e={...e}),e||(e={}),null==t)return"";Array.isArray(t)||(t=[String(t)]);const i=void 0!==e.returnDetails?e.returnDetails:this.options.returnDetails,n=void 0!==e.keySeparator?e.keySeparator:this.options.keySeparator,{key:o,namespaces:r}=this.extractFromKey(t[t.length-1],e),a=r[r.length-1],l=e.lng||this.language,u=e.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l&&"cimode"===l.toLowerCase()){if(u){const t=e.nsSeparator||this.options.nsSeparator;return i?{res:`${a}${t}${o}`,usedKey:o,exactUsedKey:o,usedLng:l,usedNS:a,usedParams:this.getUsedParamsDetails(e)}:`${a}${t}${o}`}return i?{res:o,usedKey:o,exactUsedKey:o,usedLng:l,usedNS:a,usedParams:this.getUsedParamsDetails(e)}:o}const h=this.resolve(t,e);let c=h&&h.res;const p=h&&h.usedKey||o,g=h&&h.exactUsedKey||o,d=Object.prototype.toString.apply(c),f=void 0!==e.joinArrays?e.joinArrays:this.options.joinArrays,m=!this.i18nFormat||this.i18nFormat.handleAsObject;if(m&&c&&("string"!=typeof c&&"boolean"!=typeof c&&"number"!=typeof c)&&["[object Number]","[object Function]","[object RegExp]"].indexOf(d)<0&&("string"!=typeof f||"[object Array]"!==d)){if(!e.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const t=this.options.returnedObjectHandler?this.options.returnedObjectHandler(p,c,{...e,ns:r}):`key '${o} (${this.language})' returned an object instead of string.`;return i?(h.res=t,h.usedParams=this.getUsedParamsDetails(e),h):t}if(n){const t="[object Array]"===d,s=t?[]:{},i=t?g:p;for(const t in c)if(Object.prototype.hasOwnProperty.call(c,t)){const o=`${i}${n}${t}`;s[t]=this.translate(o,{...e,joinArrays:!1,ns:r}),s[t]===o&&(s[t]=c[t])}c=s}}else if(m&&"string"==typeof f&&"[object Array]"===d)c=c.join(f),c&&(c=this.extendTranslation(c,t,e,s));else{let i=!1,r=!1;const u=void 0!==e.count&&"string"!=typeof e.count,p=b.hasDefaultValue(e),g=u?this.pluralResolver.getSuffix(l,e.count,e):"",d=e.ordinal&&u?this.pluralResolver.getSuffix(l,e.count,{ordinal:!1}):"",f=e[`defaultValue${g}`]||e[`defaultValue${d}`]||e.defaultValue;!this.isValidLookup(c)&&p&&(i=!0,c=f),this.isValidLookup(c)||(r=!0,c=o);const m=(e.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&r?void 0:c,y=p&&f!==c&&this.options.updateMissing;if(r||i||y){if(this.logger.log(y?"updateKey":"missingKey",l,a,o,y?f:c),n){const t=this.resolve(o,{...e,keySeparator:!1});t&&t.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let t=[];const s=this.languageUtils.getFallbackCodes(this.options.fallbackLng,e.lng||this.language);if("fallback"===this.options.saveMissingTo&&s&&s[0])for(let e=0;e<s.length;e++)t.push(s[e]);else"all"===this.options.saveMissingTo?t=this.languageUtils.toResolveHierarchy(e.lng||this.language):t.push(e.lng||this.language);const i=(t,s,i)=>{const n=p&&i!==c?i:m;this.options.missingKeyHandler?this.options.missingKeyHandler(t,a,s,n,y,e):this.backendConnector&&this.backendConnector.saveMissing&&this.backendConnector.saveMissing(t,a,s,n,y,e),this.emit("missingKey",t,a,s,c)};this.options.saveMissing&&(this.options.saveMissingPlurals&&u?t.forEach((t=>{this.pluralResolver.getSuffixes(t,e).forEach((s=>{i([t],o+s,e[`defaultValue${s}`]||f)}))})):i(t,o,f))}c=this.extendTranslation(c,t,e,h,s),r&&c===o&&this.options.appendNamespaceToMissingKey&&(c=`${a}:${o}`),(r||i)&&this.options.parseMissingKeyHandler&&(c="v1"!==this.options.compatibilityAPI?this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${a}:${o}`:o,i?c:void 0):this.options.parseMissingKeyHandler(c))}return i?(h.res=c,h.usedParams=this.getUsedParamsDetails(e),h):c}extendTranslation(t,e,s,i,n){var o=this;if(this.i18nFormat&&this.i18nFormat.parse)t=this.i18nFormat.parse(t,{...this.options.interpolation.defaultVariables,...s},s.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!s.skipInterpolation){s.interpolation&&this.interpolator.init({...s,interpolation:{...this.options.interpolation,...s.interpolation}});const r="string"==typeof t&&(s&&s.interpolation&&void 0!==s.interpolation.skipOnVariables?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let a;if(r){const e=t.match(this.interpolator.nestingRegexp);a=e&&e.length}let l=s.replace&&"string"!=typeof s.replace?s.replace:s;if(this.options.interpolation.defaultVariables&&(l={...this.options.interpolation.defaultVariables,...l}),t=this.interpolator.interpolate(t,l,s.lng||this.language,s),r){const e=t.match(this.interpolator.nestingRegexp);a<(e&&e.length)&&(s.nest=!1)}!s.lng&&"v1"!==this.options.compatibilityAPI&&i&&i.res&&(s.lng=i.usedLng),!1!==s.nest&&(t=this.interpolator.nest(t,(function(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];return n&&n[0]===i[0]&&!s.context?(o.logger.warn(`It seems you are nesting recursively key: ${i[0]} in key: ${e[0]}`),null):o.translate(...i,e)}),s)),s.interpolation&&this.interpolator.reset()}const r=s.postProcess||this.options.postProcess,a="string"==typeof r?[r]:r;return null!=t&&a&&a.length&&!1!==s.applyPostProcessor&&(t=y.handle(a,t,e,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(s)},...s}:s,this)),t}resolve(t){let e,s,i,n,o,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"string"==typeof t&&(t=[t]),t.forEach((t=>{if(this.isValidLookup(e))return;const a=this.extractFromKey(t,r),l=a.key;s=l;let u=a.namespaces;this.options.fallbackNS&&(u=u.concat(this.options.fallbackNS));const h=void 0!==r.count&&"string"!=typeof r.count,c=h&&!r.ordinal&&0===r.count&&this.pluralResolver.shouldUseIntlApi(),p=void 0!==r.context&&("string"==typeof r.context||"number"==typeof r.context)&&""!==r.context,g=r.lngs?r.lngs:this.languageUtils.toResolveHierarchy(r.lng||this.language,r.fallbackLng);u.forEach((t=>{this.isValidLookup(e)||(o=t,!v[`${g[0]}-${t}`]&&this.utils&&this.utils.hasLoadedNamespace&&!this.utils.hasLoadedNamespace(o)&&(v[`${g[0]}-${t}`]=!0,this.logger.warn(`key "${s}" for languages "${g.join(", ")}" won't get resolved as namespace "${o}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach((s=>{if(this.isValidLookup(e))return;n=s;const o=[l];if(this.i18nFormat&&this.i18nFormat.addLookupKeys)this.i18nFormat.addLookupKeys(o,l,s,t,r);else{let t;h&&(t=this.pluralResolver.getSuffix(s,r.count,r));const e=`${this.options.pluralSeparator}zero`,i=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(h&&(o.push(l+t),r.ordinal&&0===t.indexOf(i)&&o.push(l+t.replace(i,this.options.pluralSeparator)),c&&o.push(l+e)),p){const s=`${l}${this.options.contextSeparator}${r.context}`;o.push(s),h&&(o.push(s+t),r.ordinal&&0===t.indexOf(i)&&o.push(s+t.replace(i,this.options.pluralSeparator)),c&&o.push(s+e))}}let a;for(;a=o.pop();)this.isValidLookup(e)||(i=a,e=this.getResource(s,t,a,r))})))}))})),{res:e,usedKey:s,exactUsedKey:i,usedLng:n,usedNS:o}}isValidLookup(t){return!(void 0===t||!this.options.returnNull&&null===t||!this.options.returnEmptyString&&""===t)}getResource(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(t,e,s,i):this.resourceStore.getResource(t,e,s,i)}getUsedParamsDetails(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const e=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],s=t.replace&&"string"!=typeof t.replace;let i=s?t.replace:t;if(s&&void 0!==t.count&&(i.count=t.count),this.options.interpolation.defaultVariables&&(i={...this.options.interpolation.defaultVariables,...i}),!s){i={...i};for(const t of e)delete i[t]}return i}static hasDefaultValue(t){const e="defaultValue";for(const s in t)if(Object.prototype.hasOwnProperty.call(t,s)&&e===s.substring(0,12)&&void 0!==t[s])return!0;return!1}}function x(t){return t.charAt(0).toUpperCase()+t.slice(1)}class S{constructor(t){this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=s.create("languageUtils")}getScriptPartFromCode(t){if(!(t=f(t))||t.indexOf("-")<0)return null;const e=t.split("-");return 2===e.length?null:(e.pop(),"x"===e[e.length-1].toLowerCase()?null:this.formatLanguageCode(e.join("-")))}getLanguagePartFromCode(t){if(!(t=f(t))||t.indexOf("-")<0)return t;const e=t.split("-");return this.formatLanguageCode(e[0])}formatLanguageCode(t){if("string"==typeof t&&t.indexOf("-")>-1){const e=["hans","hant","latn","cyrl","cans","mong","arab"];let s=t.split("-");return this.options.lowerCaseLng?s=s.map((t=>t.toLowerCase())):2===s.length?(s[0]=s[0].toLowerCase(),s[1]=s[1].toUpperCase(),e.indexOf(s[1].toLowerCase())>-1&&(s[1]=x(s[1].toLowerCase()))):3===s.length&&(s[0]=s[0].toLowerCase(),2===s[1].length&&(s[1]=s[1].toUpperCase()),"sgn"!==s[0]&&2===s[2].length&&(s[2]=s[2].toUpperCase()),e.indexOf(s[1].toLowerCase())>-1&&(s[1]=x(s[1].toLowerCase())),e.indexOf(s[2].toLowerCase())>-1&&(s[2]=x(s[2].toLowerCase()))),s.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?t.toLowerCase():t}isSupportedCode(t){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(t=this.getLanguagePartFromCode(t)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(t)>-1}getBestMatchFromCodes(t){if(!t)return null;let e;return t.forEach((t=>{if(e)return;const s=this.formatLanguageCode(t);this.options.supportedLngs&&!this.isSupportedCode(s)||(e=s)})),!e&&this.options.supportedLngs&&t.forEach((t=>{if(e)return;const s=this.getLanguagePartFromCode(t);if(this.isSupportedCode(s))return e=s;e=this.options.supportedLngs.find((t=>t===s?t:t.indexOf("-")<0&&s.indexOf("-")<0?void 0:0===t.indexOf(s)?t:void 0))})),e||(e=this.getFallbackCodes(this.options.fallbackLng)[0]),e}getFallbackCodes(t,e){if(!t)return[];if("function"==typeof t&&(t=t(e)),"string"==typeof t&&(t=[t]),"[object Array]"===Object.prototype.toString.apply(t))return t;if(!e)return t.default||[];let s=t[e];return s||(s=t[this.getScriptPartFromCode(e)]),s||(s=t[this.formatLanguageCode(e)]),s||(s=t[this.getLanguagePartFromCode(e)]),s||(s=t.default),s||[]}toResolveHierarchy(t,e){const s=this.getFallbackCodes(e||this.options.fallbackLng||[],t),i=[],n=t=>{t&&(this.isSupportedCode(t)?i.push(t):this.logger.warn(`rejecting language code not found in supportedLngs: ${t}`))};return"string"==typeof t&&(t.indexOf("-")>-1||t.indexOf("_")>-1)?("languageOnly"!==this.options.load&&n(this.formatLanguageCode(t)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&n(this.getScriptPartFromCode(t)),"currentOnly"!==this.options.load&&n(this.getLanguagePartFromCode(t))):"string"==typeof t&&n(this.formatLanguageCode(t)),s.forEach((t=>{i.indexOf(t)<0&&n(this.formatLanguageCode(t))})),i}}let k=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],L={1:function(t){return Number(t>1)},2:function(t){return Number(1!=t)},3:function(t){return 0},4:function(t){return Number(t%10==1&&t%100!=11?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2)},5:function(t){return Number(0==t?0:1==t?1:2==t?2:t%100>=3&&t%100<=10?3:t%100>=11?4:5)},6:function(t){return Number(1==t?0:t>=2&&t<=4?1:2)},7:function(t){return Number(1==t?0:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?1:2)},8:function(t){return Number(1==t?0:2==t?1:8!=t&&11!=t?2:3)},9:function(t){return Number(t>=2)},10:function(t){return Number(1==t?0:2==t?1:t<7?2:t<11?3:4)},11:function(t){return Number(1==t||11==t?0:2==t||12==t?1:t>2&&t<20?2:3)},12:function(t){return Number(t%10!=1||t%100==11)},13:function(t){return Number(0!==t)},14:function(t){return Number(1==t?0:2==t?1:3==t?2:3)},15:function(t){return Number(t%10==1&&t%100!=11?0:t%10>=2&&(t%100<10||t%100>=20)?1:2)},16:function(t){return Number(t%10==1&&t%100!=11?0:0!==t?1:2)},17:function(t){return Number(1==t||t%10==1&&t%100!=11?0:1)},18:function(t){return Number(0==t?0:1==t?1:2)},19:function(t){return Number(1==t?0:0==t||t%100>1&&t%100<11?1:t%100>10&&t%100<20?2:3)},20:function(t){return Number(1==t?0:0==t||t%100>0&&t%100<20?1:2)},21:function(t){return Number(t%100==1?1:t%100==2?2:t%100==3||t%100==4?3:0)},22:function(t){return Number(1==t?0:2==t?1:(t<0||t>10)&&t%10==0?2:3)}};const O=["v1","v2","v3"],w=["v4"],N={zero:0,one:1,two:2,few:3,many:4,other:5};class R{constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.languageUtils=t,this.options=e,this.logger=s.create("pluralResolver"),this.options.compatibilityJSON&&!w.includes(this.options.compatibilityJSON)||"undefined"!=typeof Intl&&Intl.PluralRules||(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=function(){const t={};return k.forEach((e=>{e.lngs.forEach((s=>{t[s]={numbers:e.nr,plurals:L[e.fc]}}))})),t}()}addRule(t,e){this.rules[t]=e}getRule(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.shouldUseIntlApi())try{return new Intl.PluralRules(f(t),{type:e.ordinal?"ordinal":"cardinal"})}catch(t){return}return this.rules[t]||this.rules[this.languageUtils.getLanguagePartFromCode(t)]}needsPlural(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=this.getRule(t,e);return this.shouldUseIntlApi()?s&&s.resolvedOptions().pluralCategories.length>1:s&&s.numbers.length>1}getPluralFormsOfKey(t,e){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.getSuffixes(t,s).map((t=>`${e}${t}`))}getSuffixes(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=this.getRule(t,e);return s?this.shouldUseIntlApi()?s.resolvedOptions().pluralCategories.sort(((t,e)=>N[t]-N[e])).map((t=>`${this.options.prepend}${e.ordinal?`ordinal${this.options.prepend}`:""}${t}`)):s.numbers.map((s=>this.getSuffix(t,s,e))):[]}getSuffix(t,e){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const i=this.getRule(t,s);return i?this.shouldUseIntlApi()?`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${i.select(e)}`:this.getSuffixRetroCompatible(i,e):(this.logger.warn(`no plural rule found for: ${t}`),"")}getSuffixRetroCompatible(t,e){const s=t.noAbs?t.plurals(e):t.plurals(Math.abs(e));let i=t.numbers[s];this.options.simplifyPluralSuffix&&2===t.numbers.length&&1===t.numbers[0]&&(2===i?i="plural":1===i&&(i=""));const n=()=>this.options.prepend&&i.toString()?this.options.prepend+i.toString():i.toString();return"v1"===this.options.compatibilityJSON?1===i?"":"number"==typeof i?`_plural_${i.toString()}`:n():"v2"===this.options.compatibilityJSON||this.options.simplifyPluralSuffix&&2===t.numbers.length&&1===t.numbers[0]?n():this.options.prepend&&s.toString()?this.options.prepend+s.toString():s.toString()}shouldUseIntlApi(){return!O.includes(this.options.compatibilityJSON)}}function $(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:".",n=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],o=function(t,e,s){const i=l(t,s);return void 0!==i?i:l(e,s)}(t,e,s);return!o&&n&&"string"==typeof s&&(o=d(t,s,i),void 0===o&&(o=d(e,s,i))),o}class P{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.logger=s.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||(t=>t),this.init(t)}init(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.interpolation||(t.interpolation={escapeValue:!0});const e=t.interpolation;this.escape=void 0!==e.escape?e.escape:p,this.escapeValue=void 0===e.escapeValue||e.escapeValue,this.useRawValueToEscape=void 0!==e.useRawValueToEscape&&e.useRawValueToEscape,this.prefix=e.prefix?h(e.prefix):e.prefixEscaped||"{{",this.suffix=e.suffix?h(e.suffix):e.suffixEscaped||"}}",this.formatSeparator=e.formatSeparator?e.formatSeparator:e.formatSeparator||",",this.unescapePrefix=e.unescapeSuffix?"":e.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":e.unescapeSuffix||"",this.nestingPrefix=e.nestingPrefix?h(e.nestingPrefix):e.nestingPrefixEscaped||h("$t("),this.nestingSuffix=e.nestingSuffix?h(e.nestingSuffix):e.nestingSuffixEscaped||h(")"),this.nestingOptionsSeparator=e.nestingOptionsSeparator?e.nestingOptionsSeparator:e.nestingOptionsSeparator||",",this.maxReplaces=e.maxReplaces?e.maxReplaces:1e3,this.alwaysFormat=void 0!==e.alwaysFormat&&e.alwaysFormat,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const t=`${this.prefix}(.+?)${this.suffix}`;this.regexp=new RegExp(t,"g");const e=`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;this.regexpUnescape=new RegExp(e,"g");const s=`${this.nestingPrefix}(.+?)${this.nestingSuffix}`;this.nestingRegexp=new RegExp(s,"g")}interpolate(t,e,s,i){let n,r,a;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function u(t){return t.replace(/\$/g,"$$$$")}const h=t=>{if(t.indexOf(this.formatSeparator)<0){const n=$(e,l,t,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(n,void 0,s,{...i,...e,interpolationkey:t}):n}const n=t.split(this.formatSeparator),o=n.shift().trim(),r=n.join(this.formatSeparator).trim();return this.format($(e,l,o,this.options.keySeparator,this.options.ignoreJSONStructure),r,s,{...i,...e,interpolationkey:o})};this.resetRegExp();const c=i&&i.missingInterpolationHandler||this.options.missingInterpolationHandler,p=i&&i.interpolation&&void 0!==i.interpolation.skipOnVariables?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:t=>u(t)},{regex:this.regexp,safeValue:t=>this.escapeValue?u(this.escape(t)):u(t)}].forEach((e=>{for(a=0;n=e.regex.exec(t);){const s=n[1].trim();if(r=h(s),void 0===r)if("function"==typeof c){const e=c(t,n,i);r="string"==typeof e?e:""}else if(i&&Object.prototype.hasOwnProperty.call(i,s))r="";else{if(p){r=n[0];continue}this.logger.warn(`missed to pass in variable ${s} for interpolating ${t}`),r=""}else"string"==typeof r||this.useRawValueToEscape||(r=o(r));const l=e.safeValue(r);if(t=t.replace(n[0],l),p?(e.regex.lastIndex+=r.length,e.regex.lastIndex-=n[0].length):e.regex.lastIndex=0,a++,a>=this.maxReplaces)break}})),t}nest(t,e){let s,i,n,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};function a(t,e){const s=this.nestingOptionsSeparator;if(t.indexOf(s)<0)return t;const i=t.split(new RegExp(`${s}[ ]*{`));let o=`{${i[1]}`;t=i[0],o=this.interpolate(o,n);const r=o.match(/'/g),a=o.match(/"/g);(r&&r.length%2==0&&!a||a.length%2!=0)&&(o=o.replace(/'/g,'"'));try{n=JSON.parse(o),e&&(n={...e,...n})}catch(e){return this.logger.warn(`failed parsing options string in nesting for key ${t}`,e),`${t}${s}${o}`}return delete n.defaultValue,t}for(;s=this.nestingRegexp.exec(t);){let l=[];n={...r},n=n.replace&&"string"!=typeof n.replace?n.replace:n,n.applyPostProcessor=!1,delete n.defaultValue;let u=!1;if(-1!==s[0].indexOf(this.formatSeparator)&&!/{.*}/.test(s[1])){const t=s[1].split(this.formatSeparator).map((t=>t.trim()));s[1]=t.shift(),l=t,u=!0}if(i=e(a.call(this,s[1].trim(),n),n),i&&s[0]===t&&"string"!=typeof i)return i;"string"!=typeof i&&(i=o(i)),i||(this.logger.warn(`missed to resolve ${s[1]} for nesting ${t}`),i=""),u&&(i=l.reduce(((t,e)=>this.format(t,e,r.lng,{...r,interpolationkey:s[1].trim()})),i.trim())),t=t.replace(s[0],i),this.regexp.lastIndex=0}return t}}function C(t){const e={};return function(s,i,n){const o=i+JSON.stringify(n);let r=e[o];return r||(r=t(f(i),n),e[o]=r),r(s)}}class j{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.logger=s.create("formatter"),this.options=t,this.formats={number:C(((t,e)=>{const s=new Intl.NumberFormat(t,{...e});return t=>s.format(t)})),currency:C(((t,e)=>{const s=new Intl.NumberFormat(t,{...e,style:"currency"});return t=>s.format(t)})),datetime:C(((t,e)=>{const s=new Intl.DateTimeFormat(t,{...e});return t=>s.format(t)})),relativetime:C(((t,e)=>{const s=new Intl.RelativeTimeFormat(t,{...e});return t=>s.format(t,e.range||"day")})),list:C(((t,e)=>{const s=new Intl.ListFormat(t,{...e});return t=>s.format(t)}))},this.init(t)}init(t){const e=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=e.formatSeparator?e.formatSeparator:e.formatSeparator||","}add(t,e){this.formats[t.toLowerCase().trim()]=e}addCached(t,e){this.formats[t.toLowerCase().trim()]=C(e)}format(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return e.split(this.formatSeparator).reduce(((t,e)=>{const{formatName:n,formatOptions:o}=function(t){let e=t.toLowerCase().trim();const s={};if(t.indexOf("(")>-1){const i=t.split("(");e=i[0].toLowerCase().trim();const n=i[1].substring(0,i[1].length-1);"currency"===e&&n.indexOf(":")<0?s.currency||(s.currency=n.trim()):"relativetime"===e&&n.indexOf(":")<0?s.range||(s.range=n.trim()):n.split(";").forEach((t=>{if(!t)return;const[e,...i]=t.split(":"),n=i.join(":").trim().replace(/^'+|'+$/g,"");s[e.trim()]||(s[e.trim()]=n),"false"===n&&(s[e.trim()]=!1),"true"===n&&(s[e.trim()]=!0),isNaN(n)||(s[e.trim()]=parseInt(n,10))}))}return{formatName:e,formatOptions:s}}(e);if(this.formats[n]){let e=t;try{const r=i&&i.formatParams&&i.formatParams[i.interpolationkey]||{},a=r.locale||r.lng||i.locale||i.lng||s;e=this.formats[n](t,a,{...o,...i,...r})}catch(t){this.logger.warn(t)}return e}return this.logger.warn(`there was no format function for ${n}`),t}),t)}}class E extends i{constructor(t,e,i){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};super(),this.backend=t,this.store=e,this.services=i,this.languageUtils=i.languageUtils,this.options=n,this.logger=s.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=n.maxParallelReads||10,this.readingCalls=0,this.maxRetries=n.maxRetries>=0?n.maxRetries:5,this.retryTimeout=n.retryTimeout>=1?n.retryTimeout:350,this.state={},this.queue=[],this.backend&&this.backend.init&&this.backend.init(i,n.backend,n)}queueLoad(t,e,s,i){const n={},o={},r={},a={};return t.forEach((t=>{let i=!0;e.forEach((e=>{const r=`${t}|${e}`;!s.reload&&this.store.hasResourceBundle(t,e)?this.state[r]=2:this.state[r]<0||(1===this.state[r]?void 0===o[r]&&(o[r]=!0):(this.state[r]=1,i=!1,void 0===o[r]&&(o[r]=!0),void 0===n[r]&&(n[r]=!0),void 0===a[e]&&(a[e]=!0)))})),i||(r[t]=!0)})),(Object.keys(n).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(n),pending:Object.keys(o),toLoadLanguages:Object.keys(r),toLoadNamespaces:Object.keys(a)}}loaded(t,e,s){const i=t.split("|"),n=i[0],o=i[1];e&&this.emit("failedLoading",n,o,e),s&&this.store.addResourceBundle(n,o,s),this.state[t]=e?-1:2;const a={};this.queue.forEach((s=>{!function(t,e,s,i){const{obj:n,k:o}=r(t,e,Object);n[o]=n[o]||[],i&&(n[o]=n[o].concat(s)),i||n[o].push(s)}(s.loaded,[n],o),function(t,e){void 0!==t.pending[e]&&(delete t.pending[e],t.pendingCount--)}(s,t),e&&s.errors.push(e),0!==s.pendingCount||s.done||(Object.keys(s.loaded).forEach((t=>{a[t]||(a[t]={});const e=s.loaded[t];e.length&&e.forEach((e=>{void 0===a[t][e]&&(a[t][e]=!0)}))})),s.done=!0,s.errors.length?s.callback(s.errors):s.callback())})),this.emit("loaded",a),this.queue=this.queue.filter((t=>!t.done))}read(t,e,s){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:this.retryTimeout,o=arguments.length>5?arguments[5]:void 0;if(!t.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads)return void this.waitingReads.push({lng:t,ns:e,fcName:s,tried:i,wait:n,callback:o});this.readingCalls++;const r=(r,a)=>{if(this.readingCalls--,this.waitingReads.length>0){const t=this.waitingReads.shift();this.read(t.lng,t.ns,t.fcName,t.tried,t.wait,t.callback)}r&&a&&i<this.maxRetries?setTimeout((()=>{this.read.call(this,t,e,s,i+1,2*n,o)}),n):o(r,a)},a=this.backend[s].bind(this.backend);if(2!==a.length)return a(t,e,r);try{const s=a(t,e);s&&"function"==typeof s.then?s.then((t=>r(null,t))).catch(r):r(null,s)}catch(t){r(t)}}prepareLoading(t,e){let s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();"string"==typeof t&&(t=this.languageUtils.toResolveHierarchy(t)),"string"==typeof e&&(e=[e]);const n=this.queueLoad(t,e,s,i);if(!n.toLoad.length)return n.pending.length||i(),null;n.toLoad.forEach((t=>{this.loadOne(t)}))}load(t,e,s){this.prepareLoading(t,e,{},s)}reload(t,e,s){this.prepareLoading(t,e,{reload:!0},s)}loadOne(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";const s=t.split("|"),i=s[0],n=s[1];this.read(i,n,"read",void 0,void 0,((s,o)=>{s&&this.logger.warn(`${e}loading namespace ${n} for language ${i} failed`,s),!s&&o&&this.logger.log(`${e}loaded namespace ${n} for language ${i}`,o),this.loaded(t,s,o)}))}saveMissing(t,e,s,i,n){let o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},r=arguments.length>6&&void 0!==arguments[6]?arguments[6]:()=>{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(e))this.logger.warn(`did not save key "${s}" as the namespace "${e}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");else if(null!=s&&""!==s){if(this.backend&&this.backend.create){const a={...o,isUpdate:n},l=this.backend.create.bind(this.backend);if(l.length<6)try{let n;n=5===l.length?l(t,e,s,i,a):l(t,e,s,i),n&&"function"==typeof n.then?n.then((t=>r(null,t))).catch(r):r(null,n)}catch(t){r(t)}else l(t,e,s,i,r,a)}t&&t[0]&&this.store.addResource(t[0],e,s,i)}}}function F(){return{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(t){let e={};if("object"==typeof t[1]&&(e=t[1]),"string"==typeof t[1]&&(e.defaultValue=t[1]),"string"==typeof t[2]&&(e.tDescription=t[2]),"object"==typeof t[2]||"object"==typeof t[3]){const s=t[3]||t[2];Object.keys(s).forEach((t=>{e[t]=s[t]}))}return e},interpolation:{escapeValue:!0,format:t=>t,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}}function I(t){return"string"==typeof t.ns&&(t.ns=[t.ns]),"string"==typeof t.fallbackLng&&(t.fallbackLng=[t.fallbackLng]),"string"==typeof t.fallbackNS&&(t.fallbackNS=[t.fallbackNS]),t.supportedLngs&&t.supportedLngs.indexOf("cimode")<0&&(t.supportedLngs=t.supportedLngs.concat(["cimode"])),t}function D(){}class V extends i{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;var i;if(super(),this.options=I(t),this.services={},this.logger=s,this.modules={external:[]},i=this,Object.getOwnPropertyNames(Object.getPrototypeOf(i)).forEach((t=>{"function"==typeof i[t]&&(i[t]=i[t].bind(i))})),e&&!this.isInitialized&&!t.isClone){if(!this.options.initImmediate)return this.init(t,e),this;setTimeout((()=>{this.init(t,e)}),0)}}init(){var t=this;let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=arguments.length>1?arguments[1]:void 0;"function"==typeof e&&(i=e,e={}),!e.defaultNS&&!1!==e.defaultNS&&e.ns&&("string"==typeof e.ns?e.defaultNS=e.ns:e.ns.indexOf("translation")<0&&(e.defaultNS=e.ns[0]));const o=F();function r(t){return t?"function"==typeof t?new t:t:null}if(this.options={...o,...this.options,...I(e)},"v1"!==this.options.compatibilityAPI&&(this.options.interpolation={...o.interpolation,...this.options.interpolation}),void 0!==e.keySeparator&&(this.options.userDefinedKeySeparator=e.keySeparator),void 0!==e.nsSeparator&&(this.options.userDefinedNsSeparator=e.nsSeparator),!this.options.isClone){let e;this.modules.logger?s.init(r(this.modules.logger),this.options):s.init(null,this.options),this.modules.formatter?e=this.modules.formatter:"undefined"!=typeof Intl&&(e=j);const i=new S(this.options);this.store=new m(this.options.resources,this.options);const n=this.services;n.logger=s,n.resourceStore=this.store,n.languageUtils=i,n.pluralResolver=new R(i,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),!e||this.options.interpolation.format&&this.options.interpolation.format!==o.interpolation.format||(n.formatter=r(e),n.formatter.init(n,this.options),this.options.interpolation.format=n.formatter.format.bind(n.formatter)),n.interpolator=new P(this.options),n.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},n.backendConnector=new E(r(this.modules.backend),n.resourceStore,n,this.options),n.backendConnector.on("*",(function(e){for(var s=arguments.length,i=new Array(s>1?s-1:0),n=1;n<s;n++)i[n-1]=arguments[n];t.emit(e,...i)})),this.modules.languageDetector&&(n.languageDetector=r(this.modules.languageDetector),n.languageDetector.init&&n.languageDetector.init(n,this.options.detection,this.options)),this.modules.i18nFormat&&(n.i18nFormat=r(this.modules.i18nFormat),n.i18nFormat.init&&n.i18nFormat.init(this)),this.translator=new b(this.services,this.options),this.translator.on("*",(function(e){for(var s=arguments.length,i=new Array(s>1?s-1:0),n=1;n<s;n++)i[n-1]=arguments[n];t.emit(e,...i)})),this.modules.external.forEach((t=>{t.init&&t.init(this)}))}if(this.format=this.options.interpolation.format,i||(i=D),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const t=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);t.length>0&&"dev"!==t[0]&&(this.options.lng=t[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach((e=>{this[e]=function(){return t.store[e](...arguments)}}));["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach((e=>{this[e]=function(){return t.store[e](...arguments),t}}));const a=n(),l=()=>{const t=(t,e)=>{this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(e),i(t,e)};if(this.languages&&"v1"!==this.options.compatibilityAPI&&!this.isInitialized)return t(null,this.t.bind(this));this.changeLanguage(this.options.lng,t)};return this.options.resources||!this.options.initImmediate?l():setTimeout(l,0),a}loadResources(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:D;const s="string"==typeof t?t:this.language;if("function"==typeof t&&(e=t),!this.options.resources||this.options.partialBundledLanguages){if(s&&"cimode"===s.toLowerCase()&&(!this.options.preload||0===this.options.preload.length))return e();const t=[],i=e=>{if(!e)return;if("cimode"===e)return;this.services.languageUtils.toResolveHierarchy(e).forEach((e=>{"cimode"!==e&&t.indexOf(e)<0&&t.push(e)}))};if(s)i(s);else{this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach((t=>i(t)))}this.options.preload&&this.options.preload.forEach((t=>i(t))),this.services.backendConnector.load(t,this.options.ns,(t=>{t||this.resolvedLanguage||!this.language||this.setResolvedLanguage(this.language),e(t)}))}else e(null)}reloadResources(t,e,s){const i=n();return t||(t=this.languages),e||(e=this.options.ns),s||(s=D),this.services.backendConnector.reload(t,e,(t=>{i.resolve(),s(t)})),i}use(t){if(!t)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!t.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===t.type&&(this.modules.backend=t),("logger"===t.type||t.log&&t.warn&&t.error)&&(this.modules.logger=t),"languageDetector"===t.type&&(this.modules.languageDetector=t),"i18nFormat"===t.type&&(this.modules.i18nFormat=t),"postProcessor"===t.type&&y.addPostProcessor(t),"formatter"===t.type&&(this.modules.formatter=t),"3rdParty"===t.type&&this.modules.external.push(t),this}setResolvedLanguage(t){if(t&&this.languages&&!(["cimode","dev"].indexOf(t)>-1))for(let t=0;t<this.languages.length;t++){const e=this.languages[t];if(!(["cimode","dev"].indexOf(e)>-1)&&this.store.hasLanguageSomeTranslations(e)){this.resolvedLanguage=e;break}}}changeLanguage(t,e){var s=this;this.isLanguageChangingTo=t;const i=n();this.emit("languageChanging",t);const o=t=>{this.language=t,this.languages=this.services.languageUtils.toResolveHierarchy(t),this.resolvedLanguage=void 0,this.setResolvedLanguage(t)},r=(t,n)=>{n?(o(n),this.translator.changeLanguage(n),this.isLanguageChangingTo=void 0,this.emit("languageChanged",n),this.logger.log("languageChanged",n)):this.isLanguageChangingTo=void 0,i.resolve((function(){return s.t(...arguments)})),e&&e(t,(function(){return s.t(...arguments)}))},a=e=>{t||e||!this.services.languageDetector||(e=[]);const s="string"==typeof e?e:this.services.languageUtils.getBestMatchFromCodes(e);s&&(this.language||o(s),this.translator.language||this.translator.changeLanguage(s),this.services.languageDetector&&this.services.languageDetector.cacheUserLanguage&&this.services.languageDetector.cacheUserLanguage(s)),this.loadResources(s,(t=>{r(t,s)}))};return t||!this.services.languageDetector||this.services.languageDetector.async?!t&&this.services.languageDetector&&this.services.languageDetector.async?0===this.services.languageDetector.detect.length?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(t):a(this.services.languageDetector.detect()),i}getFixedT(t,e,s){var i=this;const n=function(t,e){let o;if("object"!=typeof e){for(var r=arguments.length,a=new Array(r>2?r-2:0),l=2;l<r;l++)a[l-2]=arguments[l];o=i.options.overloadTranslationOptionHandler([t,e].concat(a))}else o={...e};o.lng=o.lng||n.lng,o.lngs=o.lngs||n.lngs,o.ns=o.ns||n.ns,o.keyPrefix=o.keyPrefix||s||n.keyPrefix;const u=i.options.keySeparator||".";let h;return h=o.keyPrefix&&Array.isArray(t)?t.map((t=>`${o.keyPrefix}${u}${t}`)):o.keyPrefix?`${o.keyPrefix}${u}${t}`:t,i.t(h,o)};return"string"==typeof t?n.lng=t:n.lngs=t,n.ns=e,n.keyPrefix=s,n}t(){return this.translator&&this.translator.translate(...arguments)}exists(){return this.translator&&this.translator.exists(...arguments)}setDefaultNamespace(t){this.options.defaultNS=t}hasLoadedNamespace(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const s=e.lng||this.resolvedLanguage||this.languages[0],i=!!this.options&&this.options.fallbackLng,n=this.languages[this.languages.length-1];if("cimode"===s.toLowerCase())return!0;const o=(t,e)=>{const s=this.services.backendConnector.state[`${t}|${e}`];return-1===s||2===s};if(e.precheck){const t=e.precheck(this,o);if(void 0!==t)return t}return!!this.hasResourceBundle(s,t)||(!(this.services.backendConnector.backend&&(!this.options.resources||this.options.partialBundledLanguages))||!(!o(s,t)||i&&!o(n,t)))}loadNamespaces(t,e){const s=n();return this.options.ns?("string"==typeof t&&(t=[t]),t.forEach((t=>{this.options.ns.indexOf(t)<0&&this.options.ns.push(t)})),this.loadResources((t=>{s.resolve(),e&&e(t)})),s):(e&&e(),Promise.resolve())}loadLanguages(t,e){const s=n();"string"==typeof t&&(t=[t]);const i=this.options.preload||[],o=t.filter((t=>i.indexOf(t)<0));return o.length?(this.options.preload=i.concat(o),this.loadResources((t=>{s.resolve(),e&&e(t)})),s):(e&&e(),Promise.resolve())}dir(t){if(t||(t=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!t)return"rtl";const e=this.services&&this.services.languageUtils||new S(F());return["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"].indexOf(e.getLanguagePartFromCode(t))>-1||t.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(){return new V(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1?arguments[1]:void 0)}cloneInstance(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:D;const s=t.forkResourceStore;s&&delete t.forkResourceStore;const i={...this.options,...t,isClone:!0},n=new V(i);void 0===t.debug&&void 0===t.prefix||(n.logger=n.logger.clone(t));return["store","services","language"].forEach((t=>{n[t]=this[t]})),n.services={...this.services},n.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},s&&(n.store=new m(this.store.data,i),n.services.resourceStore=n.store),n.translator=new b(n.services,i),n.translator.on("*",(function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];n.emit(t,...s)})),n.init(i,e),n.translator.options=i,n.translator.backendConnector.services.utils={hasLoadedNamespace:n.hasLoadedNamespace.bind(n)},n}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const T=V.createInstance();return T.createInstance=V.createInstance,T}));
diff --git a/frontend/src/js/lib/i18nextBrowserLanguageDetector.min.js b/frontend/src/js/lib/i18nextBrowserLanguageDetector.min.js
deleted file mode 100644
index f4530ae..0000000
--- a/frontend/src/js/lib/i18nextBrowserLanguageDetector.min.js
+++ /dev/null
@@ -1 +0,0 @@
-!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e="undefined"!=typeof globalThis?globalThis:e||self).i18nextBrowserLanguageDetector=o()}(this,(function(){"use strict";function e(e,o){if(!(e instanceof o))throw new TypeError("Cannot call a class as a function")}function o(e){return o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o(e)}function t(e){var t=function(e,t){if("object"!==o(e)||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t||"default");if("object"!==o(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===o(t)?t:String(t)}function n(e,o){for(var n=0;n<o.length;n++){var i=o[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,t(i.key),i)}}var i=[],r=i.forEach,a=i.slice;function u(e){return r.call(a.call(arguments,1),(function(o){if(o)for(var t in o)void 0===e[t]&&(e[t]=o[t])})),e}var s=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,c=function(e,o,t){var n=t||{};n.path=n.path||"/";var i=encodeURIComponent(o),r="".concat(e,"=").concat(i);if(n.maxAge>0){var a=n.maxAge-0;if(Number.isNaN(a))throw new Error("maxAge should be a Number");r+="; Max-Age=".concat(Math.floor(a))}if(n.domain){if(!s.test(n.domain))throw new TypeError("option domain is invalid");r+="; Domain=".concat(n.domain)}if(n.path){if(!s.test(n.path))throw new TypeError("option path is invalid");r+="; Path=".concat(n.path)}if(n.expires){if("function"!=typeof n.expires.toUTCString)throw new TypeError("option expires is invalid");r+="; Expires=".concat(n.expires.toUTCString())}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite)switch("string"==typeof n.sameSite?n.sameSite.toLowerCase():n.sameSite){case!0:r+="; SameSite=Strict";break;case"lax":r+="; SameSite=Lax";break;case"strict":r+="; SameSite=Strict";break;case"none":r+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r},l=function(e,o,t,n){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{path:"/",sameSite:"strict"};t&&(i.expires=new Date,i.expires.setTime(i.expires.getTime()+60*t*1e3)),n&&(i.domain=n),document.cookie=c(e,encodeURIComponent(o),i)},f=function(e){for(var o="".concat(e,"="),t=document.cookie.split(";"),n=0;n<t.length;n++){for(var i=t[n];" "===i.charAt(0);)i=i.substring(1,i.length);if(0===i.indexOf(o))return i.substring(o.length,i.length)}return null},d={name:"cookie",lookup:function(e){var o;if(e.lookupCookie&&"undefined"!=typeof document){var t=f(e.lookupCookie);t&&(o=t)}return o},cacheUserLanguage:function(e,o){o.lookupCookie&&"undefined"!=typeof document&&l(o.lookupCookie,e,o.cookieMinutes,o.cookieDomain,o.cookieOptions)}},g={name:"querystring",lookup:function(e){var o;if("undefined"!=typeof window){var t=window.location.search;!window.location.search&&window.location.hash&&window.location.hash.indexOf("?")>-1&&(t=window.location.hash.substring(window.location.hash.indexOf("?")));for(var n=t.substring(1).split("&"),i=0;i<n.length;i++){var r=n[i].indexOf("=");if(r>0)n[i].substring(0,r)===e.lookupQuerystring&&(o=n[i].substring(r+1))}}return o}},p=null,h=function(){if(null!==p)return p;try{p="undefined"!==window&&null!==window.localStorage;var e="i18next.translate.boo";window.localStorage.setItem(e,"foo"),window.localStorage.removeItem(e)}catch(e){p=!1}return p},m={name:"localStorage",lookup:function(e){var o;if(e.lookupLocalStorage&&h()){var t=window.localStorage.getItem(e.lookupLocalStorage);t&&(o=t)}return o},cacheUserLanguage:function(e,o){o.lookupLocalStorage&&h()&&window.localStorage.setItem(o.lookupLocalStorage,e)}},v=null,w=function(){if(null!==v)return v;try{v="undefined"!==window&&null!==window.sessionStorage;var e="i18next.translate.boo";window.sessionStorage.setItem(e,"foo"),window.sessionStorage.removeItem(e)}catch(e){v=!1}return v},y={name:"sessionStorage",lookup:function(e){var o;if(e.lookupSessionStorage&&w()){var t=window.sessionStorage.getItem(e.lookupSessionStorage);t&&(o=t)}return o},cacheUserLanguage:function(e,o){o.lookupSessionStorage&&w()&&window.sessionStorage.setItem(o.lookupSessionStorage,e)}},S={name:"navigator",lookup:function(e){var o=[];if("undefined"!=typeof navigator){if(navigator.languages)for(var t=0;t<navigator.languages.length;t++)o.push(navigator.languages[t]);navigator.userLanguage&&o.push(navigator.userLanguage),navigator.language&&o.push(navigator.language)}return o.length>0?o:void 0}},k={name:"htmlTag",lookup:function(e){var o,t=e.htmlTag||("undefined"!=typeof document?document.documentElement:null);return t&&"function"==typeof t.getAttribute&&(o=t.getAttribute("lang")),o}},b={name:"path",lookup:function(e){var o;if("undefined"!=typeof window){var t=window.location.pathname.match(/\/([a-zA-Z-]*)/g);if(t instanceof Array)if("number"==typeof e.lookupFromPathIndex){if("string"!=typeof t[e.lookupFromPathIndex])return;o=t[e.lookupFromPathIndex].replace("/","")}else o=t[0].replace("/","")}return o}},x={name:"subdomain",lookup:function(e){var o="number"==typeof e.lookupFromSubdomainIndex?e.lookupFromSubdomainIndex+1:1,t="undefined"!=typeof window&&window.location&&window.location.hostname&&window.location.hostname.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(t)return t[o]}};var L=function(){function o(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e(this,o),this.type="languageDetector",this.detectors={},this.init(t,n)}var t,i,r;return t=o,i=[{key:"init",value:function(e){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};this.services=e||{languageUtils:{}},this.options=u(o,this.options||{},{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:function(e){return e}}),"string"==typeof this.options.convertDetectedLanguage&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=function(e){return e.replace("-","_")}),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=t,this.addDetector(d),this.addDetector(g),this.addDetector(m),this.addDetector(y),this.addDetector(S),this.addDetector(k),this.addDetector(b),this.addDetector(x)}},{key:"addDetector",value:function(e){this.detectors[e.name]=e}},{key:"detect",value:function(e){var o=this;e||(e=this.options.order);var t=[];return e.forEach((function(e){if(o.detectors[e]){var n=o.detectors[e].lookup(o.options);n&&"string"==typeof n&&(n=[n]),n&&(t=t.concat(n))}})),t=t.map((function(e){return o.options.convertDetectedLanguage(e)})),this.services.languageUtils.getBestMatchFromCodes?t:t.length>0?t[0]:null}},{key:"cacheUserLanguage",value:function(e,o){var t=this;o||(o=this.options.caches),o&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(e)>-1||o.forEach((function(o){t.detectors[o]&&t.detectors[o].cacheUserLanguage(e,t.options)})))}}],i&&n(t.prototype,i),r&&n(t,r),Object.defineProperty(t,"prototype",{writable:!1}),o}();return L.type="languageDetector",L}));
diff --git a/frontend/src/js/lib/i18nextHttpBackend.min.js b/frontend/src/js/lib/i18nextHttpBackend.min.js
deleted file mode 100644
index 7f1f20e..0000000
--- a/frontend/src/js/lib/i18nextHttpBackend.min.js
+++ /dev/null
@@ -1 +0,0 @@
-!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).i18nextHttpBackend=e()}(function(){return function o(r,i,s){function a(t,e){if(!i[t]){if(!r[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);throw(e=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",e}n=i[t]={exports:{}},r[t][0].call(n.exports,function(e){return a(r[t][1][e]||e)},n,n.exports,o,r,i,s)}return i[t].exports}for(var u="function"==typeof require&&require,e=0;e<s.length;e++)a(s[e]);return a}({1:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var a=e("./utils.js"),r=(e=e("./request.js"))&&e.__esModule?e:{default:e};function i(e){return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function s(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?o(Object(n),!0).forEach(function(e){c(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):o(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function u(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,f(o.key),o)}}function c(e,t,n){return(t=f(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function f(e){e=((e,t)=>{if("object"!=i(e)||!e)return e;var n=e[Symbol.toPrimitive];if(void 0===n)return("string"===t?String:Number)(e);if("object"!=i(n=n.call(e,t||"default")))return n;throw new TypeError("@@toPrimitive must return a primitive value.")})(e,"string");return"symbol"==i(e)?e:e+""}e=function e(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},o=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},r=this,i=e;if(!(r instanceof i))throw new TypeError("Cannot call a class as a function");this.services=t,this.options=n,this.allOptions=o,this.type="backend",this.init(t,n,o)},(d=[{key:"init",value:function(e){var t=this,n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},o=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};this.services=e,this.options=s(s(s({},{loadPath:"/locales/{{lng}}/{{ns}}.json",addPath:"/locales/add/{{lng}}/{{ns}}",parse:function(e){return JSON.parse(e)},stringify:JSON.stringify,parsePayload:function(e,t,n){return c({},t,n||"")},parseLoadPayload:function(e,t){},request:r.default,reloadInterval:"undefined"==typeof window&&36e5,customHeaders:{},queryStringParams:{},crossDomain:!1,withCredentials:!1,overrideMimeType:!1,requestOptions:{mode:"cors",credentials:"same-origin",cache:"default"}}),this.options||{}),n),this.allOptions=o,this.services&&this.options.reloadInterval&&"object"===i(e=setInterval(function(){return t.reload()},this.options.reloadInterval))&&"function"==typeof e.unref&&e.unref()}},{key:"readMulti",value:function(e,t,n){this._readAny(e,e,t,t,n)}},{key:"read",value:function(e,t,n){this._readAny([e],e,[t],t,n)}},{key:"_readAny",value:function(t,n,o,r,i){var s=this,e=this.options.loadPath;"function"==typeof this.options.loadPath&&(e=this.options.loadPath(t,o)),(e=(0,a.makePromise)(e)).then(function(e){if(!e)return i(null,{});e=s.services.interpolator.interpolate(e,{lng:t.join("+"),ns:o.join("+")});s.loadUrl(e,i,n,r)})}},{key:"loadUrl",value:function(i,s,a,u){var c=this,e=this.options.parseLoadPayload("string"==typeof a?[a]:a,"string"==typeof u?[u]:u);this.options.request(this.options,i,e,function(e,t){if(t&&(500<=t.status&&t.status<600||!t.status))return s("failed loading "+i+"; status code: "+t.status,!0);if(t&&400<=t.status&&t.status<500)return s("failed loading "+i+"; status code: "+t.status,!1);if(!t&&e&&e.message){var n=e.message.toLowerCase();if(["failed","fetch","network","load"].find(function(e){return-1<n.indexOf(e)}))return s("failed loading "+i+": "+e.message,!0)}if(e)return s(e,!1);var o,r;try{o="string"==typeof t.data?c.options.parse(t.data,a,u):t.data}catch(e){r="failed parsing "+i+" to json"}if(r)return s(r,!1);s(null,o)})}},{key:"create",value:function(n,o,e,t,r){var i,s,a,u,c=this;this.options.addPath&&("string"==typeof n&&(n=[n]),i=this.options.parsePayload(o,e,t),s=0,a=[],u=[],n.forEach(function(e){var t=c.options.addPath,t=("function"==typeof c.options.addPath&&(t=c.options.addPath(e,o)),c.services.interpolator.interpolate(t,{lng:e,ns:o}));c.options.request(c.options,t,i,function(e,t){s+=1,a.push(e),u.push(t),s===n.length&&"function"==typeof r&&r(a,u)})}))}},{key:"reload",value:function(){var t,e,n=this,o=this.services,r=o.backendConnector,i=o.languageUtils,s=o.logger,o=r.language;o&&"cimode"===o.toLowerCase()||(t=[],(e=function(e){i.toResolveHierarchy(e).forEach(function(e){t.indexOf(e)<0&&t.push(e)})})(o),this.allOptions.preload&&this.allOptions.preload.forEach(e),t.forEach(function(o){n.allOptions.ns.forEach(function(n){r.read(o,n,"read",null,null,function(e,t){e&&s.warn("loading namespace ".concat(n," for language ").concat(o," failed"),e),!e&&t&&s.log("loaded namespace ".concat(n," for language ").concat(o),t),r.loaded("".concat(o,"|").concat(n),e,t)})})}))}}])&&u(e.prototype,d),l&&u(e,l),Object.defineProperty(e,"prototype",{writable:!1});var l,d=e;d.type="backend",n.default=d;t.exports=n.default},{"./request.js":2,"./utils.js":3}],2:[function(e,n,o){!function(S){!function(){Object.defineProperty(o,"__esModule",{value:!0}),o.default=void 0;var h=e("./utils.js");function t(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function b(o){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?t(Object(r),!0).forEach(function(e){var t,n;t=o,n=r[e=e],(e=(e=>(e=((e,t)=>{if("object"!=v(e)||!e)return e;var n=e[Symbol.toPrimitive];if(void 0===n)return("string"===t?String:Number)(e);if("object"!=v(n=n.call(e,t||"default")))return n;throw new TypeError("@@toPrimitive must return a primitive value.")})(e,"string"),"symbol"==v(e)?e:e+""))(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(r)):t(Object(r)).forEach(function(e){Object.defineProperty(o,e,Object.getOwnPropertyDescriptor(r,e))})}return o}function v(e){return(v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var m,g,O="function"==typeof fetch?fetch:void 0;if(void 0!==S&&S.fetch?O=S.fetch:"undefined"!=typeof window&&window.fetch&&(O=window.fetch),(0,h.hasXMLHttpRequest)()&&(void 0!==S&&S.XMLHttpRequest?m=S.XMLHttpRequest:"undefined"!=typeof window&&window.XMLHttpRequest&&(m=window.XMLHttpRequest)),"function"==typeof ActiveXObject&&(void 0!==S&&S.ActiveXObject?g=S.ActiveXObject:"undefined"!=typeof window&&window.ActiveXObject&&(g=window.ActiveXObject)),!(O="function"!=typeof O?void 0:O)&&!m&&!g)try{O=e("cross-fetch")}catch(e){}var w=function(e,t){if(t&&"object"===v(t)){var n,o="";for(n in t)o+="&"+encodeURIComponent(n)+"="+encodeURIComponent(t[n]);if(!o)return e;e=e+(-1!==e.indexOf("?")?"&":"?")+o.slice(1)}return e},j=function(e,t,n,o){function r(t){if(!t.ok)return n(t.statusText||"Error",{status:t.status});t.text().then(function(e){n(null,{status:t.status,data:e})}).catch(n)}if(o){o=o(e,t);if(o instanceof Promise)return void o.then(r).catch(n)}("function"==typeof fetch?fetch:O)(e,t).then(r).catch(n)},P=!1;o.default=function(e,t,n,o){if("function"==typeof n&&(o=n,n=void 0),o=o||function(){},O&&0!==t.indexOf("file:")){var r=e,i=t,s=n,a=o,u=(r.queryStringParams&&(i=w(i,r.queryStringParams)),b({},"function"==typeof r.customHeaders?r.customHeaders():r.customHeaders)),c=("undefined"==typeof window&&void 0!==S&&void 0!==S.process&&S.process.versions&&S.process.versions.node&&(u["User-Agent"]="i18next-http-backend (node/".concat(S.process.version,"; ").concat(S.process.platform," ").concat(S.process.arch,")")),s&&(u["Content-Type"]="application/json"),"function"==typeof r.requestOptions?r.requestOptions(s):r.requestOptions),f=b({method:s?"POST":"GET",body:s?r.stringify(s):void 0,headers:u},P?{}:c),s="function"==typeof r.alternateFetch&&1<=r.alternateFetch.length?r.alternateFetch:void 0;try{j(i,f,a,s)}catch(e){if(!c||0===Object.keys(c).length||!e.message||e.message.indexOf("not implemented")<0)return a(e);try{Object.keys(c).forEach(function(e){delete f[e]}),j(i,f,a,s),P=!0}catch(e){a(e)}}}else if((0,h.hasXMLHttpRequest)()||"function"==typeof ActiveXObject){var u=e,r=t,c=n,l=o;c&&"object"===v(c)&&(c=w("",c).slice(1)),u.queryStringParams&&(r=w(r,u.queryStringParams));try{var d=m?new m:new g("MSXML2.XMLHTTP.3.0"),p=(d.open(c?"POST":"GET",r,1),u.crossDomain||d.setRequestHeader("X-Requested-With","XMLHttpRequest"),d.withCredentials=!!u.withCredentials,c&&d.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),d.overrideMimeType&&d.overrideMimeType("application/json"),u.customHeaders);if(p="function"==typeof p?p():p)for(var y in p)d.setRequestHeader(y,p[y]);d.onreadystatechange=function(){3<d.readyState&&l(400<=d.status?d.statusText:null,{status:d.status,data:d.responseText})},d.send(c)}catch(e){console&&console.log(e)}}else o(new Error("No fetch and no xhr implementation found!"))};n.exports=o.default}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./utils.js":3,"cross-fetch":4}],3:[function(e,t,n){function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.defaults=function(n){return r.call(i.call(arguments,1),function(e){if(e)for(var t in e)void 0===n[t]&&(n[t]=e[t])}),n},n.hasXMLHttpRequest=function(){return"function"==typeof XMLHttpRequest||"object"===("undefined"==typeof XMLHttpRequest?"undefined":o(XMLHttpRequest))},n.makePromise=function(e){if((e=>e&&"function"==typeof e.then)(e))return e;return Promise.resolve(e)};var n=[],r=n.forEach,i=n.slice},{}],4:[function(e,t,n){},{}]},{},[1])(1)});
\ No newline at end of file
diff --git a/frontend/src/mobile-menu.js b/frontend/src/mobile-menu.js
deleted file mode 100644
index b080815..0000000
--- a/frontend/src/mobile-menu.js
+++ /dev/null
@@ -1,146 +0,0 @@
-(function() {
- function buildMobileMenuContent(panel, header) {
- if (!panel || !header) return;
- if (panel.getAttribute('data-built') === 'true') return;
- panel.innerHTML = '';
-
- const createSection = (titleText) => {
- const title = document.createElement('div');
- title.className = 'section-title';
- title.textContent = titleText;
- panel.appendChild(title);
- };
-
- const appendLinks = (links) => {
- if (!links || links.length === 0) return;
- const list = document.createElement('div');
- list.className = 'menu-list';
- links.forEach(a => {
- try {
- const cloned = a.cloneNode(true);
- if (cloned.id) cloned.id = '';
- list.appendChild(cloned);
- } catch (_) {}
- });
- panel.appendChild(list);
- };
-
- const isAuthenticated = !!(function(){ try { return localStorage.getItem('auth_token'); } catch(_) { return null; } })();
- let displayName = '';
- const headerDisplayNameEl = header.querySelector('#userDisplayName');
- if (headerDisplayNameEl && headerDisplayNameEl.textContent) {
- displayName = headerDisplayNameEl.textContent.trim();
- }
- if (!displayName) {
- try {
- const userInfo = JSON.parse(localStorage.getItem('user_info') || 'null');
- if (userInfo) displayName = userInfo.first_name || userInfo.username || 'Account';
- } catch(_) {}
- }
- if (!displayName) displayName = 'Account';
-
- const navLinksContainer = header.querySelector('.nav-links');
- const navAnchors = navLinksContainer ? Array.from(navLinksContainer.querySelectorAll('a')) : [];
- if (navAnchors.length) {
- createSection('Navigation');
- appendLinks(navAnchors);
- }
-
- const authContainer = header.querySelector('#authContainer');
- const authAnchors = (!isAuthenticated && authContainer) ? Array.from(authContainer.querySelectorAll('a')) : [];
- if (!isAuthenticated && authAnchors.length) {
- createSection('Account');
- appendLinks(authAnchors);
- }
-
- const userDropdown = header.querySelector('#userMenuDropdown');
- const userMenuAnchors = userDropdown ? Array.from(userDropdown.querySelectorAll('a')) : [];
- if (userMenuAnchors.length) {
- createSection(displayName || 'Menu');
- appendLinks(userMenuAnchors);
-
- const logoutSource = header.querySelector('#logoutMenuItem');
- if (logoutSource) {
- const logoutLink = document.createElement('a');
- logoutLink.href = '#';
- logoutLink.id = 'mobileLogoutLink';
- logoutLink.innerHTML = '<i class="fas fa-sign-out-alt"></i> <span>Logout</span>';
- logoutLink.addEventListener('click', async function(e) {
- e.preventDefault();
- try {
- if (window.auth && typeof window.auth.logout === 'function') {
- await window.auth.logout();
- } else {
- localStorage.removeItem('auth_token');
- localStorage.removeItem('user_info');
- window.location.href = 'login.html';
- }
- } catch (_) {
- localStorage.removeItem('auth_token');
- localStorage.removeItem('user_info');
- window.location.href = 'login.html';
- }
- });
- const list = document.createElement('div');
- list.className = 'menu-list';
- list.appendChild(logoutLink);
- panel.appendChild(list);
- }
- }
-
- panel.setAttribute('data-built', 'true');
- }
-
- function initializeMobileMenu() {
- const header = document.querySelector('header');
- if (!header) return;
- const toggleBtn = header.querySelector('.mobile-menu-toggle');
- const panel = document.getElementById('mobileMenuPanel');
- const overlay = document.getElementById('mobileMenuOverlay');
- if (!toggleBtn || !panel || !overlay) return;
-
- if (toggleBtn.getAttribute('data-mm-bound') === '1') return;
- toggleBtn.setAttribute('data-mm-bound', '1');
-
- const openMenu = () => {
- buildMobileMenuContent(panel, header);
- panel.classList.add('is-open');
- overlay.classList.add('is-open');
- document.body.classList.add('mobile-menu-active');
- };
-
- const closeMenu = () => {
- panel.classList.remove('is-open');
- overlay.classList.remove('is-open');
- document.body.classList.remove('mobile-menu-active');
- };
-
- toggleBtn.addEventListener('click', function(e) {
- e.preventDefault();
- const isOpen = panel.classList.contains('is-open');
- if (isOpen) closeMenu(); else openMenu();
- });
-
- overlay.addEventListener('click', function() {
- closeMenu();
- });
-
- panel.addEventListener('click', function(e) {
- const link = e.target.closest('a');
- if (link && link.href) {
- closeMenu();
- }
- });
-
- document.addEventListener('keydown', function(e) {
- if (e.key === 'Escape' && panel.classList.contains('is-open')) {
- closeMenu();
- }
- });
- }
-
- window.initializeMobileMenu = initializeMobileMenu;
- document.addEventListener('DOMContentLoaded', initializeMobileMenu);
-})();
-
-
diff --git a/frontend/src/script.js b/frontend/src/script.js
deleted file mode 100644
index f6f4b0b..0000000
--- a/frontend/src/script.js
+++ /dev/null
@@ -1,9644 +0,0 @@
-// ===== MOBILE HAMBURGER MENU (kept for other pages) =====
-(function() {
- function buildMobileMenuContent(panel, header) {
- if (!panel || !header) return;
- // Build only once
- if (panel.getAttribute('data-built') === 'true') return;
- panel.innerHTML = '';
-
- const createSection = (titleText) => {
- const title = document.createElement('div');
- title.className = 'section-title';
- title.textContent = titleText;
- panel.appendChild(title);
- };
-
- const appendLinks = (links) => {
- if (!links || links.length === 0) return;
- const list = document.createElement('div');
- list.className = 'menu-list';
- links.forEach(a => {
- try {
- const cloned = a.cloneNode(true);
- // Remove ids to avoid duplicates
- if (cloned.id) cloned.id = '';
- list.appendChild(cloned);
- } catch (e) {
- // Skip problematic nodes
- }
- });
- panel.appendChild(list);
- };
-
- // Resolve auth state and display name
- const isAuthenticated = !!(function(){ try { return localStorage.getItem('auth_token'); } catch(_) { return null; } })();
- let displayName = '';
- const headerDisplayNameEl = header.querySelector('#userDisplayName');
- if (headerDisplayNameEl && headerDisplayNameEl.textContent) {
- displayName = headerDisplayNameEl.textContent.trim();
- }
- if (!displayName) {
- try {
- const userInfo = JSON.parse(localStorage.getItem('user_info') || 'null');
- if (userInfo) displayName = userInfo.first_name || userInfo.username || 'Account';
- } catch(_) {}
- }
- if (!displayName) displayName = 'Account';
-
- // Nav links
- const navLinksContainer = header.querySelector('.nav-links');
- const navAnchors = navLinksContainer ? Array.from(navLinksContainer.querySelectorAll('a')) : [];
- if (navAnchors.length) {
- createSection('Navigation');
- appendLinks(navAnchors);
- }
-
- // Auth buttons if present (only when NOT authenticated)
- const authContainer = header.querySelector('#authContainer');
- const authAnchors = (!isAuthenticated && authContainer) ? Array.from(authContainer.querySelectorAll('a')) : [];
- if (!isAuthenticated && authAnchors.length) {
- createSection('Account');
- appendLinks(authAnchors);
- }
-
- // User menu dropdown items if present
- const userDropdown = header.querySelector('#userMenuDropdown');
- const userMenuAnchors = userDropdown ? Array.from(userDropdown.querySelectorAll('a')) : [];
- if (userMenuAnchors.length) {
- // Use username as section title when available
- createSection(displayName || 'Menu');
- appendLinks(userMenuAnchors);
-
- // Add Logout if available
- const logoutSource = header.querySelector('#logoutMenuItem');
- if (logoutSource) {
- const logoutLink = document.createElement('a');
- logoutLink.href = '#';
- logoutLink.id = 'mobileLogoutLink';
- logoutLink.innerHTML = '<i class="fas fa-sign-out-alt"></i> <span>Logout</span>';
- logoutLink.addEventListener('click', async function(e) {
- e.preventDefault();
- try {
- if (window.auth && typeof window.auth.logout === 'function') {
- await window.auth.logout();
- } else {
- localStorage.removeItem('auth_token');
- localStorage.removeItem('user_info');
- window.location.href = 'login.html';
- }
- } catch (_) {
- localStorage.removeItem('auth_token');
- localStorage.removeItem('user_info');
- window.location.href = 'login.html';
- }
- });
- const list = document.createElement('div');
- list.className = 'menu-list';
- list.appendChild(logoutLink);
- panel.appendChild(list);
- }
- }
-
- panel.setAttribute('data-built', 'true');
- }
-
- function initializeMobileMenu() {
- const header = document.querySelector('header');
- if (!header) return;
- const toggleBtn = header.querySelector('.mobile-menu-toggle');
- const panel = document.getElementById('mobileMenuPanel');
- const overlay = document.getElementById('mobileMenuOverlay');
- if (!toggleBtn || !panel || !overlay) return;
-
- // Prevent double-binding
- if (toggleBtn.getAttribute('data-mm-bound') === '1') return;
- toggleBtn.setAttribute('data-mm-bound', '1');
-
- const openMenu = () => {
- buildMobileMenuContent(panel, header);
- panel.classList.add('is-open');
- overlay.classList.add('is-open');
- document.body.classList.add('mobile-menu-active');
- };
-
- const closeMenu = () => {
- panel.classList.remove('is-open');
- overlay.classList.remove('is-open');
- document.body.classList.remove('mobile-menu-active');
- };
-
- toggleBtn.addEventListener('click', function(e) {
- e.preventDefault();
- const isOpen = panel.classList.contains('is-open');
- if (isOpen) closeMenu(); else openMenu();
- });
-
- overlay.addEventListener('click', function() {
- closeMenu();
- });
-
- panel.addEventListener('click', function(e) {
- const link = e.target.closest('a');
- if (link && link.href) {
- closeMenu();
- }
- });
-
- document.addEventListener('keydown', function(e) {
- if (e.key === 'Escape' && panel.classList.contains('is-open')) {
- closeMenu();
- }
- });
- }
-
- // Expose and initialize
- window.initializeMobileMenu = initializeMobileMenu;
- document.addEventListener('DOMContentLoaded', initializeMobileMenu);
-})();
-console.log('[SCRIPT VERSION] 20250529-005 - Added CSS cache busting for consistent styling across domains');
-console.log('[DEBUG] script.js loaded and running');
-
-// alert('script.js loaded!'); // Remove alert after confirming script loads
-
-// Global variables
-// Central state wiring: local mirrors kept in sync with store
-let warranties = (window.store && window.store.getWarranties && window.store.getWarranties()) || [];
-window.addEventListener('state:warrantiesChanged', (e) => {
- warranties = e.detail.warranties || [];
- if (typeof applyFilters === 'function') {
- applyFilters();
- }
-});
-let warrantiesLoaded = false; // Track if warranties have been loaded from API
-let lastLoadedArchived = false; // Track if the current warranties array came from archived endpoint
-let lastLoadedIncludesArchived = false; // Track if the current warranties list includes archived items
-let currentTabIndex = 0;
-let tabContents = []; // Initialize as empty array
-let editMode = false;
-let currentWarrantyId = null;
-let userPreferencePrefix = null; // <<< ADDED GLOBAL PREFIX VARIABLE
-let isGlobalView = false; // Track if admin is viewing all users' warranties
-let currentFilters = (window.store && window.store.getFilters && window.store.getFilters()) || {
- status: 'all',
- tag: 'all',
- search: '',
- sortBy: 'expiration',
- vendor: 'all',
- warranty_type: 'all'
-};
-window.addEventListener('state:filtersChanged', (e) => {
- currentFilters = e.detail.filters || currentFilters;
- if (typeof applyFilters === 'function') {
- applyFilters();
- }
-});
-
-// Tag related variables
-let allTags = (window.store && window.store.getAllTags && window.store.getAllTags()) || [];
-window.addEventListener('state:tagsChanged', (e) => {
- allTags = e.detail.allTags || [];
-});
-let selectedTags = []; // Will hold objects with id, name, color
-
-// Global variable for edit mode tags
-let editSelectedTags = [];
-
-// DOM Elements
-const warrantyForm = document.getElementById('warrantyForm');
-const settingsBtn = document.getElementById('settingsBtn');
-const settingsMenu = document.getElementById('settingsMenu');
-const darkModeToggle = document.getElementById('darkModeToggle');
-const warrantiesList = document.getElementById('warrantiesList');
-const refreshBtn = document.getElementById('refreshBtn');
-const searchInput = document.getElementById('searchWarranties');
-const clearSearchBtn = document.getElementById('clearSearch');
-const statusFilter = document.getElementById('statusFilter');
-const sortBySelect = document.getElementById('sortBy');
-const vendorFilter = document.getElementById('vendorFilter'); // Added vendor filter select
-const warrantyTypeFilter = document.getElementById('warrantyTypeFilter'); // Added warranty type filter select
-const exportBtn = document.getElementById('exportBtn');
-const gridViewBtn = document.getElementById('gridViewBtn');
-const listViewBtn = document.getElementById('listViewBtn');
-const tableViewBtn = document.getElementById('tableViewBtn');
-const tableViewHeader = document.querySelector('.table-view-header');
-
-// Admin view controls
-const adminViewSwitcher = document.getElementById('adminViewSwitcher');
-const personalViewBtn = document.getElementById('personalViewBtn');
-const globalViewBtn = document.getElementById('globalViewBtn');
-const warrantiesPanelTitle = document.getElementById('warrantiesPanelTitle');
-const fileInput = document.getElementById('invoice');
-const fileName = document.getElementById('fileName');
-const manualInput = document.getElementById('manual');
-const manualFileName = document.getElementById('manualFileName');
-const otherDocumentInput = document.getElementById('otherDocument');
-const otherDocumentFileName = document.getElementById('otherDocumentFileName');
-const editModal = document.getElementById('editModal');
-const deleteModal = document.getElementById('deleteModal');
-const editWarrantyForm = document.getElementById('editWarrantyForm');
-const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');
-const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
-const loadingContainer = document.getElementById('loadingContainer');
-const toastContainer = document.getElementById('toastContainer');
-
-// CSV Import Elements
-const importBtn = document.getElementById('importBtn');
-const csvFileInput = document.getElementById('csvFileInput');
-if (importBtn) {
- importBtn.classList.remove('import-btn');
- importBtn.classList.add('export-btn');
-}
-
-// Tag DOM Elements
-const selectedTagsContainer = document.getElementById('selectedTags');
-const tagSearch = document.getElementById('tagSearch');
-const tagsList = document.getElementById('tagsList');
-const manageTagsBtn = document.getElementById('manageTagsBtn');
-const tagManagementModal = document.getElementById('tagManagementModal');
-const newTagForm = document.getElementById('newTagForm');
-const existingTagsContainer = document.getElementById('existingTags');
-
-// Claims modal elements
-const claimsModal = document.getElementById('claimsModal');
-const claimFormModal = document.getElementById('claimFormModal');
-const claimsListBody = document.getElementById('claimsListBody');
-const addClaimBtn = document.getElementById('addClaimBtn');
-const claimForm = document.getElementById('claimForm');
-const saveClaimBtn = document.getElementById('saveClaimBtn');
-const editClaimId = document.getElementById('editClaimId');
-const claimFormTitle = document.getElementById('claimFormTitle');
-const warrantyClaimInfo = document.getElementById('warrantyClaimInfo');
-
-// --- Add near other DOM Element declarations ---
-const isLifetimeCheckbox = document.getElementById('isLifetime');
-const warrantyDurationFields = document.getElementById('warrantyDurationFields'); // New container
-const warrantyDurationYearsInput = document.getElementById('warrantyDurationYears');
-const warrantyDurationMonthsInput = document.getElementById('warrantyDurationMonths');
-const warrantyDurationDaysInput = document.getElementById('warrantyDurationDays');
-
-const editIsLifetimeCheckbox = document.getElementById('editIsLifetime');
-const editWarrantyDurationFields = document.getElementById('editWarrantyDurationFields'); // New container
-const editWarrantyDurationYearsInput = document.getElementById('editWarrantyDurationYears');
-const editWarrantyDurationMonthsInput = document.getElementById('editWarrantyDurationMonths');
-const editWarrantyDurationDaysInput = document.getElementById('editWarrantyDurationDays');
-
-// Warranty Type DOM Elements
-const warrantyTypeInput = document.getElementById('warrantyType');
-const warrantyTypeCustomInput = document.getElementById('warrantyTypeCustom');
-const editWarrantyTypeInput = document.getElementById('editWarrantyType');
-const editWarrantyTypeCustomInput = document.getElementById('editWarrantyTypeCustom');
-
-// Warranty method selection elements
-const durationMethodRadio = document.getElementById('durationMethod');
-const exactDateMethodRadio = document.getElementById('exactDateMethod');
-const exactExpirationField = document.getElementById('exactExpirationField');
-const exactExpirationDateInput = document.getElementById('exactExpirationDate');
-
-const editDurationMethodRadio = document.getElementById('editDurationMethod');
-const editExactDateMethodRadio = document.getElementById('editExactDateMethod');
-const editExactExpirationField = document.getElementById('editExactExpirationField');
-const editExactExpirationDateInput = document.getElementById('editExactExpirationDate');
-
-// Add near other DOM Element declarations
-const showAddWarrantyBtn = document.getElementById('showAddWarrantyBtn');
-const addWarrantyModal = document.getElementById('addWarrantyModal');
-
-// Currency dropdown elements
-const currencySelect = document.getElementById('currency');
-const editCurrencySelect = document.getElementById('editCurrency');
-const serialNumbersContainer = document.getElementById('serialNumbersContainer'); // Ensure this is defined
-
-/**
- * Get current user type (admin or user)
- * @returns {string} 'admin' or 'user'
- */
-function getUserType() {
- try {
- const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
- return userInfo.is_admin === true ? 'admin' : 'user';
- } catch (e) {
- console.error('Error determining user type:', e);
- return 'user'; // Default to user if we can't determine
- }
-}
-
-/**
- * Initialize view controls for all authenticated users
- */
-async function initViewControls() {
- // Check if global view is enabled
- try {
- const response = await fetch('/api/settings/global-view-status', {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
- 'Content-Type': 'application/json'
- }
- });
-
- if (response.ok) {
- const result = await response.json();
- const scopeDropdown = document.getElementById('scopeDropdown');
- // Keep bottom admin switcher hidden; control only the header scope dropdown
- if (adminViewSwitcher) adminViewSwitcher.style.display = 'none';
- if (result.enabled) {
- if (scopeDropdown) scopeDropdown.style.display = 'block';
- // Apply saved scope (update title and state)
- const savedScope = loadViewScopePreference();
- if (savedScope === 'global') {
- isGlobalView = true;
- updateWarrantiesPanelTitle(true);
- } else {
- isGlobalView = false;
- updateWarrantiesPanelTitle(false);
- }
- } else {
- if (scopeDropdown) scopeDropdown.style.display = 'none';
- if (isGlobalView) {
- isGlobalView = false;
- updateWarrantiesPanelTitle(false);
- await loadWarranties(true);
- applyFilters();
- }
- }
- } else {
- console.error('Failed to check global view status');
- // Hide bottom switcher even on failure; show header dropdown for fallback
- if (adminViewSwitcher) adminViewSwitcher.style.display = 'none';
- const scopeDropdown = document.getElementById('scopeDropdown');
- if (scopeDropdown) scopeDropdown.style.display = 'block';
- }
- } catch (error) {
- console.error('Error checking global view status:', error);
- // Keep bottom switcher hidden; show header dropdown as fallback
- if (adminViewSwitcher) adminViewSwitcher.style.display = 'none';
- const scopeDropdown = document.getElementById('scopeDropdown');
- if (scopeDropdown) scopeDropdown.style.display = 'block';
- }
-}
-
-/**
- * Switch to personal view (user's own warranties)
- */
-async function switchToPersonalView() {
- if (!personalViewBtn || !globalViewBtn) return;
-
- isGlobalView = false;
- personalViewBtn.classList.add('active');
- globalViewBtn.classList.remove('active');
-
- // Save view preference
- saveViewScopePreference('personal');
-
- // Update title
- updateWarrantiesPanelTitle(false);
-
- // Update header scope label
- try {
- const currentScopeIcon = document.getElementById('currentScopeIcon');
- if (currentScopeIcon) {
- currentScopeIcon.className = 'fas fa-user';
- currentScopeIcon.setAttribute('aria-label', 'Personal');
- }
- } catch (e) { /* no-op */ }
-
- // Reload warranties
- try {
- const token = window.auth.getToken();
- if (token) {
- await loadWarranties(true);
- applyFilters();
- }
- } catch (error) {
- console.error('Error switching to personal view:', error);
- showToast(window.t('messages.error_loading_personal_warranties'), 'error');
- }
-}
-
-/**
- * Switch to global view (all users' warranties) - available to all users
- */
-async function switchToGlobalView() {
- if (!personalViewBtn || !globalViewBtn) return;
-
- // Check if global view is still enabled
- try {
- const response = await fetch('/api/settings/global-view-status', {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
- 'Content-Type': 'application/json'
- }
- });
-
- if (response.ok) {
- const result = await response.json();
- if (!result.enabled) {
- showToast(window.t('messages.global_view_disabled'), 'error');
- return;
- }
- }
- } catch (error) {
- console.error('Error checking global view status:', error);
- }
-
- isGlobalView = true;
- personalViewBtn.classList.remove('active');
- globalViewBtn.classList.add('active');
-
- // Save view preference
- saveViewScopePreference('global');
-
- // Update title
- updateWarrantiesPanelTitle(true);
-
- // Update header scope label
- try {
- const currentScopeIcon = document.getElementById('currentScopeIcon');
- if (currentScopeIcon) {
- currentScopeIcon.className = 'fas fa-globe';
- currentScopeIcon.setAttribute('aria-label', 'Global');
- }
- } catch (e) { /* no-op */ }
-
- // Reload warranties
- try {
- const token = window.auth.getToken();
- if (token) {
- await loadWarranties(true);
- applyFilters();
- }
- } catch (error) {
- console.error('Error switching to global view:', error);
- showToast(window.t('messages.error_loading_global_warranties'), 'error');
- }
-}
-
-/**
- * Update warranties panel title with proper translation
- * @param {boolean} isGlobal - Whether to show global or personal title
- */
-function updateWarrantiesPanelTitle(isGlobal = false) {
- if (warrantiesPanelTitle) {
- if (window.i18next && window.i18next.t) {
- warrantiesPanelTitle.textContent = isGlobal ?
- window.i18next.t('warranties.title_global') :
- window.i18next.t('warranties.title');
- } else {
- warrantiesPanelTitle.textContent = isGlobal ? 'All Users\' Warranties' : 'Your Warranties';
- }
- }
-}
-
-/**
- * Get the appropriate localStorage key prefix based on user type
- * @returns {string} The prefix to use for localStorage keys
- */
-function getPreferenceKeyPrefix() {
- return getUserType() === 'admin' ? 'admin_' : 'user_';
-}
-
-/**
- * Save view scope preference to localStorage
- * @param {string} scope - 'personal' or 'global'
- */
-function saveViewScopePreference(scope) {
- try {
- const prefix = getPreferenceKeyPrefix();
- localStorage.setItem(`${prefix}viewScope`, scope);
- console.log(`Saved view scope preference: ${scope} with prefix: ${prefix}`);
- } catch (error) {
- console.error('Error saving view scope preference:', error);
- }
-}
-
-/**
- * Load view scope preference from localStorage
- * @returns {string} The saved preference ('personal', 'global', or 'personal' as default)
- */
-function loadViewScopePreference() {
- try {
- const prefix = getPreferenceKeyPrefix();
- const savedScope = localStorage.getItem(`${prefix}viewScope`);
- console.log(`Loaded view scope preference: ${savedScope} with prefix: ${prefix}`);
- return savedScope || 'personal'; // Default to personal view
- } catch (error) {
- console.error('Error loading view scope preference:', error);
- return 'personal'; // Default to personal view on error
- }
-}
-
-// Theme Management - Simplified
-function setTheme(isDark) {
- const theme = isDark ? 'dark' : 'light';
- console.log('Setting theme to:', theme);
-
- // 1. Apply theme attribute to document root
- document.documentElement.setAttribute('data-theme', theme);
-
- // 2. Save the single source of truth to localStorage
- localStorage.setItem('darkMode', isDark);
-
- // Update toggle state if the toggle exists on this page (e.g., in the header)
- const headerToggle = document.getElementById('darkModeToggle');
- if (headerToggle) {
- headerToggle.checked = isDark;
- }
-}
-
-// Persist theme to API similar to view/filters
-async function saveThemePreference(isDark, saveToApi = true) {
- try {
- // Always persist locally first
- setTheme(isDark);
-
- if (saveToApi && window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
- const token = window.auth.getToken();
- if (token) {
- try {
- console.log('[Theme] Saving theme preference to API:', isDark ? 'dark' : 'light');
- const response = await fetch('/api/auth/preferences', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({ theme: isDark ? 'dark' : 'light' })
- });
- if (!response.ok) {
- console.warn('[Theme] Failed to save theme to API:', response.status);
- }
- } catch (err) {
- console.error('[Theme] Error saving theme to API:', err);
- }
- }
- }
- } catch (e) {
- console.warn('Failed to save theme preference', e);
- }
-}
-
-// Initialization logic on DOMContentLoaded
-document.addEventListener('DOMContentLoaded', function() {
- // Register Service Worker
- if ('serviceWorker' in navigator) {
- window.addEventListener('load', () => {
- navigator.serviceWorker.register('./sw.js')
- .then(registration => {
- console.log('Service Worker registered with scope:', registration.scope);
- })
- .catch(error => {
- console.error('Service Worker registration failed:', error);
- });
- });
- }
-
- // --- Search button click triggers search ---
- const searchBtn = document.getElementById('searchBtn');
- const searchInput = document.getElementById('searchWarranties');
- if (searchBtn && searchInput) {
- searchBtn.addEventListener('click', function(e) {
- e.preventDefault();
- if (window.store && window.store.updateFilter) window.store.updateFilter('search', searchInput.value.toLowerCase());
- currentFilters.search = searchInput.value.toLowerCase();
- applyFilters();
- });
- }
- // --- Ensure globalManageTagsBtn triggers modal and tag form is always initialized ---
- // (Redundant with setupUIEventListeners, but ensures modal is always ready)
- const globalManageTagsBtn = document.getElementById('globalManageTagsBtn');
- if (globalManageTagsBtn) {
- globalManageTagsBtn.addEventListener('click', async () => {
- if (!allTags || allTags.length === 0) {
- showLoadingSpinner();
- try {
- await loadTags();
- } catch (error) {
- console.error("Failed to load tags before opening modal:", error);
- showToast(window.t('messages.could_not_load_tags'), "error");
- hideLoadingSpinner();
- return;
- }
- hideLoadingSpinner();
- }
- openTagManagementModal();
- });
- }
- console.log('[DEBUG] Registering authStateReady event handler');
- // ... other initialization ...
-
- // --- BEGIN REFACTORED TAG MODAL AND MAIN FORM TAG UI SETUP ---
- const globalTagManagementModal = document.getElementById('tagManagementModal');
- const globalNewTagForm = document.getElementById('newTagForm'); // Inside tagManagementModal
- const mainTagSearchInput = document.getElementById('tagSearch'); // For the main "Add Warranty" form's tag search
- const warrantyFormElement = document.getElementById('warrantyForm'); // The main add warranty form
-
- // 1. ALWAYS Initialize listeners for the global Tag Management Modal IF IT EXISTS
- if (globalTagManagementModal) {
- if (globalNewTagForm) {
- // Ensure the event listener is attached only once, or manage it if DOMContentLoaded could fire multiple times (not typical)
- // For simplicity, assuming DOMContentLoaded runs once per page load.
- globalNewTagForm.addEventListener('submit', (e) => {
- e.preventDefault();
- // Inline implementation for creating a new tag from the modal
- const tagNameInput = document.getElementById('newTagName');
- const tagColorInput = document.getElementById('newTagColor');
- const name = tagNameInput ? tagNameInput.value.trim() : '';
- const color = tagColorInput ? tagColorInput.value : '#808080';
- if (!name) {
- showToast(window.t('messages.tag_name_required'), 'error');
- return;
- }
- // Use the existing createTag function if available
- if (typeof createTag === 'function') {
- createTag(name, color)
- .then(() => {
- if (tagNameInput) tagNameInput.value = '';
- if (tagColorInput) tagColorInput.value = '#808080';
- renderExistingTags && renderExistingTags();
- })
- .catch((err) => {
- showToast((err && err.message) || window.t('messages.failed_to_create_tag'), 'error');
- });
- } else {
- showToast(window.t('messages.tag_creation_function_not_found'), 'error');
- }
- });
- }
-
- const closeButtons = globalTagManagementModal.querySelectorAll('[data-dismiss="modal"]');
- closeButtons.forEach(button => {
- button.addEventListener('click', (event) => {
- globalTagManagementModal.style.display = 'none';
- event.stopPropagation(); // This was the fix from before, ensuring it's applied
- });
- });
- console.log('Global Tag Management Modal listeners initialized directly in DOMContentLoaded.');
- }
-
- // 2. Initialize Tag functionality FOR THE MAIN ADD WARRANTY FORM (if its specific tag search input exists)
- // initTagFunctionality is now refactored to be specific to the main form's tag UI.
- if (mainTagSearchInput) {
- initTagFunctionality(); // Sets up main form tag search, its manage button, etc.
- // Also calls loadTags() if needed for the main form.
- }
- // --- END REFACTORED TAG MODAL AND MAIN FORM TAG UI SETUP ---
-
-
- // Setup form submission (assuming addWarrantyForm exists - this is 'warrantyFormElement')
- // const form = document.getElementById('addWarrantyForm'); // Old selector
- if (warrantyFormElement) { // Use the variable defined above
- warrantyFormElement.addEventListener('submit', handleFormSubmit);
- // Initialize form tabs if the form exists
- // initFormTabs(); // This should be called when the ADD MODAL is SHOWN, not globally here.
- // It's correctly in setupModalTriggers for the addWarrantyModal.
- }
-
-
- // Initialize theme toggle state *after* DOM is loaded
- // ... (theme toggle init logic remains) ...
-
- // Setup view switcher (assuming view switcher elements exist)
- if (document.getElementById('gridViewBtn')) {
- // setupViewSwitcher(); // Removed undefined function
- loadViewPreference(); // This is fine here, loads initial view preference.
- }
-
- // Setup filter controls (assuming filter controls exist)
- if (document.getElementById('filterControls')) {
- // setupFilterControls(); // Removed: function not defined
- // populateTagFilter(); // This should be called AFTER warranties (and their tags) are loaded.
- // It's called in loadWarranties -> processAllWarranties or similar flow.
- }
-
- // Initialize modal interactions (general modal triggers like close buttons, backdrop)
- setupModalTriggers(); // This sets up general modal behaviors and specific triggers for add/edit.
-
- // Initialize form-specific lifetime checkbox handler FOR THE MAIN ADD FORM
- const lifetimeCheckbox = document.getElementById('isLifetime'); // Main form's checkbox
- if (lifetimeCheckbox) {
- lifetimeCheckbox.addEventListener('change', handleLifetimeChange);
- handleLifetimeChange({ target: lifetimeCheckbox }); // Initial check
- }
-
- // Initialize warranty method selection handlers
- if (durationMethodRadio && exactDateMethodRadio) {
- durationMethodRadio.addEventListener('change', handleWarrantyMethodChange);
- exactDateMethodRadio.addEventListener('change', handleWarrantyMethodChange);
- handleWarrantyMethodChange(); // Initial setup
- }
-
- if (editDurationMethodRadio && editExactDateMethodRadio) {
- editDurationMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
- editExactDateMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
- handleEditWarrantyMethodChange(); // Initial setup for edit form
- }
-
- // --- LOAD WARRANTIES AFTER AUTH ---
- let authStateHandled = false;
-
- async function runAuthenticatedTasks(isAuthenticated) { // Added isAuthenticated parameter
- if (!isAuthenticated) {
- console.log('[DEBUG] runAuthenticatedTasks: Called with isAuthenticated = false. Not running tasks yet.');
- // Do not set authStateHandled = true here, allow a subsequent call with true.
- return;
- }
- // If we reach here, isAuthenticated is true.
- if (authStateHandled) {
- console.log('[DEBUG] runAuthenticatedTasks: Tasks already handled (or in progress by another call).');
- return;
- }
- authStateHandled = true; // Set flag only when tasks are actually starting with isAuthenticated = true.
- console.log('[DEBUG] runAuthenticatedTasks: Executing with isAuthenticated = true.');
-
- // Set prefix
- userPreferencePrefix = getPreferenceKeyPrefix();
- console.log(`[runAuthenticatedTasks] Determined and stored global prefix: ${userPreferencePrefix}`);
-
- // Re-check auth status just before critical data loads
- const currentAuthStatus = window.auth && window.auth.isAuthenticated();
- console.log(`[runAuthenticatedTasks] Current auth status before loading prefs/warranties: ${currentAuthStatus}`);
-
- if (currentAuthStatus) {
- await loadAndApplyUserPreferences(true); // Pass true, as we've confirmed auth
- await loadTags(); // Ensure all available tags are loaded
- await loadCurrencies(); // Load currencies for dropdowns
-
- // Initialize Paperless-ngx integration
- await initPaperlessNgxIntegration();
-
- // Initialize view controls for all users
- initViewControls();
-
- if (document.getElementById('warrantiesList')) {
- console.log("[runAuthenticatedTasks] Loading warranty data...");
- await loadWarranties(true); // Pass true
- console.log('[DEBUG] After loadWarranties, warranties array:', warranties);
- // After warranties are loaded and filter dropdowns populated, load filter/sort prefs and apply
- loadFilterAndSortPreferences();
- // Reflect saved filters in UI selects if present
- const statusFilterEl = document.getElementById('statusFilter');
- const tagFilterEl = document.getElementById('tagFilter');
- const vendorFilterEl = document.getElementById('vendorFilter');
- const warrantyTypeFilterEl = document.getElementById('warrantyTypeFilter');
- const sortByEl = document.getElementById('sortBy');
- if (statusFilterEl && currentFilters.status) statusFilterEl.value = currentFilters.status;
- if (tagFilterEl && currentFilters.tag) tagFilterEl.value = currentFilters.tag;
- if (vendorFilterEl && currentFilters.vendor) vendorFilterEl.value = currentFilters.vendor;
- if (warrantyTypeFilterEl && currentFilters.warranty_type) warrantyTypeFilterEl.value = currentFilters.warranty_type;
- if (sortByEl && currentFilters.sortBy) sortByEl.value = currentFilters.sortBy;
- // Update the filter indicator if available
- if (typeof window.updateFilterIndicator === 'function') {
- window.updateFilterIndicator();
- }
- } else {
- console.log("[runAuthenticatedTasks] Warranties list element not found.");
- }
- } else {
- console.warn("[runAuthenticatedTasks] Auth status became false before loading data. Aborting data load.");
- // Optionally, reset authStateHandled if we want to allow another attempt
- // authStateHandled = false;
- }
-
- // Now that data and preferences are ready, apply view/currency and render via applyFilters
- console.log("[runAuthenticatedTasks] Applying preferences and rendering...");
- loadViewPreference(); // Sets currentView and UI classes/buttons
- updateCurrencySymbols(); // Update symbols
-
- // Apply filters using the loaded data and render the list
- if (document.getElementById('warrantiesList')) {
- applyFilters();
- }
- }
-
- // Listener for the 'authStateReady' event
- window.addEventListener('authStateReady', async function handleAuthEvent(event) {
- console.log('[DEBUG] authStateReady event received in script.js. Detail:', event.detail);
- // Pass the isAuthenticated status from the event detail to runAuthenticatedTasks
- await runAuthenticatedTasks(event.detail && event.detail.isAuthenticated);
- }); // Removed { once: true } to allow re-evaluation if auth state changes
-
- // Proactive check after a brief delay to allow auth.js to initialize
- setTimeout(async () => {
- console.log('[DEBUG] Proactive auth check in script.js (after timeout).');
- if (window.auth) {
- // Pass the current authentication status to runAuthenticatedTasks
- await runAuthenticatedTasks(window.auth.isAuthenticated());
- } else {
- console.log('[DEBUG] Proactive check: window.auth not available. Event listener should handle it.');
- // Call with false if auth module isn't ready, to avoid tasks running prematurely.
- await runAuthenticatedTasks(false);
- }
- }, 500); // Delay
- // --- END LOAD WARRANTIES AFTER AUTH ---
-
- // updateCurrencySymbols(); // Call removed, rely on loadWarranties triggering render with correct symbol
-});
-
-// Initialize theme based on user preference or system preference
-function initializeTheme() {
- // Only use the global darkMode key for theme persistence
- const savedTheme = localStorage.getItem('darkMode');
- if (savedTheme !== null) {
- setTheme(savedTheme === 'true');
- } else {
- setTheme(window.matchMedia('(prefers-color-scheme: dark)').matches);
- }
-}
-
-// Variables
-let currentView = 'grid'; // Default view
-let expiringSoonDays = 30; // Default value, will be updated from user preferences
-
-// API URL
-const API_URL = '/api/warranties';
-async function toggleArchiveStatus(warrantyId, shouldArchive) {
- try {
- const token = window.auth.getToken();
- if (!token) throw new Error('No auth token');
- const response = await fetch(`/api/warranties/${warrantyId}/archive`, {
- method: 'PATCH',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({ archived: !!shouldArchive })
- });
- if (!response.ok) {
- const err = await response.json().catch(() => ({}));
- throw new Error(err.error || `HTTP ${response.status}`);
- }
- // Reload appropriate list
- // Always reload current view to ensure accurate list source
- await loadWarranties(true);
- showToast(shouldArchive ? (window.t ? window.t('messages.archived_success') : 'Archived') : (window.t ? window.t('messages.unarchived_success') : 'Unarchived'), 'success');
- } catch (e) {
- console.error('Failed to toggle archive status', e);
- showToast(window.t ? window.t('messages.error_updating_archive_status') : 'Failed to update archive status', 'error');
- }
-}
-
-// Utility function to escape HTML
-function escapeHtml(text) {
- if (typeof text !== 'string') return text;
- const map = {
- '&': '&amp;',
- '<': '&lt;',
- '>': '&gt;',
- '"': '&quot;',
- "'": '&#039;'
- };
- return text.replace(/[&<>"']/g, function(m) { return map[m]; });
-}
-
-// Form tab navigation variables (simplified)
-let formTabs = []; // Changed from const to let, initialized as empty
-// Removed const formTabsElements = document.querySelectorAll('.form-tab');
-// Removed const formTabs = formTabsElements ? Array.from(formTabsElements) : [];
-// Removed const tabContentsElements = document.querySelectorAll('.tab-content');
-// Removed tabContents assignment here
-
-// const nextButton = document.querySelector('.next-tab'); // Keep these if needed globally, otherwise might remove
-// const prevButton = document.querySelector('.prev-tab'); // Keep these if needed globally, otherwise might remove
-
-// --- Add near other DOM Element declarations ---
- // ... existing code ...
- // Add save button handler for notes modal (if not already present)
- const saveNotesBtn = document.getElementById('saveNotesBtn');
- if (saveNotesBtn) {
- saveNotesBtn.onclick = async function() {
- // Get the warranty ID being edited
- const warrantyId = notesModalWarrantyId;
- const notesValue = document.getElementById('notesModalTextarea').value;
- if (!warrantyId || !notesModalWarrantyObj) return;
- // Get auth token
- const token = localStorage.getItem('auth_token');
- if (!token) {
- showToast(window.t('messages.authentication_required'), 'error');
- return;
- }
- showLoadingSpinner();
- try {
- // Use FormData and send all required fields, just like the edit modal
- const formData = new FormData();
- formData.append('product_name', notesModalWarrantyObj.product_name);
- formData.append('purchase_date', (notesModalWarrantyObj.purchase_date || '').split('T')[0]);
- formData.append('is_lifetime', notesModalWarrantyObj.is_lifetime ? 'true' : 'false');
- if (!notesModalWarrantyObj.is_lifetime) {
- // Append duration components instead of warranty_years
- formData.append('warranty_duration_years', notesModalWarrantyObj.warranty_duration_years || 0);
- formData.append('warranty_duration_months', notesModalWarrantyObj.warranty_duration_months || 0);
- formData.append('warranty_duration_days', notesModalWarrantyObj.warranty_duration_days || 0);
-
- // If all duration fields are 0 but we have an expiration date, this was created with exact date method
- const isExactDateWarranty = (notesModalWarrantyObj.warranty_duration_years || 0) === 0 &&
- (notesModalWarrantyObj.warranty_duration_months || 0) === 0 &&
- (notesModalWarrantyObj.warranty_duration_days || 0) === 0 &&
- notesModalWarrantyObj.expiration_date;
-
- if (isExactDateWarranty) {
- // For exact date warranties, send the expiration date as exact_expiration_date
- formData.append('exact_expiration_date', notesModalWarrantyObj.expiration_date.split('T')[0]);
- }
- }
- if (notesModalWarrantyObj.product_url) {
- formData.append('product_url', notesModalWarrantyObj.product_url);
- }
- if (notesModalWarrantyObj.purchase_price !== null && notesModalWarrantyObj.purchase_price !== undefined) {
- formData.append('purchase_price', notesModalWarrantyObj.purchase_price);
- }
- if (notesModalWarrantyObj.vendor) {
- formData.append('vendor', notesModalWarrantyObj.vendor);
- }
- if (notesModalWarrantyObj.warranty_type) {
- formData.append('warranty_type', notesModalWarrantyObj.warranty_type);
- }
- if (typeof notesModalWarrantyObj.model_number !== 'undefined' && notesModalWarrantyObj.model_number !== null) {
- formData.append('model_number', notesModalWarrantyObj.model_number);
- }
- if (notesModalWarrantyObj.serial_numbers && Array.isArray(notesModalWarrantyObj.serial_numbers)) {
- notesModalWarrantyObj.serial_numbers.forEach(sn => {
- if (sn && sn.trim() !== '') {
- formData.append('serial_numbers[]', sn); // Use [] for arrays
- }
- });
- } else if (!formData.has('serial_numbers[]')) {
- // Send empty array if none exist
- // formData.append('serial_numbers[]', ''); // Sending empty string might not work as expected, better to not send if empty
- }
- if (notesModalWarrantyObj.tags && Array.isArray(notesModalWarrantyObj.tags)) {
- const tagIds = notesModalWarrantyObj.tags.map(tag => tag.id);
- formData.append('tag_ids', JSON.stringify(tagIds));
- } else {
- formData.append('tag_ids', JSON.stringify([]));
- }
- formData.append('notes', notesValue);
- // Also include model number value from edit input if present on DOM
- const editModelNumberInput = document.getElementById('editModelNumber');
- if (editModelNumberInput && editModelNumberInput.value.trim() !== '') {
- formData.set('model_number', editModelNumberInput.value.trim());
- }
- const response = await fetch(`/api/warranties/${warrantyId}`, {
- method: 'PUT',
- headers: {
- 'Authorization': 'Bearer ' + token
- },
- body: formData
- });
- if (!response.ok) {
- const data = await response.json();
- throw new Error(data.error || 'Failed to update notes');
- }
- hideLoadingSpinner();
- showToast(window.t('messages.notes_updated_successfully'), 'success');
- // Close the modal
- const notesModal = document.getElementById('notesModal');
- if (notesModal) notesModal.style.display = 'none';
- // Now reload warranties and re-render UI
- await loadWarranties();
- applyFilters();
- } catch (error) {
- hideLoadingSpinner();
- console.error('Error updating notes:', error);
- showToast(error.message || window.t('messages.failed_to_update_notes'), 'error');
- }
- };
- }
-
-// Initialize form tabs
-function initFormTabs() {
- console.log('Initializing form tabs...');
- // Use the modal context if available, otherwise query document
- const modalContext = document.getElementById('addWarrantyModal'); // Assuming this is the context
- const context = modalContext && modalContext.classList.contains('active') ? modalContext : document;
-
- const tabsContainer = context.querySelector('.form-tabs');
- // Re-query tabContents and formTabs within the correct context and update global variables
- const contentsElements = context.querySelectorAll('.tab-content');
- tabContents = contentsElements ? Array.from(contentsElements) : []; // Update global variable
-
- const tabsElements = tabsContainer ? tabsContainer.querySelectorAll('.form-tab') : [];
- formTabs = tabsElements ? Array.from(tabsElements) : []; // Update global variable
-
- const nextButton = context.querySelector('#nextTabBtn'); // Use context
- const prevButton = context.querySelector('#prevTabBtn'); // Use context
- const submitButton = context.querySelector('#submitWarrantyBtn'); // Use context
-
- // Use the updated global variables length for checks
- if (!tabsContainer || !tabContents.length || !formTabs.length || !nextButton || !prevButton || !submitButton) {
- console.warn('Form tab elements not found in the expected context. Skipping tab initialization.');
- return; // Don't proceed if elements aren't present
- }
-
- // Remove the local 'tabs' and 'contents' variables, use global ones now
- // let currentTabIndex = 0; // Already global
- // const tabs = tabsContainer.querySelectorAll('.form-tab'); // Use global formTabs
- // const contents = document.querySelectorAll('.tab-content'); // Use global tabContents
-
- // Remove the inner switchToTab and updateNavigationButtons functions as they are defined globally
- /*
- function switchToTab(index) {
- // ... removed inner function ...
- }
-
- function updateNavigationButtons() {
- // ... removed inner function ...
- }
- */
-
- // --- CLONE AND REPLACE NAV BUTTONS TO REMOVE OLD LISTENERS ---
- // Ensure buttons exist before cloning
- let nextButtonCloned = nextButton;
- let prevButtonCloned = prevButton;
- if (nextButton && prevButton) {
- nextButtonCloned = nextButton.cloneNode(true);
- prevButtonCloned = prevButton.cloneNode(true);
- nextButton.parentNode.replaceChild(nextButtonCloned, nextButton);
- prevButton.parentNode.replaceChild(prevButtonCloned, prevButton);
- } else {
- console.warn("Next/Prev buttons not found for cloning listeners.");
- }
-
-
- // ... (rest of initFormTabs, including event listeners, ensure element checks)
- // Make sure event listeners use the correct global functions and variables
- formTabs.forEach((tab, index) => { // Use global formTabs
- if (tab) { // Check if tab exists
- tab.addEventListener('click', () => {
- // Allow clicking only on previous tabs if valid, or current
- if (index < currentTabIndex) {
- let canSwitch = true;
- for (let i = 0; i < index; i++) {
- // Ensure validateTab uses the correct global tabContents
- if (!validateTab(i)) {
- canSwitch = false;
- break;
- }
- }
- if (canSwitch) switchToTab(index); // Call global function
- } else if (index === currentTabIndex) {
- // Clicking current tab does nothing
- } else {
- // Try to navigate forward by clicking tab
- // Ensure validateTab uses the correct global tabContents
- if (validateTab(currentTabIndex)) {
- // Mark current as completed
- if(formTabs[currentTabIndex]) formTabs[currentTabIndex].classList.add('completed'); // Use global formTabs
- switchToTab(index); // Call global function
- } else {
- // If current tab is invalid, show errors for it
- showValidationErrors(currentTabIndex);
- }
- }
- });
- }
- });
-
- if (nextButtonCloned) { // Check button exists
- nextButtonCloned.addEventListener('click', () => {
- // Ensure validateTab uses the correct global tabContents
- if (validateTab(currentTabIndex)) {
- if (formTabs[currentTabIndex]) formTabs[currentTabIndex].classList.add('completed'); // Use global formTabs
- // Use global formTabs length
- if (currentTabIndex < formTabs.length - 1) { // <-- Ensure this uses formTabs.length
- switchToTab(currentTabIndex + 1); // Call global function
- }
- } else {
- // If current tab is invalid, show errors
- showValidationErrors(currentTabIndex);
- }
- });
- } else {
- console.warn("Cloned Next button not found, listener not added.");
- }
-
- if (prevButtonCloned) { // Check button exists
- prevButtonCloned.addEventListener('click', () => {
- if (currentTabIndex > 0) {
- switchToTab(currentTabIndex - 1);
- }
- });
- }
-
- // Initialize the first tab
- switchToTab(0);
-}
-
-// Switch to a specific tab
-function switchToTab(index) {
- console.log(`Switching to tab ${index} from tab ${currentTabIndex}`);
-
- // Ensure index is within bounds
- if (index < 0 || index >= formTabs.length) {
- console.log(`Invalid tab index: ${index}, not switching`);
- return;
- }
-
- // Update summary FIRST if switching TO the summary tab
- if (index === formTabs.length - 1) {
- updateSummary();
- }
-
- // Update active tab
- formTabs.forEach(tab => tab.classList.remove('active'));
- tabContents.forEach(content => content.classList.remove('active'));
-
- formTabs[index].classList.add('active');
- tabContents[index].classList.add('active');
-
- // Update current tab index
- currentTabIndex = index;
-
- // Update progress indicator
- document.querySelector('.form-tabs').setAttribute('data-step', currentTabIndex);
-
- // Update completed tabs
- updateCompletedTabs();
-
- // Update navigation buttons
- updateNavigationButtons();
-}
-
-// Update navigation buttons based on current tab
-function updateNavigationButtons() {
- const prevButton = document.querySelector('.prev-tab');
- const nextButton = document.querySelector('.next-tab');
- const submitButton = document.querySelector('button[type="submit"]');
-
- // Hide/show previous button
- prevButton.style.display = currentTabIndex === 0 ? 'none' : 'block';
-
- // Hide/show next button and submit button
- if (currentTabIndex === formTabs.length - 1) {
- nextButton.style.display = 'none';
- submitButton.style.display = 'block';
- } else {
- nextButton.style.display = 'block';
- submitButton.style.display = 'none';
- }
-}
-
-// Update completed tabs
-function updateCompletedTabs() {
- formTabs.forEach((tab, index) => {
- if (index < currentTabIndex) {
- tab.classList.add('completed');
- } else {
- tab.classList.remove('completed');
- }
- });
-}
-
-// Validate a specific tab
-function validateTab(tabIndex) {
- const tabContent = tabContents[tabIndex];
- const controls = tabContent.querySelectorAll('input, textarea, select');
- let isTabValid = true;
-
- controls.forEach(control => {
- // Clear previous validation state
- control.classList.remove('invalid');
- let validationMessageElement = control.nextElementSibling;
- if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {
- validationMessageElement.remove();
- }
-
- // Manual validation for required fields
- if (control.hasAttribute('required') && control.value.trim() === '') {
- isTabValid = false;
- control.classList.add('invalid');
- // Mark as invalid, message will be added by showValidationErrors
- } else if (!control.validity.valid) { // For other HTML5 validation issues (e.g., type mismatch)
- isTabValid = false;
- control.classList.add('invalid');
- }
- });
- return isTabValid;
-}
-
-// Show validation errors for a specific tab
-function showValidationErrors(tabIndex) {
- const tabContent = tabContents[tabIndex];
- const controls = tabContent.querySelectorAll('input, textarea, select');
- let firstInvalidControl = null;
- let validationToast = document.querySelector('.validation-toast'); // Check for existing validation toast
-
- controls.forEach(control => {
- if (!control.validity.valid) {
- if (!firstInvalidControl) firstInvalidControl = control;
- control.classList.add('invalid');
-
- // Add or update validation message
- let validationMessageElement = control.nextElementSibling;
- if (!validationMessageElement || !validationMessageElement.classList.contains('validation-message')) {
- validationMessageElement = document.createElement('div');
- validationMessageElement.className = 'validation-message';
- control.parentNode.insertBefore(validationMessageElement, control.nextSibling);
- }
- if (control.hasAttribute('required') && control.value.trim() === '') {
- validationMessageElement.textContent = window.i18next ? window.i18next.t('messages.please_fill_out_this_field') : 'Please fill out this field.';
- } else {
- validationMessageElement.textContent = control.validationMessage || (window.i18next ? window.i18next.t('messages.field_is_invalid') : 'This field is invalid.');
- }
- } else {
- // Ensure invalid class is removed if somehow missed by validateTab (shouldn't happen)
- control.classList.remove('invalid');
- // Remove validation message if control is now valid
- let validationMessageElement = control.nextElementSibling;
- if (validationMessageElement && validationMessageElement.classList.contains('validation-message')) {
- validationMessageElement.remove();
- }
- }
- });
-
- // The browser will attempt to focus the first invalid field when form submission is prevented.
- // Switching to the tab containing the error (done by handleFormSubmit) is key.
-
- // Manage a single validation toast
- if (!validationToast) {
- validationToast = showToast(window.t('messages.correct_errors_in_tab'), 'error', 0); // 0 duration = persistent
- validationToast.classList.add('validation-toast'); // Add a class to identify it
- } else {
- // Update existing toast message if needed (optional)
- validationToast.querySelector('span').textContent = window.t('messages.correct_errors_in_tab');
- }
-}
-
-// Update summary tab with current form values
-function updateSummary() {
- // Product information
- const summaryProductName = document.getElementById('summary-product-name');
- if (summaryProductName) {
- summaryProductName.textContent =
- document.getElementById('productName')?.value || '-';
- }
-
- const summaryProductUrl = document.getElementById('summary-product-url');
- if (summaryProductUrl) {
- summaryProductUrl.textContent =
- document.getElementById('productUrl')?.value || '-';
- }
-
- // Serial numbers
- const serialNumbers = [];
- document.querySelectorAll('input[name="serial_numbers[]"]').forEach(input => {
- if (input && input.value && input.value.trim()) {
- serialNumbers.push(input.value.trim());
- }
- });
-
- const serialNumbersContainer = document.getElementById('summary-serial-numbers');
- if (serialNumbersContainer) {
- if (serialNumbers.length > 0) {
- serialNumbersContainer.innerHTML = '<ul>' +
- serialNumbers.map(sn => `<li>${sn}</li>`).join('') +
- '</ul>';
- } else {
- serialNumbersContainer.textContent = 'None';
- }
- }
-
- // Warranty details
- const purchaseDateStr = document.getElementById('purchaseDate')?.value;
- const summaryPurchaseDate = document.getElementById('summary-purchase-date');
- if (summaryPurchaseDate) {
- if (purchaseDateStr) {
- // Use the same logic as formatDate to handle YYYY-MM-DD
- const parts = String(purchaseDateStr).split('-');
- let formattedDate = '-'; // Default
- if (parts.length === 3) {
- const year = parseInt(parts[0], 10);
- const month = parseInt(parts[1], 10) - 1; // JS months are 0-indexed
- const day = parseInt(parts[2], 10);
- const dateObj = new Date(Date.UTC(year, month, day));
- if (!isNaN(dateObj.getTime())) {
- // Format manually (example: Jan 1, 2023)
- const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
- formattedDate = `${monthNames[month]} ${day}, ${year}`;
- }
- }
- summaryPurchaseDate.textContent = formattedDate;
- } else {
- summaryPurchaseDate.textContent = '-';
- }
- }
-
- // --- Handle Lifetime in Summary ---
- const isLifetime = isLifetimeCheckbox ? isLifetimeCheckbox.checked : false;
- const summaryWarrantyDuration = document.getElementById('summary-warranty-duration'); // Use new ID
-
- if (summaryWarrantyDuration) {
- if (isLifetime) {
- summaryWarrantyDuration.textContent = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';
- } else {
- const years = parseInt(warrantyDurationYearsInput?.value || 0);
- const months = parseInt(warrantyDurationMonthsInput?.value || 0);
- const days = parseInt(warrantyDurationDaysInput?.value || 0);
-
- let durationParts = [];
- if (years > 0) {
- const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;
- durationParts.push(`${years} ${yearText}`);
- }
- if (months > 0) {
- const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;
- durationParts.push(`${months} ${monthText}`);
- }
- if (days > 0) {
- const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;
- durationParts.push(`${days} ${dayText}`);
- }
-
- summaryWarrantyDuration.textContent = durationParts.length > 0 ? durationParts.join(', ') : '-';
- }
- }
-
- // Warranty type - handle dropdown and custom input
- const warrantyTypeSelect = document.getElementById('warrantyType');
- const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');
- const summaryWarrantyType = document.getElementById('summary-warranty-type');
- if (summaryWarrantyType) {
- let warrantyTypeText = 'Not specified';
- if (warrantyTypeSelect && warrantyTypeSelect.value) {
- if (warrantyTypeSelect.value === 'other' && warrantyTypeCustom && warrantyTypeCustom.value.trim()) {
- warrantyTypeText = warrantyTypeCustom.value.trim();
- } else if (warrantyTypeSelect.value !== 'other') {
- warrantyTypeText = warrantyTypeSelect.value;
- }
- }
- summaryWarrantyType.textContent = warrantyTypeText;
- }
-
- // Purchase price
- const purchasePrice = document.getElementById('purchasePrice')?.value;
- const currency = document.getElementById('currency')?.value;
- const summaryPurchasePrice = document.getElementById('summary-purchase-price');
- if (summaryPurchasePrice) {
- if (purchasePrice) {
- const symbol = getCurrencySymbol();
- const position = getCurrencyPosition();
- const amount = parseFloat(purchasePrice).toFixed(2);
- summaryPurchasePrice.innerHTML = formatCurrencyHTML(amount, symbol, position);
- } else {
- summaryPurchasePrice.textContent = 'Not specified';
- }
- }
-
- // Documents
- const productPhotoFile = document.getElementById('productPhoto')?.files[0];
- const summaryProductPhoto = document.getElementById('summary-product-photo');
- if (summaryProductPhoto) {
- summaryProductPhoto.textContent = productPhotoFile ?
- productPhotoFile.name : 'No photo selected';
- }
-
- const invoiceFile = document.getElementById('invoice')?.files[0];
- const invoiceUrlField = document.getElementById('invoiceUrl');
- const invoiceUrl = invoiceUrlField ? invoiceUrlField.value : '';
- const summaryInvoice = document.getElementById('summary-invoice');
- if (summaryInvoice) {
- if (invoiceFile) {
- summaryInvoice.textContent = invoiceFile.name;
- } else if (invoiceUrl) {
- summaryInvoice.textContent = 'URL: ' + invoiceUrl;
- } else {
- summaryInvoice.textContent = 'Not specified';
- }
- }
-
- const manualFile = document.getElementById('manual')?.files[0];
- const manualUrlField = document.getElementById('manualUrl');
- const manualUrl = manualUrlField ? manualUrlField.value : '';
- const summaryManual = document.getElementById('summary-manual');
- if (summaryManual) {
- if (manualFile) {
- summaryManual.textContent = manualFile.name;
- } else if (manualUrl) {
- summaryManual.textContent = 'URL: ' + manualUrl;
- } else {
- summaryManual.textContent = 'Not specified';
- }
- }
-
- const otherDocumentFile = document.getElementById('otherDocument')?.files[0];
- const otherDocumentUrlField = document.getElementById('otherDocumentUrl');
- const otherDocumentUrl = otherDocumentUrlField ? otherDocumentUrlField.value : '';
- const summaryOtherDocument = document.getElementById('summary-other-document');
- if (summaryOtherDocument) {
- if (otherDocumentFile) {
- summaryOtherDocument.textContent = otherDocumentFile.name;
- } else if (otherDocumentUrl) {
- summaryOtherDocument.textContent = 'URL: ' + otherDocumentUrl;
- } else {
- summaryOtherDocument.textContent = 'Not specified';
- }
- }
-
- // Tags
- const summaryTags = document.getElementById('summary-tags');
- if (summaryTags) {
- if (selectedTags && selectedTags.length > 0) {
- summaryTags.innerHTML = '';
-
- selectedTags.forEach(tag => {
- const tagElement = document.createElement('span');
- tagElement.className = 'tag';
- tagElement.style.backgroundColor = tag.color;
- tagElement.style.color = getContrastColor(tag.color);
- tagElement.textContent = tag.name;
-
- summaryTags.appendChild(tagElement);
- });
- } else {
- summaryTags.textContent = 'No tags selected';
- }
- }
-
- // Vendor/Retailer
- const vendor = document.getElementById('vendor');
- document.getElementById('summary-vendor').textContent = vendor && vendor.value ? vendor.value : '-';
-}
-
-// Add input event listeners to remove validation errors when user types
-document.addEventListener('input', (e) => {
- if (e.target.hasAttribute('required') && e.target.classList.contains('invalid')) {
- if (e.target.value.trim()) {
- e.target.classList.remove('invalid');
-
- // Remove validation message if exists
- const validationMessage = e.target.nextElementSibling;
- if (validationMessage && validationMessage.classList.contains('validation-message')) {
- validationMessage.remove();
- }
- }
- }
-});
-
-// Function to reset the form and initialize serial number inputs
-function resetForm() {
- // Reset the form
- warrantyForm.reset();
-
- // Reset serial numbers container
- serialNumbersContainer.innerHTML = '';
-
- // Add the first serial number input
- addSerialNumberInput();
-
- // Reset form tabs
- currentTabIndex = 0;
- switchToTab(0);
-
- // Clear any file input displays
- const productPhotoFileName = document.getElementById('productPhotoFileName');
- if (productPhotoFileName) productPhotoFileName.textContent = '';
- fileName.textContent = '';
- manualFileName.textContent = '';
- if (otherDocumentFileName) otherDocumentFileName.textContent = '';
-
- // Reset photo preview
- const productPhotoPreview = document.getElementById('productPhotoPreview');
- if (productPhotoPreview) {
- productPhotoPreview.style.display = 'none';
- }
-}
-
-async function exportWarranties() {
- console.log('[EXPORT DEBUG] Starting export process');
- console.log('[EXPORT DEBUG] Total warranties in memory:', warranties.length);
- console.log('[EXPORT DEBUG] Current filters:', currentFilters);
-
- // Get filtered warranties
- let warrantiesToExport = [...warranties];
- console.log('[EXPORT DEBUG] Initial warranties to export:', warrantiesToExport.length);
-
- // Apply current filters
- if (currentFilters.search) {
- const searchTerm = currentFilters.search.toLowerCase();
- console.log('[EXPORT DEBUG] Applying search filter:', searchTerm);
- warrantiesToExport = warrantiesToExport.filter(warranty => {
- // Check if product name contains search term
- const productNameMatch = warranty.product_name.toLowerCase().includes(searchTerm);
-
- // Check if any tag name contains search term
- const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&
- warranty.tags.some(tag => tag.name.toLowerCase().includes(searchTerm));
-
- // Check if vendor name contains search term
- const vendorMatch = warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm);
-
- // Return true if either product name, tag name, or vendor name matches
- return productNameMatch || tagMatch || vendorMatch;
- });
- console.log('[EXPORT DEBUG] After search filter:', warrantiesToExport.length);
- }
-
- if (currentFilters.status !== 'all') {
- console.log('[EXPORT DEBUG] Applying status filter:', currentFilters.status);
- warrantiesToExport = warrantiesToExport.filter(warranty =>
- warranty.status === currentFilters.status
- );
- console.log('[EXPORT DEBUG] After status filter:', warrantiesToExport.length);
- }
-
- // Apply tag filter
- if (currentFilters.tag !== 'all') {
- const tagId = parseInt(currentFilters.tag);
- console.log('[EXPORT DEBUG] Applying tag filter:', tagId);
- warrantiesToExport = warrantiesToExport.filter(warranty =>
- warranty.tags && Array.isArray(warranty.tags) &&
- warranty.tags.some(tag => tag.id === tagId)
- );
- console.log('[EXPORT DEBUG] After tag filter:', warrantiesToExport.length);
- }
-
- // Apply vendor filter
- if (currentFilters.vendor !== 'all') {
- console.log('[EXPORT DEBUG] Applying vendor filter:', currentFilters.vendor);
- warrantiesToExport = warrantiesToExport.filter(warranty =>
- (warranty.vendor || '').toLowerCase() === currentFilters.vendor.toLowerCase()
- );
- console.log('[EXPORT DEBUG] After vendor filter:', warrantiesToExport.length);
- }
-
- // Apply warranty type filter
- if (currentFilters.warranty_type !== 'all') {
- console.log('[EXPORT DEBUG] Applying warranty type filter:', currentFilters.warranty_type);
- warrantiesToExport = warrantiesToExport.filter(warranty =>
- (warranty.warranty_type || '').toLowerCase() === currentFilters.warranty_type.toLowerCase()
- );
- console.log('[EXPORT DEBUG] After warranty type filter:', warrantiesToExport.length);
- }
-
- console.log('[EXPORT DEBUG] Final warranties to export:', warrantiesToExport.length);
- console.log('[EXPORT DEBUG] Warranty IDs being exported:', warrantiesToExport.map(w => w.id));
-
- // Create CSV content
- let csvContent = "data:text/csv;charset=utf-8,";
-
- // Add headers - Updated for duration components
- csvContent += "ProductName,PurchaseDate,IsLifetime,WarrantyDurationYears,WarrantyDurationMonths,WarrantyDurationDays,ExpirationDate,Status,PurchasePrice,SerialNumber,ProductURL,Tags,Vendor\n";
-
- // Add data rows
- warrantiesToExport.forEach(warranty => {
- // Format serial numbers as comma-separated string
- const serialNumbers = Array.isArray(warranty.serial_numbers)
- ? warranty.serial_numbers.filter(s => s).join(', ')
- : '';
-
- // Format tags as comma-separated string
- const tags = Array.isArray(warranty.tags)
- ? warranty.tags.map(tag => tag.name).join(', ')
- : '';
-
- // Format row data - Updated for duration components
- const row = [
- warranty.product_name || '',
- formatDateYYYYMMDD(new Date(warranty.purchase_date)),
- warranty.is_lifetime ? 'TRUE' : 'FALSE',
- warranty.warranty_duration_years || 0,
- warranty.warranty_duration_months || 0,
- warranty.warranty_duration_days || 0,
- warranty.is_lifetime ? '' : formatDateYYYYMMDD(new Date(warranty.expiration_date)), // Expiration date empty for lifetime
- warranty.status || '',
- warranty.purchase_price || '',
- serialNumbers,
- warranty.product_url || '',
- tags,
- warranty.vendor || ''
- ];
-
- // Add row to CSV content
- csvContent += row.map(field => `"${field.toString().replace(/"/g, '""')}"`).join(',') + '\n';
- });
-
- // Create a download link
- const encodedUri = encodeURI(csvContent);
- const link = document.createElement('a');
- link.setAttribute('href', encodedUri);
- link.setAttribute('download', `warranties_export_${formatDate(new Date())}.csv`);
- document.body.appendChild(link);
-
- // Trigger download
- link.click();
-
- // Clean up
- document.body.removeChild(link);
-
- // Show success notification
- showToast(window.t('messages.exported_warranties_successfully', {count: warrantiesToExport.length}), 'success');
-}
-
-// Switch view of warranties list
-async function switchView(viewType, saveToApi = true) { // Added saveToApi parameter with default true
- console.log(`Switching to view: ${viewType}`);
- currentView = viewType;
-
- const prefix = getPreferenceKeyPrefix();
- const viewKey = `${prefix}defaultView`;
- const currentStoredValue = localStorage.getItem(viewKey);
-
- // Save to localStorage immediately for responsiveness
- if (currentStoredValue !== viewType) {
- localStorage.setItem(viewKey, viewType);
- // Keep legacy keys for now if needed, but primary is viewKey
- localStorage.setItem(`${prefix}warrantyView`, viewType);
- localStorage.setItem('viewPreference', viewType);
- console.log(`Saved view preference (${viewKey}) to localStorage: ${viewType}`);
- } else {
- console.log(`View preference (${viewKey}) already set to ${viewType} in localStorage.`);
- }
-
- // --- MODIFIED: Only save preference to API if saveToApi is true ---
- if (saveToApi && window.auth && window.auth.isAuthenticated()) {
- const token = window.auth.getToken();
- if (token) {
- try {
- console.log(`Attempting to save view preference (${viewType}) to API...`);
- const response = await fetch('/api/auth/preferences', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({ default_view: viewType }) // Send only the changed preference
- });
-
- if (response.ok) {
- console.log('Successfully saved view preference to API.');
- } else {
- const errorData = await response.json().catch(() => ({}));
- console.warn(`Failed to save view preference to API: ${response.status}`, errorData.message || '');
- // Optional: Show a non-intrusive warning toast?
- // showToast('Failed to sync view preference with server.', 'warning');
- }
- } catch (error) {
- console.error('Error saving view preference to API:', error);
- // Optional: Show a non-intrusive warning toast?
- // showToast('Error syncing view preference with server.', 'error');
- }
- } else {
- console.warn('Cannot save view preference to API: No auth token found.');
- }
- } else if (!saveToApi) {
- console.log('Skipping API save as saveToApi is false (likely called from loadViewPreference).');
- } else {
- console.warn('Cannot save view preference to API: User not authenticated or auth module not loaded.');
- }
- // --- END MODIFIED: Save preference to API ---
-
- // Make sure warrantiesList exists before modifying classes
- if (warrantiesList) {
- warrantiesList.classList.remove('grid-view', 'list-view', 'table-view');
- warrantiesList.classList.add(`${viewType}-view`);
- }
-
- // Make sure view buttons exist
- if (gridViewBtn && listViewBtn && tableViewBtn) {
- gridViewBtn.classList.remove('active');
- listViewBtn.classList.remove('active');
- tableViewBtn.classList.remove('active');
- // Add active class to the correct button
- if (viewType === 'grid') gridViewBtn.classList.add('active');
- if (viewType === 'list') listViewBtn.classList.add('active');
- if (viewType === 'table') tableViewBtn.classList.add('active');
- }
-
- // Show/hide table header only if it exists
- if (tableViewHeader) {
- tableViewHeader.classList.toggle('visible', viewType === 'table');
- }
-
- // Re-apply current filters after view change to preserve user's selection
- try {
- // Persist current filters before render (defensive no-op if unchanged)
- // Skip API save on initial load to mirror view settings behavior
- saveFilterPreferences(false);
- } catch (_) {}
-
- if (warrantiesList && warrantiesLoaded) {
- // Reapply full filter set (status, tag, vendor, type, search, sort)
- applyFilters();
- }
-
- // Update header dropdown label if present
- try {
- const currentViewIcon = document.getElementById('currentViewIcon');
- if (currentViewIcon) {
- currentViewIcon.className = 'fas';
- if (viewType === 'list') {
- currentViewIcon.classList.add('fa-list');
- currentViewIcon.setAttribute('aria-label', 'List');
- } else if (viewType === 'table') {
- currentViewIcon.classList.add('fa-table');
- currentViewIcon.setAttribute('aria-label', 'Table');
- } else {
- currentViewIcon.classList.add('fa-th-large');
- currentViewIcon.setAttribute('aria-label', 'Grid');
- }
- }
- } catch (e) { /* no-op */ }
-}
-
-// Load view preference from localStorage
-function loadViewPreference() {
- // Get the appropriate key prefix based on user type
- const prefix = getPreferenceKeyPrefix();
- let savedView = null;
-
- // --- BEGIN EDIT: Check keys in priority order ---
- const userSpecificView = localStorage.getItem(`${prefix}defaultView`);
- const generalView = localStorage.getItem('viewPreference');
- const legacyWarrantyView = localStorage.getItem(`${prefix}warrantyView`);
-
- if (userSpecificView) {
- savedView = userSpecificView;
- console.log(`Loaded view preference from ${prefix}defaultView:`, savedView);
- } else if (generalView) {
- savedView = generalView;
- console.log('Loaded view preference from viewPreference:', savedView);
- } else if (legacyWarrantyView) {
- savedView = legacyWarrantyView;
- console.log(`Loaded view preference from legacy ${prefix}warrantyView:`, savedView);
- }
- // --- END EDIT ---
-
- // Default to grid view if no preference is saved
- savedView = savedView || 'grid';
-
- console.log(`Applying view preference from loadViewPreference: ${savedView}`);
- // Switch view only if view buttons exist (implying it's the main page)
- if (gridViewBtn || listViewBtn || tableViewBtn) {
- switchView(savedView, false); // Pass false to prevent API save on initial load
- }
-}
-
-// Dark mode toggle
-if (darkModeToggle) { // Add check for darkModeToggle
- darkModeToggle.addEventListener('change', (e) => {
- saveThemePreference(e.target.checked);
- });
-}
-
-// Add event listener for adding new serial number inputs
-// Add check for serialNumbersContainer before adding listener
-if (serialNumbersContainer) {
- serialNumbersContainer.addEventListener('click', (e) => {
- if (e.target.closest('.add-serial-number')) {
- addSerialNumberInput();
- }
- });
-}
-
-// Add a serial number input field
-function addSerialNumberInput(container = serialNumbersContainer) {
- // Check if the container exists before proceeding
- if (!container) {
- console.warn('Serial numbers container not found, cannot add input.');
- return;
- }
-
- const div = document.createElement('div');
- div.className = 'serial-number-input d-flex mb-2';
-
- // Create an input element
- const input = document.createElement('input');
- input.type = 'text';
- input.className = 'form-control';
- input.name = 'serial_numbers[]';
- input.placeholder = window.i18next ? window.i18next.t('warranties.enter_serial_number') : 'Enter serial number';
- console.log('i18next available for serial number placeholder:', !!window.i18next);
- if (window.i18next) {
- console.log('Translation for warranties.enter_serial_number:', window.i18next.t('warranties.enter_serial_number'));
- }
-
- // Check if this is the first serial number input
- const isFirstInput = container.querySelectorAll('.serial-number-input').length === 0;
-
- // Append input to the input group
- div.appendChild(input);
-
- // Only add remove button if this is not the first input
- if (!isFirstInput) {
- // Create a remove button
- const removeButton = document.createElement('button');
- removeButton.type = 'button';
- removeButton.className = 'btn btn-sm btn-danger remove-serial';
- removeButton.innerHTML = '<i class="fas fa-times"></i>';
-
- // Add event listener to remove button
- removeButton.addEventListener('click', function() {
- container.removeChild(div);
- });
-
- // Append remove button to the input group
- div.appendChild(removeButton);
- }
-
- // Insert the new input group before the add button
- const addButton = container.querySelector('.add-serial');
- if (addButton) {
- container.insertBefore(div, addButton);
- } else {
- container.appendChild(div);
-
- // Create and append an add button if it doesn't exist
- const addButton = document.createElement('button');
- addButton.type = 'button';
- addButton.className = 'btn btn-sm btn-secondary add-serial';
- addButton.innerHTML = '<i class="fas fa-plus"></i> ' + (window.i18next ? window.i18next.t('warranties.add_serial_number') : 'Add Serial Number');
- console.log('i18next available in addSerialNumberInput:', !!window.i18next);
- if (window.i18next) {
- console.log('Translation for warranties.add_serial_number:', window.i18next.t('warranties.add_serial_number'));
- }
-
- addButton.addEventListener('click', function() {
- addSerialNumberInput(container);
- });
-
- container.appendChild(addButton);
- }
-}
-
-// Functions
-function showLoading() {
- let localLoadingContainer = window.loadingContainer || document.getElementById('loadingContainer');
- if (localLoadingContainer) {
- localLoadingContainer.classList.add('active');
- window.loadingContainer = localLoadingContainer; // Update global reference if found
- } else {
- console.error('WarrackerDebug: loadingContainer element not found by showLoading(). Ensure it exists in the HTML and script.js is loaded after it.');
- }
-}
-
-function hideLoading() {
- let localLoadingContainer = window.loadingContainer || document.getElementById('loadingContainer');
- if (localLoadingContainer) {
- localLoadingContainer.classList.remove('active');
- window.loadingContainer = localLoadingContainer; // Update global reference if found
- } else {
- console.error('WarrackerDebug: loadingContainer element not found by hideLoading().');
- }
-}
-
-function showToast(message, type = 'info', duration = 5000) {
- // Check if a toast with the same message and type already exists
- const existingToasts = document.querySelectorAll(`.toast.toast-${type}`);
- for (let i = 0; i < existingToasts.length; i++) {
- const span = existingToasts[i].querySelector('span');
- if (span && span.textContent === message) {
- return existingToasts[i]; // Don't create a new one
- }
- }
-
- const toast = document.createElement('div');
- toast.className = `toast toast-${type}`;
-
- const icon = document.createElement('i');
- switch (type) {
- case 'success':
- icon.className = 'fas fa-check-circle';
- break;
- case 'error':
- icon.className = 'fas fa-exclamation-circle';
- break;
- case 'warning':
- icon.className = 'fas fa-exclamation-triangle';
- break;
- default:
- icon.className = 'fas fa-info-circle';
- }
-
- const messageSpan = document.createElement('span');
- messageSpan.textContent = message;
-
- toast.appendChild(icon);
- toast.appendChild(messageSpan);
-
- toastContainer.appendChild(toast);
-
- // Add a method to remove the toast
- toast.remove = function() {
- toast.classList.add('toast-fade-out');
- setTimeout(() => {
- if (toast.parentNode) {
- toast.parentNode.removeChild(toast);
- }
- }, 300);
- };
-
- // Auto-hide toast after specified duration (if not 0)
- if (duration > 0) {
- setTimeout(() => {
- toast.remove();
- }, duration);
- }
-
- return toast;
-}
-
-// Update file name display when a file is selected
-function updateFileName(event, inputId = 'invoice', outputId = 'fileName') {
- const file = event.target.files[0];
- const output = document.getElementById(outputId);
-
- if (file && output) {
- output.textContent = file.name;
- } else if (output) {
- output.textContent = '';
- }
-
- // Handle photo preview for product photo
- if (inputId === 'productPhoto' || inputId === 'editProductPhoto') {
- const previewId = inputId === 'productPhoto' ? 'productPhotoPreview' : 'editProductPhotoPreview';
- const imgId = inputId === 'productPhoto' ? 'productPhotoImg' : 'editProductPhotoImg';
- const preview = document.getElementById(previewId);
- const img = document.getElementById(imgId);
-
- if (file && file.type.startsWith('image/')) {
- const reader = new FileReader();
- reader.onload = function(e) {
- img.src = e.target.result;
- preview.style.display = 'block';
- };
- reader.readAsDataURL(file);
- } else {
- preview.style.display = 'none';
- }
- }
-}
-
-// Helper function to process warranty data
-function processWarrantyData(warranty) {
- console.log('Processing warranty data:', warranty);
-
- // Create a copy of the warranty object to avoid modifying the original
- const processedWarranty = { ...warranty };
- // Flag archived items when merged into All view
- processedWarranty.is_archived = !!(warranty.__isArchived || warranty.is_archived);
-
- // Ensure product_name exists
- if (!processedWarranty.product_name) {
- processedWarranty.product_name = 'Unnamed Product';
- }
-
- const today = new Date();
- today.setHours(0, 0, 0, 0); // Normalize today to midnight for accurate date comparisons
-
- // Parse purchase_date string (YYYY-MM-DD) into a UTC Date object
- let purchaseDateObj = null;
- if (processedWarranty.purchase_date) {
- const parts = String(processedWarranty.purchase_date).split('-');
- if (parts.length === 3) {
- const year = parseInt(parts[0], 10);
- const month = parseInt(parts[1], 10) - 1; // JS months are 0-indexed
- const day = parseInt(parts[2], 10);
- purchaseDateObj = new Date(Date.UTC(year, month, day));
- if (isNaN(purchaseDateObj.getTime())) {
- purchaseDateObj = null; // Invalid date parsed
- }
- } else {
- // Fallback for unexpected formats, though backend should send YYYY-MM-DD
- purchaseDateObj = new Date(processedWarranty.purchase_date);
- if (isNaN(purchaseDateObj.getTime())) {
- purchaseDateObj = null;
- }
- }
- }
- processedWarranty.purchaseDate = purchaseDateObj;
-
- // Parse expiration_date similarly (assuming it's also YYYY-MM-DD)
- let expirationDateObj = null;
- if (processedWarranty.expiration_date) {
- const parts = String(processedWarranty.expiration_date).split('-');
- if (parts.length === 3) {
- const year = parseInt(parts[0], 10);
- const month = parseInt(parts[1], 10) - 1;
- const day = parseInt(parts[2], 10);
- expirationDateObj = new Date(Date.UTC(year, month, day));
- if (isNaN(expirationDateObj.getTime())) {
- expirationDateObj = null;
- }
- } else {
- expirationDateObj = new Date(processedWarranty.expiration_date);
- if (isNaN(expirationDateObj.getTime())) {
- expirationDateObj = null;
- }
- }
- }
- processedWarranty.expirationDate = expirationDateObj;
-
- // --- Lifetime Handling ---
- if (processedWarranty.is_lifetime) {
- processedWarranty.status = 'active';
- processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';
- processedWarranty.daysRemaining = Infinity;
- // Ensure duration components are 0 for lifetime
- processedWarranty.warranty_duration_years = 0;
- processedWarranty.warranty_duration_months = 0;
- processedWarranty.warranty_duration_days = 0;
- } else if (processedWarranty.expirationDate && !isNaN(processedWarranty.expirationDate.getTime())) {
- // Existing logic for dated warranties
- const expirationDateOnly = new Date(processedWarranty.expirationDate);
- expirationDateOnly.setHours(0,0,0,0);
-
- const timeDiff = expirationDateOnly - today;
- const daysRemaining = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
- processedWarranty.daysRemaining = daysRemaining;
-
- if (daysRemaining < 0) {
- processedWarranty.status = 'expired';
- processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.expired') : 'Expired';
- } else if (daysRemaining < expiringSoonDays) {
- processedWarranty.status = 'expiring';
- const dayText = window.i18next ?
- window.i18next.t('warranties.day', {count: daysRemaining}) :
- `day${daysRemaining !== 1 ? 's' : ''}`;
- processedWarranty.statusText = window.i18next ?
- window.i18next.t('warranties.days_remaining', {days: daysRemaining, dayText: dayText}) :
- `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`;
- } else {
- processedWarranty.status = 'active';
- const dayText = window.i18next ?
- window.i18next.t('warranties.day', {count: daysRemaining}) :
- `day${daysRemaining !== 1 ? 's' : ''}`;
- processedWarranty.statusText = window.i18next ?
- window.i18next.t('warranties.days_remaining', {days: daysRemaining, dayText: dayText}) :
- `${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining`;
- }
-
- // Preserve original duration values to detect input method
- const originalYears = processedWarranty.warranty_duration_years || 0;
- const originalMonths = processedWarranty.warranty_duration_months || 0;
- const originalDays = processedWarranty.warranty_duration_days || 0;
-
- // Track the original input method based on duration values
- const wasExactDateMethod = originalYears === 0 && originalMonths === 0 && originalDays === 0;
- processedWarranty.original_input_method = wasExactDateMethod ? 'exact_date' : 'duration';
-
- // Calculate duration from dates if all duration components are 0 (exact date method was used)
- const hasNoDuration = originalYears === 0 && originalMonths === 0 && originalDays === 0;
-
- if (hasNoDuration && purchaseDateObj && processedWarranty.expirationDate) {
- console.log('[DEBUG] Calculating duration from dates for exact date warranty');
- const calculatedDuration = calculateDurationFromDates(
- purchaseDateObj.toISOString().split('T')[0],
- processedWarranty.expirationDate.toISOString().split('T')[0]
- );
- if (calculatedDuration) {
- // Store calculated duration for display purposes
- processedWarranty.display_duration_years = calculatedDuration.years;
- processedWarranty.display_duration_months = calculatedDuration.months;
- processedWarranty.display_duration_days = calculatedDuration.days;
- console.log('[DEBUG] Calculated duration:', calculatedDuration);
-
- // Keep original values at 0 to preserve input method detection
- processedWarranty.warranty_duration_years = 0;
- processedWarranty.warranty_duration_months = 0;
- processedWarranty.warranty_duration_days = 0;
- }
- } else {
- // Use original duration values for display
- processedWarranty.display_duration_years = originalYears;
- processedWarranty.display_duration_months = originalMonths;
- processedWarranty.display_duration_days = originalDays;
- }
- } else {
- processedWarranty.status = 'unknown';
- processedWarranty.statusText = window.i18next ? window.i18next.t('warranties.unknown_status') : 'Unknown Status';
- processedWarranty.daysRemaining = null;
- }
-
- console.log('Processed warranty data result:', processedWarranty);
- return processedWarranty;
-}
-
-// Function to process all warranties in the array
-function processAllWarranties() {
- console.log('Processing all warranties in array...');
- if (warranties && warranties.length > 0) {
- if (window.store && window.store.setWarranties) {
- window.store.setWarranties(warranties.map(warranty => processWarrantyData(warranty)));
- }
- warranties = (window.store && window.store.getWarranties) ? window.store.getWarranties() : warranties;
- }
- console.log('Processed warranties:', warranties);
-}
-
-async function loadWarranties(isAuthenticated) { // Added isAuthenticated parameter
- // +++ REMOVED: Ensure Preferences are loaded FIRST (Now handled by authStateReady) +++
- // await loadAndApplyUserPreferences();
- // +++ Preferences Loaded +++
-
- try {
- console.log('[DEBUG] Entered loadWarranties, isAuthenticated:', isAuthenticated);
-
- // Reset the flag when starting to load warranties
- warrantiesLoaded = false;
-
- showLoading();
-
- // Fetch user preferences (including date format) before loading warranties
- // --- THIS INNER PREFERENCE FETCH IS NOW REDUNDANT, REMOVE/COMMENT OUT ---
- /*
- try {
- const token = window.auth.getToken(); // Ensure token is retrieved here
- if (!token) throw new Error("No auth token found"); // Added error handling
-
- const prefsResponse = await fetch('/api/auth/preferences', {
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- });
-
- if (prefsResponse.ok) {
- const prefsData = await prefsResponse.json();
- console.log("Preferences fetched in loadWarranties:", prefsData);
-
- // Update expiringSoonDays
- if (prefsData && typeof prefsData.expiring_soon_days !== 'undefined') {
- const oldValue = expiringSoonDays;
- expiringSoonDays = prefsData.expiring_soon_days;
- console.log('Updated expiring soon days from preferences:', expiringSoonDays);
- // Reprocess logic moved below warranty fetch
- }
-
- // --- ADDED: Update dateFormat in localStorage ---
- if (prefsData && typeof prefsData.date_format !== 'undefined') {
- const oldDateFormat = localStorage.getItem('dateFormat');
- localStorage.setItem('dateFormat', prefsData.date_format);
- console.log(`Updated dateFormat in localStorage from API: ${prefsData.date_format}`);
- // Trigger re-render if format changed and warranties already exist (though unlikely at this stage)
- if (warranties && warranties.length > 0 && oldDateFormat !== prefsData.date_format) {
- console.log('Date format changed, triggering re-render via applyFilters');
- applyFilters(); // Re-render warranties with new format
- }
- } else {
- // If API doesn't return date_format, ensure localStorage has a default
- if (!localStorage.getItem('dateFormat')) {
- localStorage.setItem('dateFormat', 'MDY');
- console.log('API did not return date_format, setting localStorage default to MDY');
- }
- }
- // --- END ADDED SECTION ---
-
- } else {
- // Handle failed preference fetch
- console.warn('Failed to fetch preferences:', prefsResponse.status);
- // Ensure a default date format exists if fetch fails
- if (!localStorage.getItem('dateFormat')) {
- localStorage.setItem('dateFormat', 'MDY');
- console.log('Preferences fetch failed, setting localStorage default date format to MDY');
- }
- }
- } catch (error) {
- console.error('Error loading preferences:', error);
- // Ensure a default date format exists on error
- if (!localStorage.getItem('dateFormat')) {
- localStorage.setItem('dateFormat', 'MDY');
- console.log('Error fetching preferences, setting localStorage default date format to MDY');
- }
- // Continue loading warranties even if preferences fail
- }
- */
- // --- END REDUNDANT PREFERENCE FETCH ---
-
- // Check saved view scope preference to determine which API endpoint to use
- const savedScope = loadViewScopePreference();
- const shouldUseGlobalView = savedScope === 'global';
-
- // Use the appropriate API endpoint based on saved preference
- const baseUrl = window.location.origin;
- // If status is 'archived', use archived endpoint (support global vs personal)
- const isArchivedView = currentFilters && currentFilters.status === 'archived';
- const apiUrl = isArchivedView
- ? (shouldUseGlobalView ? `${baseUrl}/api/warranties/global/archived` : `${baseUrl}/api/warranties/archived`)
- : (shouldUseGlobalView ? `${baseUrl}/api/warranties/global` : `${baseUrl}/api/warranties`);
-
- console.log(`[DEBUG] Using API endpoint based on saved preference '${savedScope}', archivedView=${isArchivedView}: ${apiUrl}`);
-
- // Check if auth is available and user is authenticated using the passed parameter
- if (!isAuthenticated) {
- console.log('[DEBUG] loadWarranties: Early return - User not authenticated based on passed parameter.');
- renderEmptyState(window.t('messages.login_to_view_warranties'));
- hideLoading();
- return;
- }
- // Get the auth token
- const token = window.auth.getToken();
- if (!token) {
- console.log('[DEBUG] Early return: No auth token available');
- renderEmptyState(window.t('messages.authentication_error_login_again'));
- hideLoading();
- return;
- }
-
- // Create request with auth header
- const options = {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- };
-
- console.log('Fetching warranties with auth token');
- const response = await fetch(apiUrl, options);
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({ message: `HTTP error ${response.status}` }));
- console.error('Error loading warranties:', response.status, errorData);
- throw new Error(`Error loading warranties: ${errorData.message || response.status}`);
- }
- const data = await response.json();
- console.log('[DEBUG] Received warranties from server:', data);
- if (!Array.isArray(data)) {
- console.error('[DEBUG] API did not return an array! Data:', data);
- }
-
- // Update isGlobalView to match the loaded data
- isGlobalView = shouldUseGlobalView;
- console.log(`[DEBUG] Set isGlobalView to: ${isGlobalView}`);
-
- // Optionally merge archived items into the "All" view (only in personal scope)
- let combinedData = Array.isArray(data) ? data : [];
- lastLoadedIncludesArchived = false;
- if (!isArchivedView && currentFilters && currentFilters.status === 'all') {
- try {
- const archivedUrl = shouldUseGlobalView ? `${baseUrl}/api/warranties/global/archived` : `${baseUrl}/api/warranties/archived`;
- const archivedResp = await fetch(archivedUrl, options);
- if (archivedResp.ok) {
- const archivedData = await archivedResp.json();
- const archivedMarked = Array.isArray(archivedData)
- ? archivedData.map(w => ({ ...w, __isArchived: true }))
- : [];
- combinedData = combinedData.concat(archivedMarked);
- lastLoadedIncludesArchived = true;
- console.log(`[DEBUG] Merged ${archivedMarked.length} archived warranties into All view`);
- } else {
- // Log but do not block rendering of non-archived warranties
- let errInfo = '';
- try {
- const errJson = await archivedResp.json();
- errInfo = JSON.stringify(errJson);
- } catch (_) {}
- console.warn('[DEBUG] Failed to load archived warranties for All view:', archivedResp.status, errInfo);
- }
- } catch (mergeErr) {
- console.warn('[DEBUG] Error while merging archived into All:', mergeErr);
- }
- }
-
- // Process each warranty to calculate status and days remaining
- if (window.store && window.store.setWarranties) {
- window.store.setWarranties(Array.isArray(combinedData) ? combinedData.map(warranty => processWarrantyData(warranty)) : []);
- }
- warranties = (window.store && window.store.getWarranties) ? window.store.getWarranties() : (Array.isArray(combinedData) ? combinedData.map(warranty => processWarrantyData(warranty)) : []);
- lastLoadedArchived = isArchivedView;
- console.log('[DEBUG] Final warranties array:', warranties);
- console.log('[DEBUG] Total warranties loaded:', warranties.length);
- console.log('[DEBUG] Warranty IDs loaded:', warranties.map(w => w.id));
-
- // Set flag to indicate warranties have been loaded from API
- warrantiesLoaded = true;
-
- if (warranties.length === 0) {
- console.log('No warranties found, showing empty state');
- renderEmptyState(window.t('messages.no_warranties_found_add_first'));
- } else {
- console.log('Applying filters to display warranties');
-
- // Populate tag filter dropdown with tags from warranties
- populateTagFilter();
- populateVendorFilter(); // Added call to populate vendor filter
- populateWarrantyTypeFilter(); // Added call to populate warranty type filter
-
- // Ensure the UI reflects the freshly loaded data
- applyFilters();
- }
- } catch (error) {
- console.error('[DEBUG] Error loading warranties:', error);
- warrantiesLoaded = false; // Reset flag on error
- renderEmptyState(window.t('messages.error_loading_warranties_try_again'));
- } finally {
- hideLoading();
- }
-}
-
-function renderEmptyState(message = 'No warranties yet. Add your first warranty to get started.') {
- if (window.components && window.components.ui && window.components.ui.renderEmptyState && warrantiesList) {
- window.components.ui.renderEmptyState(warrantiesList, message);
- return;
- }
- warrantiesList.innerHTML = `
- <div class="empty-state">
- <i class="fas fa-box-open"></i>
- <h3>${window.t ? window.t('messages.no_warranties_found') : 'No warranties found'}</h3>
- <p>${message || (window.t ? window.t('messages.no_warranties_found_add_first') : 'No warranties yet. Add your first warranty to get started.')}</p>
- </div>
- `;
-}
-
-function formatDate(date) {
- // Input 'date' should now be a Date object created by processWarrantyData (or null)
- if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
- return 'N/A';
- }
-
- // Get the user's preferred format from localStorage, default to MDY
- const formatPreference = localStorage.getItem('dateFormat') || 'MDY';
-
- // Manually extract UTC components to avoid timezone discrepancies
- const year = date.getUTCFullYear();
- const monthIndex = date.getUTCMonth(); // 0-indexed for month names array
- const day = date.getUTCDate();
-
- // Padded numeric values
- const monthPadded = (monthIndex + 1).toString().padStart(2, '0');
- const dayPadded = day.toString().padStart(2, '0');
-
- // Abbreviated month names
- const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
- const monthAbbr = monthNames[monthIndex];
-
- switch (formatPreference) {
- case 'DMY':
- return `${dayPadded}/${monthPadded}/${year}`;
- case 'YMD':
- return `${year}-${monthPadded}-${dayPadded}`;
- case 'MDY_WORDS': // Added
- return `${monthAbbr} ${day}, ${year}`;
- case 'DMY_WORDS': // Added
- return `${day} ${monthAbbr} ${year}`;
- case 'YMD_WORDS': // Added
- return `${year} ${monthAbbr} ${day}`;
- case 'MDY':
- default:
- return `${monthPadded}/${dayPadded}/${year}`;
- }
-}
-
-function formatDateYYYYMMDD(date) {
- if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
- return 'N/A';
- }
-
- const year = date.getUTCFullYear();
- const month = String(date.getUTCMonth() + 1).padStart(2, '0');
- const day = String(date.getUTCDate()).padStart(2, '0');
-
- return `${year}-${month}-${day}`;
-}
-
-/**
- * Calculate the age of a product from purchase date to now
- * @param {string|Date} purchaseDate - The purchase date
- * @returns {string} - Formatted age string (e.g., "2 years, 3 months", "6 months", "15 days")
- */
-function calculateProductAge(purchaseDate) {
- if (!purchaseDate) return 'Unknown';
-
- const purchase = new Date(purchaseDate);
- const now = new Date();
-
- if (isNaN(purchase.getTime()) || purchase > now) {
- return 'Unknown';
- }
-
- // Calculate the difference
- let years = now.getFullYear() - purchase.getFullYear();
- let months = now.getMonth() - purchase.getMonth();
- let days = now.getDate() - purchase.getDate();
-
- // Adjust for negative days
- if (days < 0) {
- months--;
- const lastMonth = new Date(now.getFullYear(), now.getMonth(), 0);
- days += lastMonth.getDate();
- }
-
- // Adjust for negative months
- if (months < 0) {
- years--;
- months += 12;
- }
-
- // Format the result
- const parts = [];
- if (years > 0) {
- const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;
- parts.push(`${years} ${yearText}`);
- }
- if (months > 0) {
- const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;
- parts.push(`${months} ${monthText}`);
- }
- if (days > 0 && years === 0) { // Only show days if less than a year old
- const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;
- parts.push(`${days} ${dayText}`);
- }
-
- if (parts.length === 0) {
- return 'Today'; // Purchased today
- }
-
- return parts.join(', ');
-}
-
-/**
- * Calculate the age of a product in days for sorting purposes
- * @param {string|Date} purchaseDate - The purchase date
- * @returns {number} - Age in days (0 if invalid date)
- */
-function calculateProductAgeInDays(purchaseDate) {
- if (!purchaseDate) return 0;
-
- const purchase = new Date(purchaseDate);
- const now = new Date();
-
- if (isNaN(purchase.getTime()) || purchase > now) {
- return 0;
- }
-
- // Calculate difference in milliseconds and convert to days
- const diffTime = now.getTime() - purchase.getTime();
- const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
-
- return diffDays;
-}
-
-async function renderWarranties(warrantiesToRender) {
- console.log('renderWarranties called with:', warrantiesToRender);
-
- // Guard clause: If the main warrantiesList element doesn't exist on the current page, exit.
- // This can happen if saveWarranty -> applyFilters -> renderWarranties is called from a page
- // that doesn't have the main list view (e.g., the status page).
- if (!warrantiesList) {
- console.warn('renderWarranties: warrantiesList element not found. Aborting render. This might be normal if not on the main warranties page.');
- return;
- }
-
- const isArchivedView = currentFilters && currentFilters.status === 'archived';
-
- if (!warrantiesToRender || warrantiesToRender.length === 0) {
- renderEmptyState(isArchivedView ? (window.t ? window.t('messages.no_archived_warranties') : 'No archived warranties.') : undefined); // renderEmptyState should also check for warrantiesList or its specific container
- return;
- }
-
- const today = new Date();
- const globalSymbol = getCurrencySymbol(); // Get the global symbol as fallback
-
- warrantiesList.innerHTML = '';
-
- // Apply sorting based on current sort selection
- const sortedWarranties = [...warrantiesToRender].sort((a, b) => {
- switch (currentFilters.sortBy) {
- case 'name':
- return (a.product_name || '').toLowerCase().localeCompare((b.product_name || '').toLowerCase());
- case 'purchase':
- return new Date(b.purchase_date || 0) - new Date(a.purchase_date || 0);
- case 'age': // Added age sorting
- return calculateProductAgeInDays(b.purchase_date) - calculateProductAgeInDays(a.purchase_date); // Oldest first
- case 'vendor': // Added vendor sorting
- return (a.vendor || '').toLowerCase().localeCompare((b.vendor || '').toLowerCase());
- case 'warranty_type': // Added warranty type sorting
- return (a.warranty_type || '').toLowerCase().localeCompare((b.warranty_type || '').toLowerCase());
- case 'expiration':
- default:
- const dateA = new Date(a.expiration_date || 0);
- const dateB = new Date(b.expiration_date || 0);
-
- const isExpiredA = dateA < today;
- const isExpiredB = dateB < today;
-
- if (isExpiredA && !isExpiredB) return 1;
- if (!isExpiredA && isExpiredB) return -1;
-
- // Both active or both expired, sort by date
- return dateA - dateB;
- }
- });
-
- console.log('Sorted warranties:', sortedWarranties);
-
- // Update the container class based on current view
- warrantiesList.className = `warranties-list ${currentView}-view ${isArchivedView ? 'archived-view' : ''}`;
-
- // Show/hide table header for table view
- if (tableViewHeader) {
- tableViewHeader.classList.toggle('visible', currentView === 'table');
- }
-
- // Update view buttons to reflect current view
- if (gridViewBtn && listViewBtn && tableViewBtn) {
- gridViewBtn.classList.toggle('active', currentView === 'grid');
- listViewBtn.classList.toggle('active', currentView === 'list');
- tableViewBtn.classList.toggle('active', currentView === 'table');
- }
-
- sortedWarranties.forEach(warranty => {
- // --- Use processed data ---
- const purchaseDate = warranty.purchaseDate;
- const expirationDate = warranty.expirationDate;
- const isLifetime = warranty.is_lifetime;
- let statusClass = warranty.status || 'unknown';
- let statusText = warranty.statusText || 'Unknown Status';
- // If showing archived-only view or item itself is archived within All view
- if (isArchivedView || warranty.is_archived) {
- const archivedTextRaw = window.i18next ? window.i18next.t('warranties.archived') : 'Archived';
- const archivedLabel = archivedTextRaw && archivedTextRaw !== 'warranties.archived' ? archivedTextRaw : 'Archived';
- statusClass = 'archived';
- statusText = archivedLabel;
- }
- // Format warranty duration text
- let warrantyDurationText = window.i18next ? window.i18next.t('warranties.na') : 'N/A';
- if (isLifetime) {
- warrantyDurationText = window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime';
- } else {
- // Use display_duration values if available, otherwise fall back to warranty_duration values
- const years = warranty.display_duration_years !== undefined ? warranty.display_duration_years : (warranty.warranty_duration_years || 0);
- const months = warranty.display_duration_months !== undefined ? warranty.display_duration_months : (warranty.warranty_duration_months || 0);
- const days = warranty.display_duration_days !== undefined ? warranty.display_duration_days : (warranty.warranty_duration_days || 0);
-
- // If all duration fields are 0 but we have expiration date, calculate from dates
- if (years === 0 && months === 0 && days === 0 && warranty.expiration_date && warranty.purchase_date) {
- const calculatedDuration = calculateDurationFromDates(warranty.purchase_date, warranty.expiration_date);
- if (calculatedDuration) {
- let parts = [];
- if (calculatedDuration.years > 0) {
- const yearText = window.i18next ? window.i18next.t('warranties.year', {count: calculatedDuration.years}) : `year${calculatedDuration.years !== 1 ? 's' : ''}`;
- parts.push(`${calculatedDuration.years} ${yearText}`);
- }
- if (calculatedDuration.months > 0) {
- const monthText = window.i18next ? window.i18next.t('warranties.month', {count: calculatedDuration.months}) : `month${calculatedDuration.months !== 1 ? 's' : ''}`;
- parts.push(`${calculatedDuration.months} ${monthText}`);
- }
- if (calculatedDuration.days > 0) {
- const dayText = window.i18next ? window.i18next.t('warranties.day', {count: calculatedDuration.days}) : `day${calculatedDuration.days !== 1 ? 's' : ''}`;
- parts.push(`${calculatedDuration.days} ${dayText}`);
- }
- if (parts.length > 0) {
- warrantyDurationText = parts.join(', ');
- }
- }
- } else {
- // Use the stored/calculated duration fields
- let parts = [];
- if (years > 0) {
- const yearText = window.i18next ? window.i18next.t('warranties.year', {count: years}) : `year${years !== 1 ? 's' : ''}`;
- parts.push(`${years} ${yearText}`);
- }
- if (months > 0) {
- const monthText = window.i18next ? window.i18next.t('warranties.month', {count: months}) : `month${months !== 1 ? 's' : ''}`;
- parts.push(`${months} ${monthText}`);
- }
- if (days > 0) {
- const dayText = window.i18next ? window.i18next.t('warranties.day', {count: days}) : `day${days !== 1 ? 's' : ''}`;
- parts.push(`${days} ${dayText}`);
- }
- if (parts.length > 0) {
- warrantyDurationText = parts.join(', ');
- }
- }
- }
- const expirationDateText = isLifetime ? (window.i18next ? window.i18next.t('warranties.lifetime') : 'Lifetime') : formatDate(expirationDate);
-
- // Calculate product age
- const productAge = calculateProductAge(warranty.purchase_date);
-
- // Make sure serial numbers array exists and is valid
- const validSerialNumbers = Array.isArray(warranty.serial_numbers)
- ? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
- : [];
- // Prepare user info HTML for global view
- let userInfoHtml = '';
- if (isGlobalView && warranty.user_display_name) {
- const ownerLabel = window.i18next ? window.i18next.t('warranties.owner') : 'Owner';
- userInfoHtml = `<div><strong>${ownerLabel}:</strong> <span>${warranty.user_display_name}</span></div>`;
- }
-
- // Prepare tags array for component-based rendering
- const tagsArray = Array.isArray(warranty.tags) ? warranty.tags : [];
- // Add notes display button if present
- let notesHtml = '';
- const hasNotes = warranty.notes && warranty.notes.trim() !== '';
- // Remove the button, and instead prepare a notes link for document-links-row
- let notesLinkHtml = '';
- if (hasNotes) {
- const notesLabel = window.i18next ? window.i18next.t('warranties.notes') : 'Notes';
- notesLinkHtml = `<a href="#" class="notes-link" data-id="${warranty.id}" title="View Notes"><i class='fas fa-sticky-note'></i> ${notesLabel}</a>`;
- }
-
- const hasDocuments = Boolean(
- warranty.product_url ||
- warranty.invoice_path || warranty.invoice_url ||
- warranty.manual_path || warranty.manual_url ||
- warranty.other_document_path || warranty.other_document_url ||
- warranty.paperless_invoice_id || warranty.paperless_manual_id ||
- warranty.paperless_photo_id || warranty.paperless_other_id ||
- hasNotes
- );
-
-
- // Get current user ID to check warranty ownership
- const currentUserId = (() => {
- try {
- const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
- return userInfo.id;
- } catch (e) {
- return null;
- }
- })();
-
- // Check if current user can edit/delete this warranty
- // Allow if: not in global view, user owns the warranty, or user is admin
- const isAdmin = getUserType() === 'admin';
- const canEdit = !isGlobalView || (warranty.user_id === currentUserId) || isAdmin;
-
- // Determine claims button class and title based on claim status
- let claimsButtonClass = 'action-btn claims-link';
- let claimsTitle = 'Claims';
-
- if (warranty.claim_status_summary === 'OPEN') {
- claimsButtonClass += ' claims-open';
- claimsTitle = 'Claims (Open)';
- } else if (warranty.claim_status_summary === 'FINISHED') {
- claimsButtonClass += ' claims-finished';
- claimsTitle = 'Claims (Finished)';
- }
-
- // Generate action buttons HTML based on permissions
- const actionButtonsHtml = canEdit ? `
- <button class="${claimsButtonClass}" title="${claimsTitle}" data-id="${warranty.id}">
- <i class="fas fa-clipboard-list"></i>
- </button>
- ${ (isArchivedView || warranty.is_archived) ? `
- <button class="action-btn unarchive-btn" title="Unarchive" data-id="${warranty.id}">
- <i class="fas fa-box-open"></i>
- </button>
- <button class="action-btn edit-btn" title="Edit (disabled in archived view)" data-id="${warranty.id}" disabled>
- <i class="fas fa-edit"></i>
- </button>
- ` : `
- <button class="action-btn edit-btn" title="Edit" data-id="${warranty.id}">
- <i class="fas fa-edit"></i>
- </button>
- <button class="action-btn archive-btn" title="Archive" data-id="${warranty.id}">
- <i class="fas fa-archive"></i>
- </button>
- `}
- <button class="action-btn delete-btn" title="Delete" data-id="${warranty.id}">
- <i class="fas fa-trash"></i>
- </button>
- ` : `
- <button class="${claimsButtonClass}" title="${claimsTitle}" data-id="${warranty.id}">
- <i class="fas fa-clipboard-list"></i>
- </button>
- <span class="action-btn-placeholder" title="View only - not your warranty">
- <i class="fas fa-eye" style="color: #666;"></i>
- </span>
- `;
-
- let cardElement = document.createElement('div');
- const isArchivedItem = isArchivedView || warranty.is_archived;
- cardElement.className = `warranty-card ${isArchivedItem ? 'archived' : (statusClass === 'expired' ? 'expired' : statusClass === 'expiring' ? 'expiring-soon' : 'active')}`;
-
- // Claims button styling will be handled in the action buttons HTML generation
-
- if (currentView === 'grid') {
- const rootModifierClass = (isArchivedItem ? 'archived' : (statusClass === 'expired' ? 'expired' : (statusClass === 'expiring' ? 'expiring-soon' : 'active')));
- const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `
- <div class="product-photo-thumbnail">
- <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
- <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
- style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 2px solid var(--border-color); cursor: pointer;"
- onerror="this.style.display='none'" class="secure-image">
- </a>
- </div>
- ` : '';
- const contentHtml = `
- ${photoThumbnailHtml}
- <div class="warranty-info">
- ${userInfoHtml}
- <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>
- <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>
- <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>
- ${warranty.purchase_price ? `<div><i class=\"fas fa-coins\"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}
- ${validSerialNumbers.length > 0 ? `
- <div><i class=\"fas fa-barcode\"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>
- ${validSerialNumbers.length > 1 ? `
- <div style=\"margin-left: 28px;\">
- <ul style=\"margin-top: 5px;\">
- ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}
- </ul>
- </div>
- ` : ''}
- ` : ''}
- ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}
- ${warranty.vendor ? `<div><i class=\"fas fa-store\"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}
- ${warranty.warranty_type ? `<div><i class=\"fas fa-shield-alt\"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}
- </div>
- ${hasDocuments ? `
- <div class="document-links-row">
- <div class="document-links-inner-container">
- ${warranty.product_url ? `
- <a href="${warranty.product_url}" class="product-link" target="_blank">
- <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}
- </a>
- ` : ''}
- ${generateDocumentLink(warranty, 'invoice')}
- ${generateDocumentLink(warranty, 'manual')}
- ${generateDocumentLink(warranty, 'other')}
- ${notesLinkHtml}
- </div>
- </div>
- ` : ''}
-
- `;
- if (window.components && window.components.createWarrantyCard) {
- cardElement = window.components.createWarrantyCard(warranty, { actionsHtml: actionButtonsHtml, contentHtml, statusText, statusClass, rootModifierClass });
- } else {
- cardElement.className = `warranty-card ${rootModifierClass}`;
- cardElement.innerHTML = `
- <div class=\"product-name-header\">\n <h3 class=\"warranty-title\">${warranty.product_name || 'Unnamed Product'}</h3>\n <div class=\"warranty-actions\">${actionButtonsHtml}</div>\n </div>
- <div class=\"warranty-content\">${contentHtml}</div>
- <div class=\"warranty-status-row status-${statusClass}\"><span>${statusText}</span></div>
- `;
- }
- } else if (currentView === 'list') {
- // List view uses the same component template with different content sizing
- const rootModifierClass = (isArchivedItem ? 'archived' : (statusClass === 'expired' ? 'expired' : (statusClass === 'expiring' ? 'expiring-soon' : 'active')));
- const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `
- <div class="product-photo-thumbnail">
- <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
- <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
- style="width: 180px; height: 180px; object-fit: cover; border-radius: 6px; border: 2px solid var(--border-color); cursor: pointer;"
- onerror="this.style.display='none'" class="secure-image">
- </a>
- </div>
- ` : '';
-
- const contentHtml = `
- ${photoThumbnailHtml}
- <div class="warranty-info">
- ${userInfoHtml}
- <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>
- <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>
- <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>
- ${warranty.purchase_price ? `<div><i class=\"fas fa-coins\"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}
- ${validSerialNumbers.length > 0 ? `
- <div><i class=\"fas fa-barcode\"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>
- ${validSerialNumbers.length > 1 ? `
- <div style=\"margin-left: 28px;\">
- <ul style=\"margin-top: 5px;\">
- ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}
- </ul>
- </div>
- ` : ''}
- ` : ''}
- ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}
- ${warranty.vendor ? `<div><i class=\"fas fa-store\"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}
- ${warranty.warranty_type ? `<div><i class=\"fas fa-shield-alt\"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}
- </div>
- ${hasDocuments ? `
- <div class="document-links-row">
- <div class="document-links-inner-container">
- ${warranty.product_url ? `
- <a href="${warranty.product_url}" class="product-link" target="_blank">
- <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}
- </a>
- ` : ''}
- ${generateDocumentLink(warranty, 'invoice')}
- ${generateDocumentLink(warranty, 'manual')}
- ${generateDocumentLink(warranty, 'other')}
- ${notesLinkHtml}
- </div>
- </div>
- ` : ''}
-
- `;
-
- if (window.components && window.components.createWarrantyCard) {
- cardElement = window.components.createWarrantyCard(warranty, { actionsHtml: actionButtonsHtml, contentHtml, statusText, statusClass, rootModifierClass });
- } else {
- cardElement.className = `warranty-card ${rootModifierClass}`;
- cardElement.innerHTML = `
- <div class=\"product-name-header\">\n <h3 class=\"warranty-title\">${warranty.product_name || 'Unnamed Product'}</h3>\n <div class=\"warranty-actions\">${actionButtonsHtml}</div>\n </div>
- <div class=\"warranty-content\">${contentHtml}</div>
- <div class=\"warranty-status-row status-${statusClass}\"><span>${statusText}</span></div>
- `;
- }
- } else if (currentView === 'table') {
- // Table view uses the same component template with compact content sizing
- const rootModifierClass = (isArchivedItem ? 'archived' : (statusClass === 'expired' ? 'expired' : (statusClass === 'expiring' ? 'expiring-soon' : 'active')));
- const photoThumbnailHtml = warranty.product_photo_path && warranty.product_photo_path !== 'null' ? `
- <div class="product-photo-thumbnail">
- <a href="#" onclick="openSecureFile('${warranty.product_photo_path}'); return false;" title="Click to view full size image">
- <img data-secure-src="/api/secure-file/${warranty.product_photo_path.replace('uploads/', '')}" alt="Product Photo"
- style="width: 55px; height: 55px; object-fit: cover; border-radius: 4px; border: 1px solid var(--border-color); cursor: pointer;"
- onerror="this.style.display='none'" class="secure-image">
- </a>
- </div>
- ` : '';
-
- const contentHtml = `
- ${photoThumbnailHtml}
- <div class="warranty-info">
- ${userInfoHtml}
- <div><i class="fas fa-calendar"></i> ${window.i18next ? window.i18next.t('warranties.age') : 'Age'}: <span>${productAge}</span></div>
- <div><i class="fas fa-file-alt"></i> ${window.i18next ? window.i18next.t('warranties.warranty') : 'Warranty'}: <span>${warrantyDurationText}</span></div>
- <div><i class="fas fa-wrench"></i> ${window.i18next ? window.i18next.t('warranties.warranty_ends') : 'Warranty Ends'}: <span>${expirationDateText}</span></div>
- ${warranty.purchase_price ? `<div><i class=\"fas fa-coins\"></i> ${window.i18next ? window.i18next.t('warranties.price') : 'Price'}: <span>${formatCurrencyHTML(warranty.purchase_price, warranty.currency ? getCurrencySymbolByCode(warranty.currency) : getCurrencySymbol(), getCurrencyPosition())}</span></div>` : ''}
- ${validSerialNumbers.length > 0 ? `
- <div><i class=\"fas fa-barcode\"></i> ${window.i18next ? window.i18next.t('warranties.serial_number') : 'Serial Number'}: <span>${validSerialNumbers[0]}</span></div>
- ${validSerialNumbers.length > 1 ? `
- <div style=\"margin-left: 28px;\">
- <ul style=\"margin-top: 5px;\">
- ${validSerialNumbers.slice(1).map(sn => `<li>${sn}</li>`).join('')}
- </ul>
- </div>
- ` : ''}
- ` : ''}
- ${warranty.model_number ? `<div><i class=\"fas fa-tag\"></i> ${window.i18next ? window.i18next.t('warranties.model_number') : 'Model Number'}: <span>${warranty.model_number}</span></div>` : ''}
- ${warranty.vendor ? `<div><i class=\"fas fa-store\"></i> ${window.i18next ? window.i18next.t('warranties.vendor') : 'Vendor'}: <span>${warranty.vendor}</span></div>` : ''}
- ${warranty.warranty_type ? `<div><i class=\"fas fa-shield-alt\"></i> ${window.i18next ? window.i18next.t('warranties.type') : 'Type'}: <span>${warranty.warranty_type}</span></div>` : ''}
- </div>
- <div class="warranty-status-row status-${statusClass}">
- <span>${statusText}</span>
- </div>
- ${hasDocuments ? `
- <div class="document-links-row">
- <div class="document-links-inner-container">
- ${warranty.product_url ? `
- <a href="${warranty.product_url}" class="product-link" target="_blank">
- <i class="fas fa-globe"></i> ${window.i18next ? window.i18next.t('warranties.product_website') : 'Product Website'}
- </a>
- ` : ''}
- ${generateDocumentLink(warranty, 'invoice')}
- ${generateDocumentLink(warranty, 'manual')}
- ${generateDocumentLink(warranty, 'other')}
- ${notesLinkHtml}
- </div>
- </div>
- ` : ''}
-
- `;
-
- if (window.components && window.components.createWarrantyCard) {
- cardElement = window.components.createWarrantyCard(warranty, { actionsHtml: actionButtonsHtml, contentHtml, statusText, statusClass, rootModifierClass });
- } else {
- cardElement.className = `warranty-card ${rootModifierClass}`;
- cardElement.innerHTML = `
- <div class=\"product-name-header\">\n <h3 class=\"warranty-title\">${warranty.product_name || 'Unnamed Product'}</h3>\n <div class=\"warranty-actions\">${actionButtonsHtml}</div>\n </div>
- <div class=\"warranty-content\">${contentHtml}</div>
- `;
- }
- }
-
- // Append tags via component (replaces previous string-based tagsHtml)
- if (window.components && window.components.appendTags && tagsArray && tagsArray.length > 0) {
- try {
- window.components.appendTags(cardElement, tagsArray);
- } catch (e) {
- console.warn('appendTags failed', e);
- }
- }
-
- // Add event listeners
- warrantiesList.appendChild(cardElement);
-
- // Add event listeners only if user can edit (buttons exist)
- if (canEdit) {
- // Edit button event listener
- const editBtn = cardElement.querySelector('.edit-btn');
- if (editBtn && !editBtn.disabled) {
- editBtn.addEventListener('click', async () => {
- console.log('[DEBUG] Edit button clicked for warranty ID:', warranty.id);
- // Find the current warranty data instead of using the potentially stale warranty object
- const currentWarranty = warranties.find(w => w.id === warranty.id);
- console.log('[DEBUG] Found current warranty:', currentWarranty ? 'Yes' : 'No', currentWarranty?.notes);
- if (currentWarranty) {
- await openEditModal(currentWarranty);
- } else {
- showToast(window.t('messages.warranty_not_found_refresh'), 'error');
- }
- });
- }
-
- // Delete button event listener
- const deleteBtn = cardElement.querySelector('.delete-btn');
- if (deleteBtn) {
- deleteBtn.addEventListener('click', () => {
- openDeleteModal(warranty.id, warranty.product_name);
- });
- }
-
- // Archive/Unarchive button event listeners
- const archiveBtn = cardElement.querySelector('.archive-btn');
- if (archiveBtn) {
- archiveBtn.addEventListener('click', () => {
- openArchiveModal(warranty.id, warranty.product_name);
- });
- }
- const unarchiveBtn = cardElement.querySelector('.unarchive-btn');
- if (unarchiveBtn) {
- unarchiveBtn.addEventListener('click', async () => {
- await toggleArchiveStatus(warranty.id, false);
- });
- }
- }
- // View notes button event listener
- const notesLink = cardElement.querySelector('.notes-link');
- if (notesLink) {
- notesLink.addEventListener('click', (e) => {
- e.preventDefault();
- // Find the current warranty data instead of using the potentially stale warranty object
- const currentWarranty = warranties.find(w => w.id === warranty.id);
- if (currentWarranty) {
- showNotesModal(currentWarranty.notes, currentWarranty);
- } else {
- showToast(window.t('messages.warranty_not_found_refresh'), 'error');
- }
- });
- }
- });
-
- // Load secure images with authentication after rendering
- loadSecureImages();
-
- // Improved: Align card heights after all images have loaded
- if (currentView === 'grid') {
- const cards = warrantiesList.querySelectorAll('.warranty-card');
- if (cards.length > 0) {
- const images = warrantiesList.querySelectorAll('.secure-image');
- let loadedCount = 0;
- const totalImages = images.length;
-
- const alignHeights = () => {
- let maxHeight = 0;
- cards.forEach(card => {
- card.style.minHeight = ''; // Reset
- const height = card.getBoundingClientRect().height;
- if (height > maxHeight) maxHeight = height;
- });
- cards.forEach(card => {
- card.style.minHeight = `${maxHeight}px`;
- });
- };
-
- if (totalImages === 0) {
- alignHeights(); // No images, align immediately
- } else {
- images.forEach(img => {
- if (img.complete) {
- loadedCount++;
- if (loadedCount === totalImages) alignHeights();
- } else {
- img.addEventListener('load', () => {
- loadedCount++;
- if (loadedCount === totalImages) alignHeights();
- });
- img.addEventListener('error', () => {
- loadedCount++;
- if (loadedCount === totalImages) alignHeights();
- });
- }
- });
- }
- }
- }
-
- // Update the timeline chart if on the status page or appropriate
- if (typeof updateTimelineChart === 'function') {
- updateTimelineChart();
- }
-
- console.log('Warranties rendered successfully');
-}
-
-function filterWarranties() {
- const searchTerm = searchInput ? searchInput.value.toLowerCase() : ''; // Add null check for searchInput
-
- // Show or hide the clear search button if it exists
- if (clearSearchBtn) {
- clearSearchBtn.style.display = searchTerm ? 'flex' : 'none';
- }
-
- if (!searchTerm) {
- return warranties; // Return the full list if no search term
- // REMOVED: renderWarranties();
- // REMOVED: return;
- }
-
- const filtered = warranties.filter(warranty => {
- // Check product name
- if (warranty.product_name && warranty.product_name.toLowerCase().includes(searchTerm)) { // Add null check
- return true;
- }
-
- // Check tags
- if (warranty.tags && Array.isArray(warranty.tags)) {
- if (warranty.tags.some(tag => tag.name && tag.name.toLowerCase().includes(searchTerm))) {
- return true;
- }
- }
-
- // Check notes
- if (warranty.notes && warranty.notes.toLowerCase().includes(searchTerm)) {
- return true;
- }
-
- // Check vendor
- if (warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm)) {
- return true;
- }
-
- // Check model number
- if (warranty.model_number && warranty.model_number.toLowerCase().includes(searchTerm)) {
- return true;
- }
-
- // Check if any serial number contains search term
- if (warranty.serial_numbers && Array.isArray(warranty.serial_numbers)) {
- if (warranty.serial_numbers.some(sn => sn && sn.toLowerCase().includes(searchTerm))) {
- return true;
- }
- }
-
- return false;
- });
-
- // REMOVED: Add visual feedback if no results found
- // REMOVED: if (filtered.length === 0) {
- // REMOVED: renderEmptyState(`No matches found for "${searchTerm}". Try a different search term.`);
- // REMOVED: } else {
- // REMOVED: renderWarranties(filtered);
- // REMOVED: }
-
- return filtered; // Return the filtered list
-}
-
-function applyFilters() {
- console.log('[FILTER DEBUG] Applying filters with:', currentFilters);
- console.log('[FILTER DEBUG] Total warranties before filtering:', warranties.length);
-
- // If user selected archived status, reload data from archived endpoint and return
- if (currentFilters.status === 'archived') {
- if (!lastLoadedArchived) {
- loadWarranties(true);
- return;
- }
- } else if (lastLoadedArchived) {
- // If leaving archived view, reload normal source
- loadWarranties(true);
- return;
- } else if (currentFilters.status === 'all' && !lastLoadedIncludesArchived) {
- // Ensure All view re-merges archived items after switching away and back
- loadWarranties(true);
- return;
- }
-
- // Filter warranties based on currentFilters
- const filtered = warranties.filter(warranty => {
- // Exclude archived items from specific status views (only show in 'all' or 'archived')
- if (warranty.is_archived && currentFilters.status !== 'all' && currentFilters.status !== 'archived') {
- return false;
- }
- // Status filter: allow archived items to pass in All view
- if (currentFilters.status !== 'all' && currentFilters.status !== 'archived' && warranty.status !== currentFilters.status) {
- return false;
- }
-
- // Tag filter
- if (currentFilters.tag !== 'all') {
- const tagId = parseInt(currentFilters.tag);
- const hasTag = warranty.tags && Array.isArray(warranty.tags) &&
- warranty.tags.some(tag => tag.id === tagId);
- if (!hasTag) {
- return false;
- }
- }
-
- // Vendor filter
- if (currentFilters.vendor !== 'all' && (warranty.vendor || '').toLowerCase() !== currentFilters.vendor.toLowerCase()) {
- return false;
- }
-
- // Warranty type filter
- if (currentFilters.warranty_type !== 'all' && (warranty.warranty_type || '').toLowerCase() !== currentFilters.warranty_type.toLowerCase()) {
- return false;
- }
-
- // Search filter
- if (currentFilters.search) {
- const searchTerm = currentFilters.search.toLowerCase();
- // Check if product name contains search term
- const productNameMatch = warranty.product_name.toLowerCase().includes(searchTerm);
- // Check if any tag name contains search term
- const tagMatch = warranty.tags && Array.isArray(warranty.tags) &&
- warranty.tags.some(tag => tag.name.toLowerCase().includes(searchTerm));
- // Check if notes contains search term
- const notesMatch = warranty.notes && warranty.notes.toLowerCase().includes(searchTerm);
- // Check if vendor contains search term
- const vendorMatch = warranty.vendor && warranty.vendor.toLowerCase().includes(searchTerm);
- // Check if model number contains search term
- const modelNumberMatch = warranty.model_number && warranty.model_number.toLowerCase().includes(searchTerm);
- // Check if any serial number contains search term
- const serialNumberMatch = warranty.serial_numbers && Array.isArray(warranty.serial_numbers) &&
- warranty.serial_numbers.some(sn => sn && sn.toLowerCase().includes(searchTerm));
- // Return true if any match
- if (!productNameMatch && !tagMatch && !notesMatch && !vendorMatch && !modelNumberMatch && !serialNumberMatch) {
- return false;
- }
- }
-
- return true;
- });
-
- console.log('[FILTER DEBUG] Filtered warranties:', filtered.length);
- console.log('[FILTER DEBUG] Filtered warranty IDs:', filtered.map(w => w.id));
-
- // Render the filtered warranties
- renderWarranties(filtered);
-}
-
-// --- Persist and restore filters/sort ---
-async function saveFilterPreferences(saveToApi = true) {
- try {
- const prefix = getPreferenceKeyPrefix();
- const filtersToSave = {
- status: currentFilters.status || 'all',
- tag: currentFilters.tag || 'all',
- vendor: currentFilters.vendor || 'all',
- warranty_type: currentFilters.warranty_type || 'all',
- search: currentFilters.search || '',
- sortBy: currentFilters.sortBy || 'expiration'
- };
- localStorage.setItem(`${prefix}warrantyFilters`, JSON.stringify(filtersToSave));
-
- // Save to API if authenticated and saveToApi is true
- if (saveToApi && window.auth && window.auth.isAuthenticated()) {
- const token = window.auth.getToken();
- if (token) {
- try {
- console.log('[Filters] Saving filter preferences to API:', filtersToSave);
- const response = await fetch('/api/auth/preferences', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({ saved_filters: filtersToSave })
- });
-
- if (response.ok) {
- console.log('[Filters] Successfully saved filter preferences to API');
- } else {
- console.warn('[Filters] Failed to save filter preferences to API:', response.status);
- }
- } catch (error) {
- console.error('[Filters] Error saving filter preferences to API:', error);
- }
- }
- }
- } catch (e) {
- console.warn('Failed to save filter preferences', e);
- }
-}
-
-// Deprecated: Sort preference is now saved as part of saveFilterPreferences
-
-function loadFilterAndSortPreferences() {
- try {
- const prefix = getPreferenceKeyPrefix();
- const savedFiltersRaw = localStorage.getItem(`${prefix}warrantyFilters`);
- if (savedFiltersRaw) {
- const savedFilters = JSON.parse(savedFiltersRaw);
- if (savedFilters && typeof savedFilters === 'object') {
- console.log('[Filters] Loading saved filters from localStorage:', savedFilters);
- if (window.store && window.store.updateFilter) {
- if (savedFilters.status) window.store.updateFilter('status', savedFilters.status);
- if (savedFilters.tag) window.store.updateFilter('tag', savedFilters.tag);
- if (savedFilters.vendor) window.store.updateFilter('vendor', savedFilters.vendor);
- if (savedFilters.warranty_type) window.store.updateFilter('warranty_type', savedFilters.warranty_type);
- window.store.updateFilter('search', savedFilters.search || '');
- if (savedFilters.sortBy) window.store.updateFilter('sortBy', savedFilters.sortBy);
- }
- currentFilters.status = savedFilters.status || currentFilters.status;
- currentFilters.tag = savedFilters.tag || currentFilters.tag;
- currentFilters.vendor = savedFilters.vendor || currentFilters.vendor;
- currentFilters.warranty_type = savedFilters.warranty_type || currentFilters.warranty_type;
- currentFilters.search = savedFilters.search || '';
- currentFilters.sortBy = savedFilters.sortBy || currentFilters.sortBy;
-
- // Restore search input UI state
- const searchInput = document.getElementById('searchWarranties');
- const clearSearchBtn = document.getElementById('clearSearch');
- if (searchInput && savedFilters.search) {
- searchInput.value = savedFilters.search;
- // Show clear button if search has value
- if (clearSearchBtn) {
- clearSearchBtn.style.display = 'flex';
- }
- // Add active search class
- searchInput.parentElement.classList.add('active-search');
- }
- }
- }
- } catch (e) {
- console.warn('Failed to load filter/sort preferences', e);
- }
-}
-
-async function openEditModal(warranty) {
- // Close any existing modals first
- closeModals();
-
- currentWarrantyId = warranty.id;
-
- // Load currencies for the dropdown and wait for it to complete
- await loadCurrencies();
-
- console.log('[DEBUG] Opening edit modal for warranty:', warranty.id, 'with notes:', warranty.notes);
-
- // Populate form fields
- document.getElementById('editProductName').value = warranty.product_name;
- document.getElementById('editProductUrl').value = warranty.product_url || '';
- const editModelNumberInput = document.getElementById('editModelNumber');
- if (editModelNumberInput) {
- editModelNumberInput.value = warranty.model_number || '';
- }
- document.getElementById('editPurchaseDate').value = warranty.purchase_date.split('T')[0];
- // Populate new duration fields
- document.getElementById('editWarrantyDurationYears').value = warranty.warranty_duration_years || 0;
- document.getElementById('editWarrantyDurationMonths').value = warranty.warranty_duration_months || 0;
- document.getElementById('editWarrantyDurationDays').value = warranty.warranty_duration_days || 0;
-
- document.getElementById('editPurchasePrice').value = warranty.purchase_price || '';
-
- // Set currency dropdown
- const editCurrencySelect = document.getElementById('editCurrency');
- if (editCurrencySelect && warranty.currency) {
- editCurrencySelect.value = warranty.currency;
- }
- document.getElementById('editVendor').value = warranty.vendor || '';
-
- // Populate URL fields for documents (with null checks)
- const editInvoiceUrl = document.getElementById('editInvoiceUrl');
- if (editInvoiceUrl) editInvoiceUrl.value = warranty.invoice_url || '';
-
- const editManualUrl = document.getElementById('editManualUrl');
- if (editManualUrl) editManualUrl.value = warranty.manual_url || '';
-
- const editOtherDocumentUrl = document.getElementById('editOtherDocumentUrl');
- if (editOtherDocumentUrl) editOtherDocumentUrl.value = warranty.other_document_url || '';
-
- // Handle warranty type - check if it's a predefined option or custom
- const editWarrantyTypeSelect = document.getElementById('editWarrantyType');
- const editWarrantyTypeCustom = document.getElementById('editWarrantyTypeCustom');
- if (editWarrantyTypeSelect && warranty.warranty_type) {
- // Check if the warranty type exists as an option in the dropdown
- const options = Array.from(editWarrantyTypeSelect.options);
- const matchingOption = options.find(option => option.value === warranty.warranty_type);
-
- if (matchingOption) {
- // It's a predefined option
- editWarrantyTypeSelect.value = warranty.warranty_type;
- if (editWarrantyTypeCustom) editWarrantyTypeCustom.style.display = 'none';
- } else {
- // It's a custom value
- editWarrantyTypeSelect.value = 'other';
- if (editWarrantyTypeCustom) {
- editWarrantyTypeCustom.style.display = 'block';
- editWarrantyTypeCustom.value = warranty.warranty_type;
- }
- }
- } else if (editWarrantyTypeSelect) {
- editWarrantyTypeSelect.value = '';
- if (editWarrantyTypeCustom) editWarrantyTypeCustom.style.display = 'none';
- }
-
- // Clear existing serial number inputs
- const editSerialNumbersContainer = document.getElementById('editSerialNumbersContainer');
- editSerialNumbersContainer.innerHTML = '';
-
- // Normalize serial_numbers to array of strings if needed
- if (Array.isArray(warranty.serial_numbers) && warranty.serial_numbers.length > 0 && typeof warranty.serial_numbers[0] === 'object') {
- warranty.serial_numbers = warranty.serial_numbers
- .map(snObj => snObj && snObj.serial_number)
- .filter(sn => typeof sn === 'string' && sn.trim() !== '');
- }
-
- // Add event listener for adding new serial number inputs in edit modal
- editSerialNumbersContainer.addEventListener('click', (e) => {
- if (e.target.closest('.add-serial-number')) {
- addSerialNumberInput(editSerialNumbersContainer);
- }
- });
-
- const validSerialNumbers = Array.isArray(warranty.serial_numbers)
- ? warranty.serial_numbers.filter(sn => sn && typeof sn === 'string' && sn.trim() !== '')
- : [];
-
- if (validSerialNumbers.length === 0) {
- // Add a single empty input if there are no serial numbers
- addSerialNumberInput(editSerialNumbersContainer);
- } else {
- // Add the first serial number with an "Add Another" button only (no remove button)
- const firstInput = document.createElement('div');
- firstInput.className = 'serial-number-input';
- firstInput.innerHTML = `
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="${i18next.t('warranties.enter_serial_number')}" value="${validSerialNumbers[0]}">
- <button type="button" class="btn btn-sm btn-primary add-serial-number">
- <i class="fas fa-plus"></i> ${i18next.t('warranties.add_serial_number')}
- </button>
- `;
-
- // Add event listener for the Add button
- firstInput.querySelector('.add-serial-number').addEventListener('click', function(e) {
- e.stopPropagation(); // Stop event from bubbling up
- addSerialNumberInput(editSerialNumbersContainer);
- });
-
- editSerialNumbersContainer.appendChild(firstInput);
-
- // Add the rest of the serial numbers with "Remove" buttons
- for (let i = 1; i < validSerialNumbers.length; i++) {
- const newInput = document.createElement('div');
- newInput.className = 'serial-number-input';
- newInput.innerHTML = `
- <input type="text" name="serial_numbers[]" class="form-control" placeholder="${i18next.t('warranties.enter_serial_number')}" value="${validSerialNumbers[i]}">
- <button type="button" class="btn btn-sm btn-danger remove-serial-number">
- <i class="fas fa-minus"></i> ${i18next.t('actions.delete')}
- </button>
- `;
-
- // Add remove button functionality
- newInput.querySelector('.remove-serial-number').addEventListener('click', function() {
- this.parentElement.remove();
- });
-
- editSerialNumbersContainer.appendChild(newInput);
- }
- }
-
- // Show current invoice if exists
- const currentInvoiceElement = document.getElementById('currentInvoice');
- const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');
- if (currentInvoiceElement && deleteInvoiceBtn) {
- const hasLocalInvoice = warranty.invoice_path && warranty.invoice_path !== 'null';
- const hasPaperlessInvoice = warranty.paperless_invoice_id && warranty.paperless_invoice_id !== null;
-
- if (hasLocalInvoice) {
- currentInvoiceElement.innerHTML = `
- <span class="text-success">
- <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_invoice')}:
- <a href="#" class="view-document-link" onclick="openSecureFile('${warranty.invoice_path}'); return false;">View</a>
- (${i18next.t('warranties.upload_new_file_replace')})
- </span>
- `;
- deleteInvoiceBtn.style.display = '';
- } else if (hasPaperlessInvoice) {
- currentInvoiceElement.innerHTML = `
- <span class="text-success">
- <i class="fas fa-check-circle"></i> ${i18next.t('warranties.current_invoice')}:
- <a href="#" class="view-document-link" onclick="openPaperlessDocument(${warranty.paperless_invoice_id}, {user_id: ${warranty.user_id}, id: ${warranty.id}}); return false;">View</a>
- <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i> (${i18next.t('warranties.upload_new_file_replace')})
- </span>
- `;
- deleteInvoiceBtn.style.display = '';
- } else {
- currentInvoiceElement.innerHTML = `<span>${i18next.t('warranties.no_invoice_uploaded')}</span>`;
- deleteInvoiceBtn.style.display = 'none';
- }
- // Reset delete state
- deleteInvoiceBtn.dataset.delete = 'false';
- deleteInvoiceBtn.onclick = function() {
- deleteInvoiceBtn.dataset.delete = 'true';
- currentInvoiceElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.invoice_will_be_deleted')}</span>`;
- deleteInvoiceBtn.style.display = 'none';
- };
- }
- // Show current manual (component-based)
- const currentManualElement = document.getElementById('currentManual');
- const deleteManualBtn = document.getElementById('deleteManualBtn');
- if (currentManualElement && deleteManualBtn && window.components && window.components.editModal) {
- window.components.editModal.renderCurrentManual(currentManualElement, deleteManualBtn, warranty, window.i18next);
- deleteManualBtn.dataset.delete = 'false';
- deleteManualBtn.onclick = function() {
- deleteManualBtn.dataset.delete = 'true';
- currentManualElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.manual_will_be_deleted')}</span>`;
- deleteManualBtn.style.display = 'none';
- };
- }
-
- // Show current product photo (component-based)
- const currentProductPhotoElement = document.getElementById('currentProductPhoto');
- const deleteProductPhotoBtn = document.getElementById('deleteProductPhotoBtn');
- if (currentProductPhotoElement && deleteProductPhotoBtn && window.components && window.components.editModal) {
- window.components.editModal.renderCurrentPhoto(currentProductPhotoElement, deleteProductPhotoBtn, warranty, window.i18next);
- deleteProductPhotoBtn.dataset.delete = 'false';
- deleteProductPhotoBtn.onclick = function() {
- deleteProductPhotoBtn.dataset.delete = 'true';
- currentProductPhotoElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.photo_will_be_deleted')}</span>`;
- deleteProductPhotoBtn.style.display = 'none';
- };
- }
-
- // Show current other document (component-based)
- const currentOtherDocumentElement = document.getElementById('currentOtherDocument');
- const deleteOtherDocumentBtn = document.getElementById('deleteOtherDocumentBtn');
- if (currentOtherDocumentElement && deleteOtherDocumentBtn && window.components && window.components.editModal) {
- window.components.editModal.renderCurrentOther(currentOtherDocumentElement, deleteOtherDocumentBtn, warranty, window.i18next);
- deleteOtherDocumentBtn.dataset.delete = 'false';
- deleteOtherDocumentBtn.onclick = function() {
- deleteOtherDocumentBtn.dataset.delete = 'true';
- currentOtherDocumentElement.innerHTML = `<span class="text-danger">${i18next.t('warranties.other_document_will_be_deleted')}</span>`;
- deleteOtherDocumentBtn.style.display = 'none';
- };
- }
-
- // Reset file inputs
- document.getElementById('editProductPhoto').value = '';
- document.getElementById('editInvoice').value = '';
- document.getElementById('editManual').value = '';
- document.getElementById('editOtherDocument').value = '';
- document.getElementById('editProductPhotoFileName').textContent = '';
- document.getElementById('editFileName').textContent = '';
- document.getElementById('editManualFileName').textContent = '';
- document.getElementById('editOtherDocumentFileName').textContent = '';
-
- // Reset photo preview
- const editPhotoPreview = document.getElementById('editProductPhotoPreview');
- if (editPhotoPreview) {
- editPhotoPreview.style.display = 'none';
- }
-
- // Set storage options based on current document storage
- if (paperlessNgxEnabled) {
- // Set product photo storage option
- const editProductPhotoStorageRadios = document.getElementsByName('editProductPhotoStorage');
- if (editProductPhotoStorageRadios.length > 0) {
- const isPaperlessPhoto = warranty.paperless_photo_id && warranty.paperless_photo_id !== null;
- editProductPhotoStorageRadios.forEach(radio => {
- radio.checked = isPaperlessPhoto ? (radio.value === 'paperless') : (radio.value === 'local');
- });
- }
-
- // Set invoice storage option
- const editInvoiceStorageRadios = document.getElementsByName('editInvoiceStorage');
- if (editInvoiceStorageRadios.length > 0) {
- const isPaperlessInvoice = warranty.paperless_invoice_id && warranty.paperless_invoice_id !== null;
- editInvoiceStorageRadios.forEach(radio => {
- radio.checked = isPaperlessInvoice ? (radio.value === 'paperless') : (radio.value === 'local');
- });
- }
-
- // Set manual storage option
- const editManualStorageRadios = document.getElementsByName('editManualStorage');
- if (editManualStorageRadios.length > 0) {
- const isPaperlessManual = warranty.paperless_manual_id && warranty.paperless_manual_id !== null;
- editManualStorageRadios.forEach(radio => {
- radio.checked = isPaperlessManual ? (radio.value === 'paperless') : (radio.value === 'local');
- });
- }
-
- // Set other document storage option
- const editOtherDocumentStorageRadios = document.getElementsByName('editOtherDocumentStorage');
- if (editOtherDocumentStorageRadios.length > 0) {
- const isPaperlessOther = warranty.paperless_other_id && warranty.paperless_other_id !== null;
- editOtherDocumentStorageRadios.forEach(radio => {
- radio.checked = isPaperlessOther ? (radio.value === 'paperless') : (radio.value === 'local');
- });
- }
-
- console.log('[Edit Modal] Storage options set based on current document storage:', {
- photo: warranty.paperless_photo_id ? 'paperless' : 'local',
- invoice: warranty.paperless_invoice_id ? 'paperless' : 'local',
- manual: warranty.paperless_manual_id ? 'paperless' : 'local',
- other: warranty.paperless_other_id ? 'paperless' : 'local'
- });
- }
-
- // Initialize file input event listeners
- const editProductPhotoInput = document.getElementById('editProductPhoto');
- if (editProductPhotoInput) {
- editProductPhotoInput.addEventListener('change', function(event) {
- updateFileName(event, 'editProductPhoto', 'editProductPhotoFileName');
- });
- }
-
- const editInvoiceInput = document.getElementById('editInvoice');
- if (editInvoiceInput) {
- editInvoiceInput.addEventListener('change', function(event) {
- updateFileName(event, 'editInvoice', 'editFileName');
- });
- }
-
- const editManualInput = document.getElementById('editManual');
- if (editManualInput) {
- editManualInput.addEventListener('change', function(event) {
- updateFileName(event, 'editManual', 'editManualFileName');
- });
- }
-
- const editOtherDocumentInput = document.getElementById('editOtherDocument');
- if (editOtherDocumentInput) {
- editOtherDocumentInput.addEventListener('change', function(event) {
- updateFileName(event, 'editOtherDocument', 'editOtherDocumentFileName');
- });
- }
-
- // Show edit modal
- const modalBackdrop = document.getElementById('editModal');
- if (modalBackdrop) {
- modalBackdrop.classList.add('active'); // Add active class to display as flex
- }
-
- // Reset tabs to first tab
- const editTabBtns = document.querySelectorAll('.edit-tab-btn');
- editTabBtns.forEach(btn => btn.classList.remove('active'));
- document.querySelector('.edit-tab-btn[data-tab="edit-product-info"]').classList.add('active');
-
- // Reset tab content
- document.querySelectorAll('.edit-tab-content').forEach(content => content.classList.remove('active'));
- document.getElementById('edit-product-info').classList.add('active');
-
- // Initialize edit mode tags
- editSelectedTags = [];
-
- // If warranty has tags, populate editSelectedTags
- if (warranty.tags && Array.isArray(warranty.tags)) {
- editSelectedTags = warranty.tags.map(tag => ({
- id: tag.id,
- name: tag.name,
- color: tag.color
- }));
- }
-
- // Render selected tags using the helper function
- renderEditSelectedTags();
-
- // Set up tag search in edit mode
- const editTagSearch = document.getElementById('editTagSearch');
- const editTagsList = document.getElementById('editTagsList');
-
- if (editTagSearch && editTagsList) {
- // Add event listeners for tag search
- editTagSearch.addEventListener('focus', () => {
- renderEditTagsList();
- editTagsList.classList.add('show');
- });
-
- editTagSearch.addEventListener('input', () => {
- renderEditTagsList(editTagSearch.value);
- });
-
- // Add event listener to close dropdown when clicking outside
- document.addEventListener('click', (e) => {
- if (!editTagSearch.contains(e.target) && !editTagsList.contains(e.target)) {
- editTagsList.classList.remove('show');
- }
- });
- }
-
- // Set up manage tags button in edit mode
- const editManageTagsBtn = document.getElementById('editManageTagsBtn');
- if (editManageTagsBtn) {
- editManageTagsBtn.addEventListener('click', (e) => {
- e.preventDefault();
- openTagManagementModal();
- });
- }
-
- // Validate all tabs to update completion indicators
- validateEditTab('edit-product-info');
- validateEditTab('edit-warranty-details');
- validateEditTab('edit-documents');
- validateEditTab('edit-tags');
-
- // Add input event listeners to update validation status
- document.querySelectorAll('#editWarrantyForm input').forEach(input => {
- input.addEventListener('input', function() {
- // Find the tab this input belongs to
- const tabContent = this.closest('.edit-tab-content');
- if (tabContent) {
- validateEditTab(tabContent.id);
- }
- });
- });
-
- // --- Set Lifetime Checkbox and Toggle Duration Fields ---
- if (editIsLifetimeCheckbox && editWarrantyDurationFields) {
- editIsLifetimeCheckbox.checked = warranty.is_lifetime || false;
- handleEditLifetimeChange(); // Call handler to set initial state
-
- // Remove previous listener if exists
- editIsLifetimeCheckbox.removeEventListener('change', handleEditLifetimeChange);
- // Add new listener
- editIsLifetimeCheckbox.addEventListener('change', handleEditLifetimeChange);
-
- // Set duration values only if NOT lifetime
- if (!warranty.is_lifetime) {
- document.getElementById('editWarrantyDurationYears').value = warranty.warranty_duration_years || 0;
- document.getElementById('editWarrantyDurationMonths').value = warranty.warranty_duration_months || 0;
- document.getElementById('editWarrantyDurationDays').value = warranty.warranty_duration_days || 0;
- } else {
- document.getElementById('editWarrantyDurationYears').value = '';
- document.getElementById('editWarrantyDurationMonths').value = '';
- document.getElementById('editWarrantyDurationDays').value = '';
- }
- } else {
- console.error("Lifetime warranty elements or duration fields not found in edit form");
- }
-
- // --- Set Warranty Method Selection ---
- if (editDurationMethodRadio && editExactDateMethodRadio && editExactExpirationDateInput) {
- console.log('[DEBUG Edit Modal] Warranty method detection:', {
- originalInputMethod: warranty.original_input_method,
- isLifetime: warranty.is_lifetime,
- expirationDate: warranty.expiration_date,
- warrantyDurationYears: warranty.warranty_duration_years,
- warrantyDurationMonths: warranty.warranty_duration_months,
- warrantyDurationDays: warranty.warranty_duration_days
- });
-
- // Use the original input method if available, otherwise fall back to previous logic
- if (!warranty.is_lifetime) {
- if (warranty.original_input_method === 'exact_date') {
- // Use exact date method
- editExactDateMethodRadio.checked = true;
- editDurationMethodRadio.checked = false;
- editExactExpirationDateInput.value = warranty.expiration_date.split('T')[0];
- console.log('[DEBUG Edit Modal] Selected exact date method based on original_input_method');
- } else {
- // Use duration method (either explicitly set or fallback)
- editDurationMethodRadio.checked = true;
- editExactDateMethodRadio.checked = false;
- editExactExpirationDateInput.value = '';
- console.log('[DEBUG Edit Modal] Selected duration method based on original_input_method or fallback');
- }
- }
-
- // Set up event listeners for warranty method change
- editDurationMethodRadio.removeEventListener('change', handleEditWarrantyMethodChange);
- editExactDateMethodRadio.removeEventListener('change', handleEditWarrantyMethodChange);
- editDurationMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
- editExactDateMethodRadio.addEventListener('change', handleEditWarrantyMethodChange);
-
- console.log('[DEBUG Edit Modal] Event listeners attached to warranty method radio buttons');
- console.log('[DEBUG Edit Modal] Initial radio states:', {
- durationChecked: editDurationMethodRadio.checked,
- exactDateChecked: editExactDateMethodRadio.checked
- });
-
- // Call handler to set initial state
- handleEditWarrantyMethodChange();
- }
-
- // Set notes
- const notesInput = document.getElementById('editNotes');
- if (notesInput) {
- notesInput.value = warranty.notes || '';
- }
-
- // Update currency symbols and positioning for the edit form
- const symbol = getCurrencySymbol();
- const position = getCurrencyPosition();
- updateFormCurrencyPosition(symbol, position);
-
- // Trigger currency positioning after modal is visible
- setTimeout(() => {
- if (position === 'right') {
- const editPriceInput = document.getElementById('editPurchasePrice');
- const editCurrencySymbol = document.getElementById('editCurrencySymbol');
- if (editPriceInput && editCurrencySymbol) {
- // Force update the currency position now that modal is visible
- const wrapper = editPriceInput.closest('.price-input-wrapper');
- if (wrapper && wrapper.classList.contains('currency-right')) {
- const updateEvent = new Event('focus');
- editPriceInput.dispatchEvent(updateEvent);
- const blurEvent = new Event('blur');
- editPriceInput.dispatchEvent(blurEvent);
- }
- }
- }
- }, 200);
-
- // Load secure images with authentication for the edit modal
- setTimeout(() => loadSecureImages(), 100); // Small delay to ensure DOM is updated
-}
-
-function openDeleteModal(warrantyId, productName) {
- currentWarrantyId = warrantyId;
- if (window.components && window.components.modals && window.components.modals.openDeleteModal) {
- window.components.modals.openDeleteModal(productName);
- return;
- }
- const deleteProductNameElement = document.getElementById('deleteProductName');
- if (deleteProductNameElement) deleteProductNameElement.textContent = productName || '';
- const deleteModal = document.getElementById('deleteModal');
- if (deleteModal) deleteModal.classList.add('active');
-}
-
-// Open Archive confirmation modal
-function openArchiveModal(warrantyId, productName) {
- currentWarrantyId = warrantyId;
- if (window.components && window.components.modals && window.components.modals.openArchiveModal) {
- window.components.modals.openArchiveModal(productName);
- return;
- }
- const archiveProductNameElement = document.getElementById('archiveProductName');
- if (archiveProductNameElement) archiveProductNameElement.textContent = productName || '';
- const archiveModal = document.getElementById('archiveModal');
- if (archiveModal) archiveModal.classList.add('active');
-}
-
-// Confirm archive handler
-async function confirmArchive() {
- if (!currentWarrantyId) {
- showToast('No warranty selected', 'error');
- return;
- }
- try {
- await toggleArchiveStatus(currentWarrantyId, true);
- closeModals();
- // Guidance toast for where to find archived items
- const guidance = 'You can find archived warranties by selecting "Archived" in Filters.';
- showToast(guidance, 'info');
- currentWarrantyId = null;
- } catch (e) {
- // toggleArchiveStatus already toasts on failure
- console.error('Archive failed', e);
- }
-}
-
-// Function to close all modals
-function closeModals() {
- document.querySelectorAll('.modal-backdrop').forEach(modal => {
- modal.classList.remove('active');
- });
-}
-
-// Validate file size before upload
-function validateFileSize(formData, maxSizeMB = 32) {
- let totalSize = 0;
-
- // Check file sizes
- if (formData.has('invoice') && formData.get('invoice').size > 0) {
- totalSize += formData.get('invoice').size;
- }
-
- if (formData.has('manual') && formData.get('manual').size > 0) {
- totalSize += formData.get('manual').size;
- }
-
- if (formData.has('other_document') && formData.get('other_document').size > 0) {
- totalSize += formData.get('other_document').size;
- }
-
- // Convert bytes to MB for comparison and display
- const totalSizeMB = totalSize / (1024 * 1024);
- console.log(`Total upload size: ${totalSizeMB.toFixed(2)} MB`);
-
- // Check if total size exceeds limit
- if (totalSizeMB > maxSizeMB) {
- return {
- valid: false,
- message: `Total file size (${totalSizeMB.toFixed(2)} MB) exceeds the maximum allowed size of ${maxSizeMB} MB. Please reduce file sizes.`
- };
- }
-
- return {
- valid: true
- };
-}
-
-// Submit form function - event handler for form submit
-async function handleFormSubmit(event) { // Made async to properly await paperless uploads
- event.preventDefault();
-
- const isLifetime = isLifetimeCheckbox.checked;
- const isDurationMethod = durationMethodRadio && durationMethodRadio.checked;
- const years = parseInt(warrantyDurationYearsInput.value || 0);
- const months = parseInt(warrantyDurationMonthsInput.value || 0);
- const days = parseInt(warrantyDurationDaysInput.value || 0);
- const exactDate = exactExpirationDateInput ? exactExpirationDateInput.value : '';
-
- // --- Updated Lifetime and Method Check ---
- if (!isLifetime) {
- if (isDurationMethod) {
- // Validate duration fields
- if (years === 0 && months === 0 && days === 0) {
- showValidationErrors(1);
- switchToTab(1); // Switch to warranty details tab
- // Optionally focus the first duration input
- if (warrantyDurationYearsInput) warrantyDurationYearsInput.focus();
- // Add invalid class to the container or individual inputs if needed
- if (warrantyDurationFields) warrantyDurationFields.classList.add('invalid-duration'); // Example
- return;
- }
- } else {
- // Validate exact expiration date
- if (!exactDate) {
- showValidationErrors(1);
- switchToTab(1); // Switch to warranty details tab
- if (exactExpirationDateInput) exactExpirationDateInput.focus();
- return;
- }
-
- // Validate that expiration date is in the future relative to purchase date
- const purchaseDate = document.getElementById('purchaseDate').value;
- if (purchaseDate && exactDate <= purchaseDate) {
- showToast(window.t('messages.expiration_date_after_purchase_date'), 'error');
- switchToTab(1);
- if (exactExpirationDateInput) exactExpirationDateInput.focus();
- return;
- }
- }
- }
-
- // Remove invalid duration class if validation passes
- if (warrantyDurationFields) warrantyDurationFields.classList.remove('invalid-duration');
-
- // Validate all tabs
- for (let i = 0; i < tabContents.length; i++) {
- if (!validateTab(i)) {
- // Switch to the first invalid tab
- switchToTab(i);
- showValidationErrors(i);
- return;
- }
- }
-
- // Create form data object
- const formData = new FormData(warrantyForm);
- // Ensure model_number is included if present
- const modelNumberInput = document.getElementById('modelNumber');
- if (modelNumberInput && modelNumberInput.value.trim() !== '') {
- formData.set('model_number', modelNumberInput.value.trim());
- }
-
- // Handle warranty type - use custom value if "other" is selected
- const warrantyTypeSelect = document.getElementById('warrantyType');
- const warrantyTypeCustom = document.getElementById('warrantyTypeCustom');
- if (warrantyTypeSelect && warrantyTypeSelect.value === 'other' && warrantyTypeCustom && warrantyTypeCustom.value.trim()) {
- formData.set('warranty_type', warrantyTypeCustom.value.trim());
- }
-
- // Debug: Log all form data entries
- console.log('=== DEBUG: Form Data Contents ===');
- for (let [key, value] of formData.entries()) {
- console.log(`${key}: ${value}`);
- }
- console.log('=== END DEBUG ===');
-
- // Product URL handling
- let productUrlValue = formData.get('product_url');
- if (productUrlValue && typeof productUrlValue === 'string') {
- productUrlValue = productUrlValue.trim();
- if (productUrlValue && !productUrlValue.startsWith('http://') && !productUrlValue.startsWith('https://')) {
- formData.set('product_url', 'https://' + productUrlValue);
- } else if (productUrlValue) {
- // Ensure trimmed value is set back if it was already valid
- formData.set('product_url', productUrlValue);
- }
- }
-
- // Remove old warranty_years if it exists in formData (it shouldn't if HTML is correct)
- formData.delete('warranty_years');
-
- // Append new duration fields (already handled by FormData constructor if names match)
- // formData.append('warranty_duration_years', years);
- // formData.append('warranty_duration_months', months);
- // formData.append('warranty_duration_days', days);
-
- // Add serial numbers to form data (using correct name 'serial_numbers[]')
- const serialInputs = document.querySelectorAll('#serialNumbersContainer input[name="serial_numbers[]"]');
- // Clear existing serial_numbers[] from formData before appending new ones
- formData.delete('serial_numbers[]');
- serialInputs.forEach(input => {
- if (input.value.trim()) {
- formData.append('serial_numbers[]', input.value.trim()); // Use [] for arrays
- }
- });
-
- // Add tag IDs to form data as JSON string
- if (selectedTags && selectedTags.length > 0) {
- const tagIds = selectedTags.map(tag => tag.id);
- formData.append('tag_ids', JSON.stringify(tagIds));
- } else {
- formData.append('tag_ids', JSON.stringify([])); // Send empty array if no tags
- }
-
- // Add URL fields for documents (with null checks)
- const invoiceUrlField = document.getElementById('invoiceUrl');
- formData.append('invoice_url', invoiceUrlField ? invoiceUrlField.value || '' : '');
-
- const manualUrlField = document.getElementById('manualUrl');
- formData.append('manual_url', manualUrlField ? manualUrlField.value || '' : '');
-
- const otherDocumentUrlField = document.getElementById('otherDocumentUrl');
- formData.append('other_document_url', otherDocumentUrlField ? otherDocumentUrlField.value || '' : '');
-
- // --- Ensure is_lifetime is correctly added ---
- // FormData already includes it if the checkbox is checked. If not checked, it's omitted.
- // We need to explicitly add 'false' if it's not checked.
- if (!isLifetimeCheckbox.checked) {
- formData.append('is_lifetime', 'false');
-
- // Add warranty method and exact expiration date if using exact date method
- if (!isDurationMethod && exactDate) {
- formData.append('exact_expiration_date', exactDate);
- // Ensure duration fields are 0 when using exact date
- formData.set('warranty_duration_years', '0');
- formData.set('warranty_duration_months', '0');
- formData.set('warranty_duration_days', '0');
- }
- } else {
- // Ensure duration fields are 0 if lifetime is checked
- formData.set('warranty_duration_years', '0');
- formData.set('warranty_duration_months', '0');
- formData.set('warranty_duration_days', '0');
- }
-
- // Add other_document file (always, as no storage selection for this)
- const otherDocumentFile = document.getElementById('otherDocument').files[0];
- if (otherDocumentFile) {
- formData.append('other_document', otherDocumentFile);
- }
-
- // --- Only append invoice/manual files to FormData if storage is 'local' ---
- const invoiceFile = document.getElementById('invoice')?.files[0];
- const manualFile = document.getElementById('manual')?.files[0];
- let invoiceStorage = 'local';
- let manualStorage = 'local';
- const invoiceStorageRadio = document.querySelector('input[name="invoiceStorage"]:checked');
- const manualStorageRadio = document.querySelector('input[name="manualStorage"]:checked');
- if (invoiceStorageRadio) invoiceStorage = invoiceStorageRadio.value;
- if (manualStorageRadio) manualStorage = manualStorageRadio.value;
- formData.set('invoiceStorage', invoiceStorage);
- formData.set('manualStorage', manualStorage);
- console.log('[DEBUG] Invoice storage:', invoiceStorage, 'Manual storage:', manualStorage);
- console.log('[DEBUG] Invoice file:', invoiceFile);
- console.log('[DEBUG] Manual file:', manualFile);
- if (invoiceStorage === 'local' && invoiceFile) {
- console.log('[DEBUG] Appending invoice file to FormData (local storage)');
- formData.append('invoice', invoiceFile);
- }
- if (manualStorage === 'local' && manualFile) {
- console.log('[DEBUG] Appending manual file to FormData (local storage)');
- formData.append('manual', manualFile);
- }
- if (invoiceStorage === 'paperless') {
- console.log('[DEBUG] Invoice should be uploaded to Paperless-ngx');
- }
- if (manualStorage === 'paperless') {
- console.log('[DEBUG] Manual should be uploaded to Paperless-ngx');
- }
-
- // Add selected Paperless documents (for linking existing docs, not uploads)
- const selectedPaperlessProductPhoto = document.getElementById('selectedPaperlessProductPhoto');
- const selectedPaperlessInvoice = document.getElementById('selectedPaperlessInvoice');
- const selectedPaperlessManual = document.getElementById('selectedPaperlessManual');
- const selectedPaperlessOtherDocument = document.getElementById('selectedPaperlessOtherDocument');
- if (selectedPaperlessProductPhoto && selectedPaperlessProductPhoto.value) {
- formData.append('paperless_photo_id', selectedPaperlessProductPhoto.value);
- }
- if (selectedPaperlessInvoice && selectedPaperlessInvoice.value) {
- formData.append('paperless_invoice_id', selectedPaperlessInvoice.value);
- }
- if (selectedPaperlessManual && selectedPaperlessManual.value) {
- formData.append('paperless_manual_id', selectedPaperlessManual.value);
- }
- if (selectedPaperlessOtherDocument && selectedPaperlessOtherDocument.value) {
- formData.append('paperless_other_id', selectedPaperlessOtherDocument.value);
- }
-
- // Show loading spinner
- showLoadingSpinner();
-
- try {
- // Process Paperless-ngx uploads if enabled
- const paperlessUploads = await processPaperlessNgxUploads(formData);
-
- // Add Paperless-ngx document IDs to form data
- Object.keys(paperlessUploads).forEach(key => {
- formData.append(key, paperlessUploads[key]);
- });
-
- // Send the form data to the server
- const response = await fetch('/api/warranties', {
- method: 'POST',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
- },
- body: formData
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.error || 'Failed to add warranty');
- }
-
- const data = await response.json();
- hideLoadingSpinner();
- showToast(window.t('messages.warranty_added_successfully'), 'success');
-
- // Store the new warranty ID for auto-linking
- const newWarrantyId = data.id;
-
- // --- Store file info and storage type before upload for auto-link logic ---
- const invoiceFileInput = document.getElementById('invoice');
- const manualFileInput = document.getElementById('manual');
- const invoiceFilePre = invoiceFileInput?.files[0];
- const manualFilePre = manualFileInput?.files[0];
- const invoiceStoragePre = formData.get('invoiceStorage');
- const manualStoragePre = formData.get('manualStorage');
-
- // Auto-link any documents that were uploaded to Paperless-ngx (match edit modal behavior)
- const autoLinkTypes = [];
- const fileInfo = {};
- if (invoiceStoragePre === 'paperless' && invoiceFilePre) {
- autoLinkTypes.push('invoice');
- fileInfo.invoice = invoiceFilePre.name;
- }
- if (manualStoragePre === 'paperless' && manualFilePre) {
- autoLinkTypes.push('manual');
- fileInfo.manual = manualFilePre.name;
- }
- // Other document does not have a storage option, so skip unless you add support
- // If you want to support auto-linking for 'other', add logic here
- console.log('[Auto-Link DEBUG] newWarrantyId:', newWarrantyId, 'autoLinkTypes:', autoLinkTypes, 'fileInfo:', fileInfo, 'invoiceStorage:', invoiceStoragePre, 'manualStorage:', manualStoragePre);
- if (autoLinkTypes.length > 0 && newWarrantyId) {
- console.log('[Auto-Link] Starting automatic document linking after warranty creation (Paperless-ngx uploads only)', autoLinkTypes, fileInfo);
- setTimeout(() => {
- console.log('[Auto-Link DEBUG] Calling autoLinkRecentDocuments with:', newWarrantyId, autoLinkTypes, fileInfo);
- autoLinkRecentDocuments(newWarrantyId, autoLinkTypes, 10, 10000, fileInfo);
- }, 3000); // Wait 3 seconds for Paperless-ngx to process the documents
- }
-
- // Close and reset the modal on success
- if (addWarrantyModal) {
- addWarrantyModal.classList.remove('active');
- }
- resetAddWarrantyWizard(); // Reset the wizard form
-
- try {
- await loadWarranties(true);
- console.log('Warranties reloaded after adding new warranty');
- applyFilters();
-
- // Load secure images for the new cards
- setTimeout(() => {
- console.log('Loading secure images for new warranty cards');
- loadSecureImages();
- }, 200);
- } catch (error) {
- console.error('Error reloading warranties after adding:', error);
- }
- } catch (error) {
- hideLoadingSpinner();
- console.error('Error adding warranty:', error);
- showToast(error.message || window.t('messages.failed_to_add_warranty'), 'error');
- }
-}
-
-// Initialize page
-document.addEventListener('DOMContentLoaded', function() {
- // Initialize the warranty form *only* if the form element exists
- if (warrantyForm) {
- initWarrantyForm();
- }
-
- // Load warranties (might need checks if warrantiesList doesn't always exist)
- if (warrantiesList) {
- // REMOVED: loadWarranties(); // Now called after authStateReady
- // REMOVED: loadViewPreference(); // Now called after authStateReady
- loadTags(); // Load tags for the form
- initTagFunctionality(); // Initialize tag search/selection
- }
-
- // Initialize theme (should be safe on all pages)
- initializeTheme();
-
- // Set up event listeners for other UI controls (should contain checks)
- setupUIEventListeners();
- setupModalTriggers(); // Add the new modal listeners
-
- // Check if user is logged in and update UI
- // checkLoginStatus(); // Removed undefined function
-
- // Setup form submission
- const form = document.getElementById('addWarrantyForm');
- if (form) {
- form.addEventListener('submit', handleFormSubmit); // Use renamed handler
- }
-
- // Setup settings menu toggle
- // setupSettingsMenu(); // Removed: function not defined, handled by auth.js
-
- // Initialize theme toggle state *after* DOM is loaded
- // Find the header toggle (assuming ID 'darkModeToggle')
- const headerToggle = document.getElementById('darkModeToggle');
- if (headerToggle) {
- // Set initial state based on theme applied by theme-loader.js
- const currentTheme = document.documentElement.getAttribute('data-theme');
- headerToggle.checked = currentTheme === 'dark';
-
- // Add listener to update theme when toggled
- headerToggle.addEventListener('change', function() {
- setTheme(this.checked);
- });
- }
-
- // REMOVE any direct calls to initializeTheme() from here or globally
- // initializeTheme();
-
- // Setup view switcher
- // setupViewSwitcher(); // Removed undefined function
-
- // Setup filter controls
- // setupFilterControls(); // Removed: function not defined
-
- // Setup form tabs and navigation
- // initFormTabs(); // <-- Remove this line from DOMContentLoaded
-
- // Initialize modal interactions
- // initializeModals(); // Removed: function not defined, handled by setupModalTriggers
-
- // Load preferences (if needed for things other than theme)
- // loadPreferences(); // Consider if needed
-
- // REMOVED: updateCurrencySymbols(); // Now called after authStateReady
-
- // Initialize claims functionality
- initClaimsEventListeners();
-});
-
-// ====== WARRANTY CLAIMS FUNCTIONALITY ======
-
-// Global variables for claims
-let currentClaimsWarrantyId = null;
-let currentClaims = [];
-let currentClaimsCanEdit = false; // Track if current user can edit the warranty being viewed
-
-/**
- * Initialize claims event listeners
- */
-function initClaimsEventListeners() {
- // Event delegation for claims links
- if (warrantiesList) {
- warrantiesList.addEventListener('click', (e) => {
- if (e.target.closest('.claims-link')) {
- e.preventDefault();
- const warrantyId = parseInt(e.target.closest('.claims-link').dataset.id);
- openClaimsModal(warrantyId);
- return;
- }
- // Archive button
- if (e.target.closest('.archive-btn')) {
- e.preventDefault();
- const el = e.target.closest('.archive-btn');
- const warrantyId = parseInt(el.dataset.id);
- const card = el.closest('.warranty-card');
- const titleEl = card ? card.querySelector('.product-name-header .warranty-title') : null;
- const productName = titleEl ? titleEl.textContent.trim() : '';
- openArchiveModal(warrantyId, productName);
- return;
- }
- // Unarchive button
- if (e.target.closest('.unarchive-btn')) {
- e.preventDefault();
- const warrantyId = parseInt(e.target.closest('.unarchive-btn').dataset.id);
- toggleArchiveStatus(warrantyId, false);
- return;
- }
- });
- }
-
- // Add claim button
- if (addClaimBtn) {
- addClaimBtn.addEventListener('click', () => {
- openClaimFormModal();
- });
- }
-
- // Claim form submission
- if (claimForm) {
- claimForm.addEventListener('submit', handleClaimFormSubmit);
- }
-
- // Modal close handling - Removed backdrop click listeners to match warranty modal behavior
- // Claims modals now only close via explicit close buttons with [data-dismiss="modal"]
- // The general modal click prevention (e.stopPropagation) handles preventing backdrop clicks
-
- // Add event listeners for claims modal close buttons
- if (claimsModal) {
- claimsModal.querySelectorAll('[data-dismiss="modal"]').forEach(closeBtn => {
- closeBtn.addEventListener('click', () => {
- closeClaimsModal();
- });
- });
- }
-
- if (claimFormModal) {
- claimFormModal.querySelectorAll('[data-dismiss="modal"]').forEach(closeBtn => {
- closeBtn.addEventListener('click', () => {
- closeClaimFormModal();
- });
- });
- }
-}
-
-/**
- * Open the claims modal for a specific warranty
- */
-async function openClaimsModal(warrantyId) {
- try {
- currentClaimsWarrantyId = warrantyId;
-
- // Find warranty info
- const warranty = warranties.find(w => w.id === warrantyId);
- if (!warranty) {
- showToast(window.i18next ? window.i18next.t('claims.warranty_not_found') : 'Warranty not found', 'error');
- return;
- }
-
- // Determine if current user can edit this warranty
- const currentUserId = (() => {
- try {
- const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
- return userInfo.id;
- } catch (e) {
- return null;
- }
- })();
- const isAdmin = getUserType() === 'admin';
- currentClaimsCanEdit = !isGlobalView || (warranty.user_id === currentUserId) || isAdmin;
-
- // Show/hide the Add New Claim button based on edit permissions
- if (addClaimBtn) {
- addClaimBtn.style.display = currentClaimsCanEdit ? 'inline-block' : 'none';
- }
-
- // Update warranty info in modal
- if (warrantyClaimInfo) {
- if (window.components && window.components.claims && window.components.claims.renderWarrantyInfo) {
- window.components.claims.renderWarrantyInfo(warrantyClaimInfo, warranty, formatDate);
- } else {
- warrantyClaimInfo.innerHTML = `
- <div class="warranty-info-card">
- <h4>${warranty.product_name || 'Unnamed Product'}</h4>
- <div class="warranty-details">
- <span><i class="fas fa-building"></i> ${warranty.vendor || 'Unknown Vendor'}</span>
- <span><i class="fas fa-calendar"></i> Expires: ${formatDate(warranty.expiration_date ? new Date(warranty.expiration_date) : null)}</span>
- <span class="warranty-status status-${warranty.status || 'unknown'}">
- ${warranty.statusText || 'Unknown Status'}
- </span>
- </div>
- </div>
- `;
- }
- }
-
- // Show modal
- claimsModal.classList.add('active');
-
- // Load claims
- await loadClaims(warrantyId);
-
- } catch (error) {
- console.error('Error opening claims modal:', error);
- showToast('Failed to open claims modal', 'error');
- }
-}
-
-/**
- * Load claims for a warranty
- */
-async function loadClaims(warrantyId) {
- try {
- // Show loading
- if (claimsListBody) {
- if (window.components && window.components.claims && window.components.claims.renderClaimsLoading) {
- window.components.claims.renderClaimsLoading(claimsListBody);
- } else {
- claimsListBody.innerHTML = `
- <div class="loading-message" style="text-align: center; padding: 20px;">
- <i class="fas fa-spinner fa-spin"></i> Loading claims...
- </div>
- `;
- }
- }
-
- // Fetch claims
- const response = await fetch(`/api/warranties/${warrantyId}/claims`, {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- throw new Error('Failed to load claims');
- }
-
- currentClaims = await response.json();
- renderClaims();
-
- } catch (error) {
- console.error('Error loading claims:', error);
- if (claimsListBody) {
- if (window.components && window.components.claims && window.components.claims.renderClaimsError) {
- window.components.claims.renderClaimsError(claimsListBody, window.i18next ? window.i18next.t('claims.failed_to_load') : 'Failed to load claims');
- } else {
- claimsListBody.innerHTML = `
- <div class="error-message" style="text-align: center; padding: 20px; color: var(--danger-color);">
- <i class="fas fa-exclamation-triangle"></i> Failed to load claims
- </div>
- `;
- }
- }
- }
-}
-
-/**
- * Render claims list
- */
-function renderClaims() {
- if (!claimsListBody) return;
-
- if (currentClaims.length === 0) {
- if (window.components && window.components.claims && window.components.claims.renderClaimsList) {
- window.components.claims.renderClaimsList(claimsListBody, [], currentClaimsCanEdit, formatDate);
- } else {
- const noClaimsMessage = currentClaimsCanEdit
- ? (window.i18next ? window.i18next.t('claims.no_claims_message') : 'Click "Add New Claim" to get started')
- : 'No claims have been filed for this warranty';
- claimsListBody.innerHTML = `
- <div class="no-claims-message" style="text-align: center; padding: 40px;">
- <i class="fas fa-clipboard-list" style="font-size: 3rem; color: var(--medium-gray); margin-bottom: 1rem;"></i>
- <h4 style="color: var(--text-color); margin-bottom: 0.5rem;">${window.i18next ? window.i18next.t('claims.no_claims_yet') : 'No Claims Yet'}</h4>
- <p style="color: var(--dark-gray); margin-bottom: 0;">${noClaimsMessage}</p>
- </div>
- `;
- }
- return;
- }
-
- if (window.components && window.components.claims && window.components.claims.renderClaimsList) {
- window.components.claims.renderClaimsList(claimsListBody, currentClaims, currentClaimsCanEdit, formatDate);
- } else {
- let claimsHtml = '';
- currentClaims.forEach(claim => {
- claimsHtml += `
- <div class="claim-item" data-claim-id="${claim.id}">
- <div class="claim-header">
- <div class="claim-info">
- <div class="claim-title">
- ${claim.claim_number ? `<strong>${claim.claim_number}</strong>` : `<strong>Claim #${claim.id}</strong>`}
- <span class="claim-status-badge claim-status-${claim.status.toLowerCase().replace(' ', '-')}">
- ${claim.status}
- </span>
- </div>
- <div class="claim-date">
- <i class="fas fa-calendar"></i> ${formatDate(claim.claim_date ? new Date(claim.claim_date) : null)}
- ${claim.resolution_date && claim.resolution_date.trim() ? `<span style=\"margin-left: 10px;\"><i class=\"fas fa-check-circle\"></i> Resolved: ${formatDate(new Date(claim.resolution_date))}</span>` : ''}
- </div>
- </div>
- <div class="claim-actions">
- ${currentClaimsCanEdit ? `
- <button class="btn btn-sm btn-secondary edit-claim-btn" data-claim-id="${claim.id}">
- <i class="fas fa-edit"></i> Edit
- </button>
- <button class="btn btn-sm btn-danger delete-claim-btn" data-claim-id="${claim.id}">
- <i class="fas fa-trash"></i> Delete
- </button>
- ` : `
- <span class="claim-readonly-indicator" style="color: var(--medium-gray); font-size: 0.9em;">
- <i class="fas fa-eye"></i> View Only
- </span>
- `}
- </div>
- </div>
- ${claim.description ? `<div class=\"claim-description\">${escapeHtml(claim.description)}</div>` : ''}
- ${claim.resolution ? `<div class=\"claim-resolution\"><strong>Resolution:</strong> ${escapeHtml(claim.resolution)}</div>` : ''}
- </div>
- `;
- });
- claimsListBody.innerHTML = claimsHtml;
- }
-
- // Add event listeners for edit and delete buttons (only if user can edit)
- if (currentClaimsCanEdit) {
- claimsListBody.addEventListener('click', (e) => {
- if (e.target.closest('.edit-claim-btn')) {
- const claimId = parseInt(e.target.closest('.edit-claim-btn').dataset.claimId);
- const claim = currentClaims.find(c => c.id === claimId);
- if (claim) {
- openClaimFormModal(claim);
- }
- }
-
- if (e.target.closest('.delete-claim-btn')) {
- const claimId = parseInt(e.target.closest('.delete-claim-btn').dataset.claimId);
- if (confirm(window.i18next ? window.i18next.t('claims.confirm_delete_claim') : 'Are you sure you want to delete this claim?')) {
- deleteClaim(claimId);
- }
- }
- });
- }
-}
-
-/**
- * Open claim form modal for adding or editing
- */
-function openClaimFormModal(claim = null) {
- if (!claimFormModal) return;
-
- // Update title
- if (claimFormTitle) {
- claimFormTitle.textContent = claim ? (window.i18next ? window.i18next.t('claims.edit_claim') : 'Edit Claim') : (window.i18next ? window.i18next.t('claims.add_new_claim') : 'Add New Claim');
- }
-
- // Reset form
- if (claimForm) {
- claimForm.reset();
- }
-
- if (claim) {
- // Populate form with claim data
- if (editClaimId) editClaimId.value = claim.id;
- if (document.getElementById('claimDate')) document.getElementById('claimDate').value = claim.claim_date || '';
- if (document.getElementById('claimStatus')) document.getElementById('claimStatus').value = claim.status;
- if (document.getElementById('claimNumber')) document.getElementById('claimNumber').value = claim.claim_number || '';
- if (document.getElementById('claimDescription')) document.getElementById('claimDescription').value = claim.description || '';
- if (document.getElementById('claimResolution')) document.getElementById('claimResolution').value = claim.resolution || '';
- if (document.getElementById('resolutionDate')) document.getElementById('resolutionDate').value = claim.resolution_date || '';
- } else {
- // Set default values for new claim
- if (editClaimId) editClaimId.value = '';
- if (document.getElementById('claimDate')) document.getElementById('claimDate').value = new Date().toISOString().split('T')[0];
- if (document.getElementById('claimStatus')) document.getElementById('claimStatus').value = 'Submitted';
- }
-
- // Show modal
- claimFormModal.classList.add('active');
-}
-
-/**
- * Handle claim form submission
- */
-async function handleClaimFormSubmit(event) {
- event.preventDefault();
-
- try {
- const formData = new FormData(claimForm);
- const claimId = editClaimId.value;
-
- const claimData = {
- claim_date: formData.get('claim_date'),
- status: formData.get('status'),
- claim_number: formData.get('claim_number'),
- description: formData.get('description'),
- resolution: formData.get('resolution'),
- resolution_date: formData.get('resolution_date')
- };
-
- // Remove empty strings
- Object.keys(claimData).forEach(key => {
- if (claimData[key] === '') {
- claimData[key] = null;
- }
- });
-
- const isEdit = claimId && claimId !== '';
- const url = isEdit
- ? `/api/warranties/${currentClaimsWarrantyId}/claims/${claimId}`
- : `/api/warranties/${currentClaimsWarrantyId}/claims`;
- const method = isEdit ? 'PUT' : 'POST';
-
- const response = await fetch(url, {
- method: method,
- headers: {
- 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(claimData)
- });
-
- if (!response.ok) {
- const error = await response.json();
- throw new Error(error.error || 'Failed to save claim');
- }
-
- showToast(isEdit ? (window.i18next ? window.i18next.t('claims.claim_updated_successfully') : 'Claim updated successfully') : (window.i18next ? window.i18next.t('claims.claim_created_successfully') : 'Claim created successfully'), 'success');
- closeClaimFormModal();
-
- // Reload claims
- await loadClaims(currentClaimsWarrantyId);
-
- } catch (error) {
- console.error('Error saving claim:', error);
- showToast(error.message || 'Failed to save claim', 'error');
- }
-}
-
-/**
- * Delete a claim
- */
-async function deleteClaim(claimId) {
- try {
- const response = await fetch(`/api/warranties/${currentClaimsWarrantyId}/claims/${claimId}`, {
- method: 'DELETE',
- headers: {
- 'Authorization': 'Bearer ' + (window.auth ? window.auth.getToken() : localStorage.getItem('auth_token')),
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- const error = await response.json();
- throw new Error(error.error || 'Failed to delete claim');
- }
-
- showToast(window.i18next ? window.i18next.t('claims.claim_deleted_successfully') : 'Claim deleted successfully', 'success');
-
- // Reload claims
- await loadClaims(currentClaimsWarrantyId);
-
- } catch (error) {
- console.error('Error deleting claim:', error);
- showToast(error.message || 'Failed to delete claim', 'error');
- }
-}
-
-/**
- * Close claims modal
- */
-function closeClaimsModal() {
- if (claimsModal) {
- claimsModal.classList.remove('active');
- }
- currentClaimsWarrantyId = null;
- currentClaims = [];
- currentClaimsCanEdit = false;
-}
-
-/**
- * Close claim form modal
- */
-function closeClaimFormModal() {
- if (claimFormModal) {
- claimFormModal.classList.remove('active');
- }
-}
-
-/**
- * Escape HTML to prevent XSS
- */
-function escapeHtml(text) {
- if (!text) return '';
- const div = document.createElement('div');
- div.textContent = text;
- return div.innerHTML;
-}
-
-// Add this function to handle edit tab functionality
-function initEditTabs() {
- const editTabBtns = document.querySelectorAll('.edit-tab-btn');
-
- editTabBtns.forEach(btn => {
- btn.addEventListener('click', () => {
- // Remove active class from all tabs
- editTabBtns.forEach(b => b.classList.remove('active'));
-
- // Add active class to clicked tab
- btn.classList.add('active');
-
- // Hide all tab content
- document.querySelectorAll('.edit-tab-content').forEach(content => {
- content.classList.remove('active');
- });
-
- // Show the selected tab content
- const tabId = btn.getAttribute('data-tab');
- document.getElementById(tabId).classList.add('active');
- });
- });
-}
-
-// Update validateEditTabs function
-function validateEditTab(tabId) {
- const tab = document.getElementById(tabId);
- if (!tab) {
- console.warn('validateEditTab: Could not find tab with ID:', tabId);
- return false; // Or true, depending on desired behavior for missing tabs
- }
- let isTabValid = true;
-
- // Get all relevant form controls within the tab
- const controls = tab.querySelectorAll('input, textarea, select');
-
- controls.forEach(control => {
- // Check the native HTML5 validity state
- if (!control.validity.valid) {
- isTabValid = false;
- control.classList.add('invalid');
- // Optionally, you could add logic here to display specific messages
- // or rely on browser default behavior if the form is submitted.
- } else {
- control.classList.remove('invalid');
- }
- });
-
- // Update the tab button to show completion status
- const tabBtn = document.querySelector(`.edit-tab-btn[data-tab="${tabId}"]`);
- if (tabBtn) {
- if (isTabValid) {
- tabBtn.classList.add('completed');
- } else {
- tabBtn.classList.remove('completed');
- }
- }
- return isTabValid;
-}
-
-// Add this function for secure file access
-function openSecureFile(filePath) {
- console.log(`[openSecureFile] Opening file: ${filePath}`);
-
- // Get the file name from the path, handling both uploads/ prefix and direct filenames
- let fileName = filePath;
- if (filePath.startsWith('uploads/')) {
- fileName = filePath.substring(8); // Remove 'uploads/' prefix
- } else if (filePath.startsWith('/uploads/')) {
- fileName = filePath.substring(9); // Remove '/uploads/' prefix
- }
-
- console.log(`[openSecureFile] Processed filename: ${fileName}`);
-
- const token = auth.getToken();
-
- if (!token) {
- showToast(window.t('messages.login_to_access_files'), 'error');
- return false;
- }
-
- // Enhanced fetch with retry logic and better error handling
- const fetchWithRetry = async (url, options, retries = 2) => {
- for (let i = 0; i <= retries; i++) {
- try {
- console.log(`[openSecureFile] Attempt ${i + 1} to fetch: ${url}`);
- const response = await fetch(url, options);
-
- if (!response.ok) {
- if (response.status === 401) {
- throw new Error('Authentication error. Please log in again.');
- } else if (response.status === 403) {
- throw new Error('You are not authorized to access this file.');
- } else if (response.status === 404) {
- throw new Error('File not found. It may have been deleted.');
- } else {
- throw new Error(`Server error: ${response.status} ${response.statusText}`);
- }
- }
-
- // Check if response has content-length header
- const contentLength = response.headers.get('content-length');
- console.log(`[openSecureFile] Response Content-Length: ${contentLength}`);
-
- // Convert to blob with error handling
- const blob = await response.blob();
- console.log(`[openSecureFile] Blob size: ${blob.size} bytes`);
-
- // Verify blob size matches content-length if available
- if (contentLength && parseInt(contentLength) !== blob.size) {
- console.warn(`[openSecureFile] Content-Length mismatch: header=${contentLength}, blob=${blob.size}`);
- if (i < retries) {
- console.log(`[openSecureFile] Retrying due to content-length mismatch...`);
- await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second before retry
- continue;
- } else {
- console.error(`[openSecureFile] Final attempt failed with content-length mismatch`);
- }
- }
-
- return blob;
-
- } catch (error) {
- console.error(`[openSecureFile] Attempt ${i + 1} failed:`, error);
-
- // If this is a content-length mismatch or network error, retry
- if (i < retries && (
- error.message.includes('content-length') ||
- error.message.includes('Failed to fetch') ||
- error.name === 'TypeError'
- )) {
- console.log(`[openSecureFile] Retrying after error: ${error.message}`);
- await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); // Exponential backoff
- continue;
- }
-
- throw error;
- }
- }
- };
-
- fetchWithRetry(`/api/secure-file/${fileName}`, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Cache-Control': 'no-cache, no-store, must-revalidate',
- 'Pragma': 'no-cache'
- }
- })
- .then(blob => {
- console.log(`[openSecureFile] Successfully received blob of size: ${blob.size}`);
-
- // Create a URL for the blob
- const blobUrl = window.URL.createObjectURL(blob);
-
- // Open in new tab
- const newWindow = window.open(blobUrl, '_blank');
-
- // Clean up the blob URL after a delay to prevent memory leaks
- setTimeout(() => {
- window.URL.revokeObjectURL(blobUrl);
- }, 10000); // Clean up after 10 seconds
-
- // Check if window was blocked by popup blocker
- if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {
- showToast(window.t('messages.popup_blocked'), 'warning');
- window.URL.revokeObjectURL(blobUrl); // Clean up immediately if blocked
- }
- })
- .catch(error => {
- console.error('Error fetching file:', error);
-
- // Provide more specific error messages
- let errorMessage = 'Error opening file';
- if (error.message.includes('Authentication')) {
- errorMessage = 'Authentication error. Please refresh and try again.';
- } else if (error.message.includes('authorized')) {
- errorMessage = 'You are not authorized to access this file.';
- } else if (error.message.includes('not found')) {
- errorMessage = 'File not found. It may have been deleted.';
- } else if (error.message.includes('Failed to fetch') || error.name === 'TypeError') {
- errorMessage = 'Network error. Please check your connection and try again.';
- } else {
- errorMessage = `Error opening file: ${error.message}`;
- }
-
- showToast(errorMessage, 'error');
- });
-
- return false;
-}
-
-/**
- * Open a Paperless-ngx document by ID
- */
-
-/**
- * Generate document link HTML for both local and Paperless-ngx documents
- */
-function generateDocumentLink(warranty, docType) {
- const docConfig = {
- invoice: {
- localPath: warranty.invoice_path,
- paperlessId: warranty.paperless_invoice_id,
- url: warranty.invoice_url,
- icon: 'fas fa-file-invoice',
- label: 'Invoice',
- className: 'invoice-link'
- },
- manual: {
- localPath: warranty.manual_path,
- paperlessId: warranty.paperless_manual_id,
- url: warranty.manual_url,
- icon: 'fas fa-book',
- label: 'Manual',
- className: 'manual-link'
- },
- other: {
- localPath: warranty.other_document_path,
- paperlessId: warranty.paperless_other_id,
- url: warranty.other_document_url,
- icon: 'fas fa-file-alt',
- label: 'Files',
- className: 'other-document-link'
- },
- photo: {
- localPath: warranty.product_photo_path,
- paperlessId: warranty.paperless_photo_id,
- url: null, // Photos don't have URLs
- icon: 'fas fa-image',
- label: 'Photo',
- className: 'photo-link'
- }
- };
-
- const config = docConfig[docType];
- if (!config) return '';
-
- // Check Global View permissions for "other" documents
- if (docType === 'other' && isGlobalView) {
- // Get current user ID to check warranty ownership
- const currentUserId = (() => {
- try {
- const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
- return userInfo.id;
- } catch (e) {
- return null;
- }
- })();
-
- const isAdmin = getUserType() === 'admin';
- const canViewOtherDocs = !isGlobalView || (warranty.user_id === currentUserId) || isAdmin;
-
- // Hide "other" documents in Global View unless user owns the warranty or is admin
- if (!canViewOtherDocs) {
- return '';
- }
- }
-
- const hasLocal = config.localPath && config.localPath !== 'null';
- const hasPaperless = config.paperlessId && config.paperlessId !== null;
- const hasUrl = config.url && config.url.trim() !== '';
-
-
- let linksHtml = '';
-
- if (hasLocal) {
- linksHtml += `<a href="#" onclick="openSecureFile('${config.localPath}'); return false;" class="${config.className}">
- <i class="${config.icon}"></i> ${config.label}
- </a>`;
- } else if (hasPaperless) {
- const warrantyContextJson = JSON.stringify({user_id: warranty.user_id, id: warranty.id}).replace(/"/g, '&quot;');
- linksHtml += `<a href="#" onclick="openPaperlessDocument(${config.paperlessId}, JSON.parse('${warrantyContextJson}')); return false;" class="${config.className}">
- <i class="${config.icon}"></i> ${config.label} <i class="fas fa-cloud" style="color: #4dabf7; margin-left: 4px; font-size: 0.8em;" title="Stored in Paperless-ngx"></i>
- </a>`;
- }
-
- // Add URL link if available
- if (hasUrl) {
- if (linksHtml) linksHtml += ' ';
- linksHtml += `<a href="${config.url}" target="_blank" class="document-url-link ${config.className}" title="Open ${config.label} URL">
- <i class="fas fa-link"></i> ${config.label} Link
- </a>`;
- }
-
- return linksHtml;
-}
-
-// Initialize the warranty form and all its components
-function initWarrantyForm() {
- // Initialize form tabs
- if (formTabs && tabContents) {
- initFormTabs();
- }
-
- // Initialize serial number inputs
- addSerialNumberInput();
-
- // Initialize file input display
- if (document.getElementById('productPhoto')) {
- document.getElementById('productPhoto').addEventListener('change', function(event) {
- updateFileName(event, 'productPhoto', 'productPhotoFileName');
- });
- }
-
- if (document.getElementById('invoice')) {
- document.getElementById('invoice').addEventListener('change', function(event) {
- updateFileName(event, 'invoice', 'fileName');
- });
- }
-
- if (document.getElementById('manual')) {
- document.getElementById('manual').addEventListener('change', function(event) {
- updateFileName(event, 'manual', 'manualFileName');
- });
- }
-
- if (document.getElementById('otherDocument')) {
- document.getElementById('otherDocument').addEventListener('change', function(event) {
- updateFileName(event, 'otherDocument', 'otherDocumentFileName');
- });
- }
-
- // Initialize tag functionality
- initTagFunctionality();
-
- // Form submission
- if (warrantyForm) {
- warrantyForm.addEventListener('submit', handleFormSubmit); // Use renamed handler
- }
-
- // Initialize lifetime checkbox listener
- if (isLifetimeCheckbox && warrantyDurationFields) { // Check for new container
- isLifetimeCheckbox.addEventListener('change', handleLifetimeChange);
- handleLifetimeChange(); // Initial check
- } else {
- console.error("Lifetime warranty elements or duration fields not found in add form");
- }
-}
-
-// Initialize tag functionality
-function initTagFunctionality() {
- // This function now ONLY sets up listeners for the main "Add Warranty" form's tag interface.
- // Assumes globalTagManagementModal listeners (new tag form, close buttons) are set up separately if the modal exists.
-
- // Get main form tag elements
- const mainFormTagSearch = document.getElementById('tagSearch');
- const mainFormTagsList = document.getElementById('tagsList'); // Dropdown for search in main form
- const mainFormManageTagsBtn = document.getElementById('manageTagsBtn'); // "Manage Tags" button in main form
- const mainFormSelectedTagsContainer = document.getElementById('selectedTags'); // Container for selected tags in main form
-
- // Skip if main form specific tag elements don't exist
- if (!mainFormTagSearch || !mainFormTagsList || !mainFormManageTagsBtn || !mainFormSelectedTagsContainer) {
- console.log('Main form tag UI elements (tagSearch, tagsList, manageTagsBtn, or selectedTagsContainer) not found, skipping main form tag UI initialization.');
- return;
- }
-
- console.log('Initializing main form tag UI functionality (search, selection, manage button).');
-
- // Load allTags if not already loaded (needed for search suggestions in the main form)
- if (allTags.length === 0) {
- loadTags(); // loadTags is async
- }
-
- mainFormTagSearch.addEventListener('focus', () => {
- renderTagsList(); // Renders suggestions into mainFormTagsList based on allTags
- mainFormTagsList.classList.add('show');
- });
-
- mainFormTagSearch.addEventListener('input', () => {
- renderTagsList(mainFormTagSearch.value); // Filters suggestions
- });
-
- // Hide main form's tag suggestion dropdown when clicking outside
- document.addEventListener('click', (e) => {
- // Check if mainFormTagSearch and mainFormTagsList are still valid (e.g. not removed from DOM)
- if (mainFormTagSearch && mainFormTagsList &&
- !mainFormTagSearch.contains(e.target) &&
- !mainFormTagsList.contains(e.target)) {
- mainFormTagsList.classList.remove('show');
- }
- });
-
- // "Manage Tags" button in the main form opens the global tagManagementModal
- mainFormManageTagsBtn.addEventListener('click', (e) => {
- e.preventDefault();
- openTagManagementModal(); // This function shows the global modal
- });
-
- // Initial rendering of selected tags for the main form (if any are pre-selected or loaded)
- renderSelectedTags(); // Renders into mainFormSelectedTagsContainer
-}
-
-// Function to load all tags
-async function loadTags(force = false) {
- console.log('[script.js] loadTags() called. Current page:', window.location.pathname);
-
- // Check if tags are already loaded and reasonably populated
- if (!force && allTags && allTags.length > 0) {
- console.log('[script.js] Tags already loaded in allTags global. Skipping fetch. Count:', allTags.length);
- // Optionally, re-dispatch the event if other components might need it on subsequent (though now less likely) calls
- // document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: allTags }));
- return;
- }
-
- try {
- const token = auth.getToken();
- if (!token) {
- console.warn('[script.js] No token available for loadTags. User might not be authenticated yet.');
- allTags = []; // Ensure allTags is empty if we can't load
- if (window.store && window.store.setAllTags) window.store.setAllTags(allTags);
- return;
- }
- const response = await fetch('/api/tags', {
- headers: { 'Authorization': `Bearer ${token}` }
- });
- if (!response.ok) {
- const errorText = await response.text();
- console.error('[script.js] Failed to load tags:', response.status, errorText);
- allTags = []; // Default to empty on error
- if (window.store && window.store.setAllTags) window.store.setAllTags(allTags);
- return;
- }
- const fetchedTags = await response.json();
- // Assuming fetchedTags is an array of {id, name, color, ...} as expected by other functions
- allTags = fetchedTags;
- if (window.store && window.store.setAllTags) window.store.setAllTags(allTags);
- console.log('[script.js] All tags loaded into global allTags variable:', allTags.length, 'tags. Sample:', allTags.slice(0,2));
- // Dispatch event for any components that might be waiting for tags (e.g., Tagify instances)
- document.dispatchEvent(new CustomEvent('allTagsLoaded', { detail: allTags }));
-
- } catch (error) {
- console.error('[script.js] Error in loadTags():', error);
- allTags = []; // Default to empty on critical error
- if (window.store && window.store.setAllTags) window.store.setAllTags(allTags);
- }
-}
-
-// Render the tags dropdown list
-function renderTagsList(searchTerm = '') {
- if (!tagsList) return;
-
- while (tagsList.firstChild) tagsList.removeChild(tagsList.firstChild);
-
- // Filter tags based on search term
- const filteredTags = allTags.filter(tag =>
- !searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase())
- );
-
- // Add option to create new tag if search term is provided and not in list
- if (searchTerm && !filteredTags.some(tag => tag.name.toLowerCase() === searchTerm.toLowerCase())) {
- const createOption = document.createElement('div');
- createOption.className = 'tag-option create-tag';
- const icon = document.createElement('i'); icon.className = 'fas fa-plus';
- createOption.appendChild(icon);
- const createText = (window.i18next ? window.i18next.t('actions.create') : 'Create');
- createOption.appendChild(document.createTextNode(` ${createText} "${searchTerm}"`));
- createOption.addEventListener('click', () => {
- createTag(searchTerm).then(newTag => {
- // Add the new tag to selectedTags
- selectedTags.push(newTag);
- renderSelectedTags();
- renderTagsList(''); // Clear search and refresh list
- });
- tagsList.classList.remove('show');
- });
- tagsList.appendChild(createOption);
- }
-
- // Add existing tags to dropdown
- filteredTags.forEach(tag => {
- const option = document.createElement('div');
- option.className = 'tag-option';
-
- // Check if tag is already selected
- const isSelected = selectedTags.some(selected => selected.id === tag.id);
-
- const color = document.createElement('span'); color.className = 'tag-color'; color.style.backgroundColor = tag.color;
- const name = document.createTextNode(` ${tag.name}`);
- const status = document.createElement('span'); status.className = 'tag-status';
- if (isSelected) {
- const check = document.createElement('i'); check.className = 'fas fa-check';
- status.appendChild(check);
- }
- option.appendChild(color);
- option.appendChild(name);
- option.appendChild(status);
-
- option.addEventListener('click', () => {
- if (isSelected) {
- // Remove tag if already selected
- selectedTags = selectedTags.filter(selected => selected.id !== tag.id);
- } else {
- // Add tag if not selected
- selectedTags.push({
- id: tag.id,
- name: tag.name,
- color: tag.color
- });
- }
-
- renderSelectedTags();
- renderTagsList(searchTerm);
- });
-
- tagsList.appendChild(option);
- });
-
- // Show the dropdown
- tagsList.classList.add('show');
-}
-
-// Update renderEditTagsList to add new tag to editSelectedTags after creation
-function renderEditTagsList(searchTerm = '') {
- const editTagsList = document.getElementById('editTagsList');
- if (!editTagsList) return;
- while (editTagsList.firstChild) editTagsList.removeChild(editTagsList.firstChild);
- // Filter tags based on search term
- const filteredTags = allTags.filter(tag =>
- !searchTerm || tag.name.toLowerCase().includes(searchTerm.toLowerCase())
- );
- // Add option to create new tag if search term is provided and not in list
- if (searchTerm && !filteredTags.some(tag => tag.name.toLowerCase() === searchTerm.toLowerCase())) {
- const createOption = document.createElement('div');
- createOption.className = 'tag-option create-tag';
- const plus = document.createElement('i');
- plus.className = 'fas fa-plus';
- createOption.appendChild(plus);
- createOption.appendChild(document.createTextNode(' ' + (window.i18next ? window.i18next.t('actions.create') : 'Create') + ` "${searchTerm}"`));
- createOption.addEventListener('click', () => {
- createTag(searchTerm).then(newTag => {
- // Add the new tag to editSelectedTags
- editSelectedTags.push(newTag);
- renderEditSelectedTags();
- renderEditTagsList(''); // Clear search and refresh list
- });
- editTagsList.classList.remove('show');
- });
- editTagsList.appendChild(createOption);
- }
- // Add existing tags to dropdown
- filteredTags.forEach(tag => {
- const option = document.createElement('div');
- option.className = 'tag-option';
-
- // Check if tag is already selected
- const isSelected = editSelectedTags.some(selected => selected.id === tag.id);
- const colorSpan = document.createElement('span');
- colorSpan.className = 'tag-color';
- colorSpan.style.backgroundColor = tag.color;
- const nameText = document.createTextNode(tag.name);
- const statusSpan = document.createElement('span');
- statusSpan.className = 'tag-status';
- if (isSelected) {
- const check = document.createElement('i');
- check.className = 'fas fa-check';
- statusSpan.appendChild(check);
- }
- option.appendChild(colorSpan);
- option.appendChild(document.createTextNode(' '));
- option.appendChild(nameText);
- option.appendChild(statusSpan);
-
- option.addEventListener('click', () => {
- if (isSelected) {
- // Remove tag if already selected
- editSelectedTags = editSelectedTags.filter(selected => selected.id !== tag.id);
- } else {
- // Add tag if not selected
- editSelectedTags.push({
- id: tag.id,
- name: tag.name,
- color: tag.color
- });
- }
-
- // Use our helper function to render selected tags
- renderEditSelectedTags();
-
- renderEditTagsList(searchTerm);
- });
-
- editTagsList.appendChild(option);
- });
-
- // Show the dropdown
- editTagsList.classList.add('show');
-}
-
-// Render the selected tags
-function renderSelectedTags() {
- if (!selectedTagsContainer) return;
- while (selectedTagsContainer.firstChild) selectedTagsContainer.removeChild(selectedTagsContainer.firstChild);
-
- if (selectedTags.length === 0) {
- const placeholder = document.createElement('span');
- placeholder.className = 'no-tags-selected';
- placeholder.textContent = 'No tags selected';
- selectedTagsContainer.appendChild(placeholder);
- return;
- }
-
- selectedTags.forEach(tag => {
- const tagElement = document.createElement('span');
- tagElement.className = 'tag';
- tagElement.style.backgroundColor = tag.color;
- tagElement.style.color = getContrastColor(tag.color);
- tagElement.appendChild(document.createTextNode(tag.name + ' '));
- const removeSpan = document.createElement('span');
- removeSpan.className = 'remove-tag';
- removeSpan.dataset.id = String(tag.id);
- removeSpan.textContent = '×';
- tagElement.appendChild(removeSpan);
-
- // Add event listener for removing tag
- removeSpan.addEventListener('click', (e) => {
- e.stopPropagation();
- selectedTags = selectedTags.filter(t => t.id !== tag.id);
- renderSelectedTags();
-
- // Update summary if needed
- if (document.getElementById('summary-tags')) {
- updateSummary();
- }
- });
-
- selectedTagsContainer.appendChild(tagElement);
- });
-}
-
-// Helper function to render the edit selected tags
-function renderEditSelectedTags() {
- const editSelectedTagsContainer = document.getElementById('editSelectedTags');
- if (!editSelectedTagsContainer) return;
- while (editSelectedTagsContainer.firstChild) editSelectedTagsContainer.removeChild(editSelectedTagsContainer.firstChild);
-
- if (editSelectedTags.length > 0) {
- editSelectedTags.forEach(tag => {
- const tagElement = document.createElement('span');
- tagElement.className = 'tag';
- tagElement.style.backgroundColor = tag.color;
- tagElement.style.color = getContrastColor(tag.color);
- tagElement.appendChild(document.createTextNode(tag.name + ' '));
- const removeSpan = document.createElement('span');
- removeSpan.className = 'remove-tag';
- removeSpan.dataset.id = String(tag.id);
- removeSpan.textContent = '×';
- tagElement.appendChild(removeSpan);
-
- // Add event listener for removing tag
- removeSpan.addEventListener('click', (e) => {
- e.stopPropagation();
- e.preventDefault(); // Add this to prevent default action
-
- // Prevent the event from bubbling up to parent elements
- if (e.cancelBubble !== undefined) {
- e.cancelBubble = true;
- }
-
- editSelectedTags = editSelectedTags.filter(t => t.id !== tag.id);
-
- // Re-render just the tags
- renderEditSelectedTags();
- return false; // Add return false for older browsers
- });
-
- editSelectedTagsContainer.appendChild(tagElement);
- });
- } else {
- const placeholder = document.createElement('span');
- placeholder.className = 'no-tags-selected';
- placeholder.textContent = 'No tags selected';
- editSelectedTagsContainer.appendChild(placeholder);
- }
-}
-
-// Update createTag to return a Promise
-function createTag(name) {
- return new Promise((resolve, reject) => {
- // Enhanced auth manager availability check
- if (!window.auth) {
- console.error('[createTag] Auth manager not available');
- reject(new Error('Authentication system not ready. Please try again.'));
- return;
- }
-
- // Use auth manager's getToken method instead of directly accessing localStorage
- const token = window.auth.getToken();
- console.log('[createTag] Debug info:', {
- hasToken: !!token,
- tokenLength: token ? token.length : 0,
- hasUserInfo: !!localStorage.getItem('user_info'),
- authManagerAvailable: !!window.auth,
- isAuthenticated: window.auth.isAuthenticated(),
- tokenSource: 'auth.getToken()'
- });
-
- if (!token) {
- console.error('[createTag] No authentication token found');
- reject(new Error('No authentication token found. Please try logging in again.'));
- return;
- }
- // Generate a random color for the tag
- const color = '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');
- fetch('/api/tags', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': 'Bearer ' + token
- },
- body: JSON.stringify({
- name: name,
- color: color
- })
- })
- .then(response => {
- if (!response.ok) {
- // Enhanced error handling to capture specific error details
- return response.json().then(errorData => {
- console.error('[createTag] API Error Response:', {
- status: response.status,
- statusText: response.statusText,
- errorData: errorData
- });
-
- if (response.status === 409) {
- reject(new Error(window.t('messages.tag_already_exists')));
- return;
- }
- if (response.status === 401) {
- reject(new Error('Authentication failed. Please try logging in again.'));
- return;
- }
- if (response.status === 403) {
- reject(new Error('Permission denied. You may not have access to create tags.'));
- return;
- }
-
- const errorMsg = errorData?.error || errorData?.message || 'Failed to create tag';
- reject(new Error(errorMsg));
- }).catch(() => {
- // If response body is not JSON or is empty
- console.error('[createTag] Non-JSON error response:', response.status, response.statusText);
- reject(new Error(`Failed to create tag (${response.status})`));
- });
- }
- return response.json();
- })
- .then(data => {
- if (!data) return;
- const newTag = {
- id: data.id,
- name: data.name,
- color: data.color
- };
- allTags.push(newTag);
- renderExistingTags();
- populateTagFilter();
- showToast(window.t('messages.tag_created_successfully'), 'success');
- resolve(newTag);
- })
- .catch(error => {
- console.error('Error creating tag:', error);
- showToast(error.message || window.t('messages.failed_to_create_tag'), 'error');
- reject(error);
- });
- });
-}
-
-// Helper function to determine text color based on background color
-function getContrastColor(hexColor) {
- // Convert hex to RGB
- const r = parseInt(hexColor.substr(1, 2), 16);
- const g = parseInt(hexColor.substr(3, 2), 16);
- const b = parseInt(hexColor.substr(5, 2), 16);
-
- // Calculate luminance
- const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
-
- // Return black or white depending on luminance
- return (yiq >= 128) ? '#000000' : '#ffffff';
-}
-
-// Open tag management modal
-function openTagManagementModal() {
- if (!tagManagementModal) return;
-
- // Populate existing tags
- renderExistingTags();
- addTagManagementEventListeners();
-
- // Show modal
- tagManagementModal.classList.add('active');
-}
-
-// Render existing tags in the management modal
-function renderExistingTags() {
- if (!existingTagsContainer) return;
- existingTagsContainer.textContent = '';
-
- const wrapper = document.createElement('div');
- // Ensure horizontal scroll on small screens
- wrapper.className = 'table-responsive';
- const table = document.createElement('table');
- table.className = 'tag-management-table';
-
- // Header
- const thead = document.createElement('thead');
- const trHead = document.createElement('tr');
- const thColor = document.createElement('th'); thColor.className = 'tag-color-header'; thColor.textContent = window.i18next ? window.i18next.t('warranties.color') : 'Color';
- const thName = document.createElement('th'); thName.textContent = window.i18next ? window.i18next.t('warranties.name') : 'Name';
- const thActions = document.createElement('th'); thActions.className = 'tag-actions-header'; thActions.textContent = window.i18next ? window.i18next.t('actions.actions') : 'Actions';
- trHead.appendChild(thColor); trHead.appendChild(thName); trHead.appendChild(thActions);
- thead.appendChild(trHead);
- table.appendChild(thead);
-
- const tbody = document.createElement('tbody');
-
- if (!allTags || allTags.length === 0) {
- const emptyRow = document.createElement('tr');
- const td = document.createElement('td'); td.colSpan = 3;
- const noDiv = document.createElement('div'); noDiv.className = 'no-tags'; noDiv.textContent = window.t ? window.t('messages.no_tags_created_yet') : 'No tags created yet';
- td.appendChild(noDiv); emptyRow.appendChild(td); tbody.appendChild(emptyRow);
- } else {
- allTags.forEach(tag => {
- const row = document.createElement('tr');
- row.className = 'existing-tag-row';
- row.dataset.id = String(tag.id);
- // Color cell
- const tdColor = document.createElement('td');
- const swatchContainer = document.createElement('div'); swatchContainer.className = 'tag-color-swatch-container';
- const swatch = document.createElement('div'); swatch.className = 'tag-color-swatch'; swatch.style.backgroundColor = tag.color; swatch.setAttribute('aria-label', escapeHtml(tag.name));
- const colorInput = document.createElement('input'); colorInput.type = 'color'; colorInput.className = 'tag-color-input-hidden'; colorInput.value = tag.color; colorInput.setAttribute('aria-label', 'Pick color');
- swatchContainer.appendChild(swatch); swatchContainer.appendChild(colorInput); tdColor.appendChild(swatchContainer);
- // Name cell
- const tdName = document.createElement('td');
- const nameDisp = document.createElement('span'); nameDisp.className = 'tag-name-display'; nameDisp.textContent = tag.name;
- const nameInput = document.createElement('input'); nameInput.type = 'text'; nameInput.className = 'form-control tag-name-input'; nameInput.value = tag.name;
- tdName.appendChild(nameDisp); tdName.appendChild(nameInput);
- // Actions cell
- const tdActions = document.createElement('td'); tdActions.className = 'tag-actions';
- const viewActions = document.createElement('div'); viewActions.className = 'view-actions';
- const editBtn = document.createElement('button'); editBtn.className = 'btn btn-sm btn-secondary edit-tag'; editBtn.title = 'Edit'; const editIcon = document.createElement('i'); editIcon.className = 'fas fa-edit'; editBtn.appendChild(editIcon);
- const delBtn = document.createElement('button'); delBtn.className = 'btn btn-sm btn-danger delete-tag'; delBtn.title = 'Delete'; const delIcon = document.createElement('i'); delIcon.className = 'fas fa-trash'; delBtn.appendChild(delIcon);
- viewActions.appendChild(editBtn); viewActions.appendChild(delBtn);
- const editActions = document.createElement('div'); editActions.className = 'edit-actions';
- const saveBtn = document.createElement('button'); saveBtn.className = 'btn btn-sm btn-primary save-tag'; saveBtn.title = 'Save'; const saveIcon = document.createElement('i'); saveIcon.className = 'fas fa-check'; saveBtn.appendChild(saveIcon);
- const cancelBtn = document.createElement('button'); cancelBtn.className = 'btn btn-sm btn-secondary cancel-edit'; cancelBtn.title = 'Cancel'; const cancelIcon = document.createElement('i'); cancelIcon.className = 'fas fa-times'; cancelBtn.appendChild(cancelIcon);
- editActions.appendChild(saveBtn); editActions.appendChild(cancelBtn);
- tdActions.appendChild(viewActions); tdActions.appendChild(editActions);
- // Append cells to row
- row.appendChild(tdColor); row.appendChild(tdName); row.appendChild(tdActions);
-
- tbody.appendChild(row);
- });
- }
-
- table.appendChild(tbody);
- wrapper.appendChild(table);
- existingTagsContainer.appendChild(wrapper);
-
- // Ensure delegation is attached once
- addTagManagementEventListeners();
-}
-
-// Edit a tag
-function editTag(row) {
- // Switch row into edit mode (toggle inputs/buttons)
- const nameDisplay = row.querySelector('.tag-name-display');
- const nameInput = row.querySelector('.tag-name-input');
- const viewActions = row.querySelector('.view-actions');
- const editActions = row.querySelector('.edit-actions');
- if (!nameDisplay || !nameInput || !viewActions || !editActions) return;
-
- nameDisplay.style.display = 'none';
- nameInput.style.display = 'block';
- viewActions.style.display = 'none';
- editActions.style.display = 'flex';
- row.classList.add('editing');
-}
-
-// Update a tag
-function updateTag(id, name, color) {
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
- if (!token) {
- console.error('No authentication token found');
- return;
- }
-
- fetch(`/api/tags/${id}`, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': 'Bearer ' + token
- },
- body: JSON.stringify({
- name: name,
- color: color
- })
- })
- .then(response => {
- if (!response.ok) {
- if (response.status === 409) {
- throw new Error('A tag with this name already exists');
- }
- throw new Error(window.t('messages.failed_to_update_tag'));
- }
- return response.json();
- })
- .then(data => {
- // Refresh lists to ensure consistency and exit edit mode
- return loadTags(true).then(() => {
- // Update local selections and warranties to reflect new tag data immediately
- try {
- if (data && typeof data.id !== 'undefined') {
- // Update selected tags in Add Warranty flow
- if (Array.isArray(selectedTags) && selectedTags.length > 0) {
- selectedTags = selectedTags.map(t => t.id === data.id ? { id: data.id, name: data.name, color: data.color } : t);
- }
- // Update selected tags in Edit Warranty flow
- if (Array.isArray(editSelectedTags) && editSelectedTags.length > 0) {
- editSelectedTags = editSelectedTags.map(t => t.id === data.id ? { id: data.id, name: data.name, color: data.color } : t);
- }
- // Update tags inside existing warranties so cards reflect changes
- if (Array.isArray(warranties) && warranties.length > 0) {
- warranties.forEach(w => {
- if (Array.isArray(w.tags)) {
- w.tags.forEach(tag => {
- if (tag.id === data.id) {
- tag.name = data.name;
- tag.color = data.color;
- }
- });
- }
- });
- }
- }
- } catch (e) {
- console.warn('[script.js] Non-fatal error while updating local tag state after update:', e);
- }
-
- renderExistingTags();
- renderSelectedTags();
- renderEditSelectedTags();
- populateTagFilter();
- renderWarranties(warranties);
- if (document.getElementById('summary-tags')) {
- updateSummary();
- }
- showToast(window.t('messages.tag_updated_successfully'), 'success');
- });
- })
- .catch(error => {
- console.error('Error updating tag:', error);
- showToast(error.message || window.t('messages.failed_to_update_tag'), 'error');
- });
-}
-
-// Centralized event delegation for tag management table
-function addTagManagementEventListeners() {
- if (!tagManagementModal) return;
- const container = existingTagsContainer;
- if (!container) return;
-
- // Avoid attaching multiple times
- if (container.dataset.tmListenersAttached === 'true') return;
- container.dataset.tmListenersAttached = 'true';
-
- container.addEventListener('click', (e) => {
- const row = e.target.closest('tr.existing-tag-row');
- if (!row) return;
- const id = parseInt(row.dataset.id, 10);
- if (Number.isNaN(id)) return;
-
- if (e.target.closest('.edit-tag')) {
- editTag(row);
- return;
- }
- if (e.target.closest('.cancel-edit')) {
- // Exit edit mode: revert inputs/buttons visibility
- const nameDisplay = row.querySelector('.tag-name-display');
- const nameInput = row.querySelector('.tag-name-input');
- const viewActions = row.querySelector('.view-actions');
- const editActions = row.querySelector('.edit-actions');
- if (nameDisplay && nameInput && viewActions && editActions) {
- nameDisplay.style.display = '';
- nameInput.style.display = 'none';
- viewActions.style.display = '';
- editActions.style.display = 'none';
- }
- row.classList.remove('editing');
- return;
- }
- if (e.target.closest('.save-tag')) {
- const nameInput = row.querySelector('.tag-name-input');
- const colorInput = row.querySelector('.tag-color-input-hidden');
- const newName = (nameInput && nameInput.value ? nameInput.value.trim() : '');
- const newColor = colorInput ? colorInput.value : undefined;
- if (!newName) {
- showToast(window.t('messages.tag_name_required'), 'error');
- return;
- }
- updateTag(id, newName, newColor);
- row.classList.remove('editing');
- return;
- }
- if (e.target.closest('.delete-tag')) {
- deleteTag(id);
- return;
- }
- });
-
- // Color picker change via delegation
- container.addEventListener('input', (e) => {
- if (e.target.matches('.tag-color-input-hidden')) {
- const row = e.target.closest('tr.existing-tag-row');
- const swatch = row ? row.querySelector('.tag-color-swatch') : null;
- if (swatch) swatch.style.backgroundColor = e.target.value;
- }
- });
-
- // Auto-save color changes without requiring Edit/Save click
- container.addEventListener('change', (e) => {
- if (e.target.matches('.tag-color-input-hidden')) {
- const row = e.target.closest('tr.existing-tag-row');
- if (!row) return;
- const id = parseInt(row.dataset.id, 10);
- if (Number.isNaN(id)) return;
- const nameInput = row.querySelector('.tag-name-input');
- const nameDisplay = row.querySelector('.tag-name-display');
- const currentName = (nameInput && nameInput.style.display !== 'none' ? nameInput.value : (nameDisplay ? nameDisplay.textContent : '')).trim();
- const newColor = e.target.value;
- if (!currentName) {
- showToast(window.t ? window.t('messages.tag_name_required') : 'Tag name is required', 'error');
- return;
- }
- updateTag(id, currentName, newColor);
- }
- });
-}
-
-// Delete a tag
-function deleteTag(id) {
- if (!confirm('Are you sure you want to delete this tag? It will be removed from all warranties.')) {
- return;
- }
-
- const token = localStorage.getItem('auth_token');
- if (!token) {
- console.error('No authentication token found');
- showToast(window.t('messages.authentication_required'), 'error'); // Added toast for better feedback
- return;
- }
-
- showLoadingSpinner(); // Show loading indicator
-
- fetch(`/api/tags/${id}`, { // Use the correct URL with tag ID
- method: 'DELETE', // Use DELETE method
- headers: {
- 'Authorization': 'Bearer ' + token
- }
- })
- .then(response => {
- if (!response.ok) {
- // Log the status for debugging the 405 error
- console.error(`Failed to delete tag. Status: ${response.status} ${response.statusText}`);
- // Try to get error message from response body
- return response.json().then(errData => {
- throw new Error(errData.error || errData.message || 'Failed to delete tag');
- }).catch(() => {
- // If response body is not JSON or empty
- throw new Error(`Failed to delete tag. Status: ${response.status}`);
- });
- }
- return response.json();
- })
- .then(data => {
- // Remove tag from allTags array
- allTags = allTags.filter(tag => tag.id !== id);
- if (window.store && window.store.setAllTags) window.store.setAllTags(allTags);
-
- // Remove tag from selectedTags if present (in both add and edit modes)
- selectedTags = selectedTags.filter(tag => tag.id !== id);
- editSelectedTags = editSelectedTags.filter(tag => tag.id !== id);
-
- // Remove tag from warranties array
- warranties.forEach(warranty => {
- if (warranty.tags && Array.isArray(warranty.tags)) {
- warranty.tags = warranty.tags.filter(tag => tag.id !== id);
- }
- });
-
- // --- FIX: Re-render UI elements ---
- renderExistingTags(); // Update the list in the modal
- renderSelectedTags(); // Update selected tags in the add form
- renderEditSelectedTags(); // Update selected tags in the edit form
- populateTagFilter(); // Update the filter dropdown on the main page
- renderWarranties(warranties); // Update warranty cards to remove deleted tag
- // --- END FIX ---
-
- showToast(window.t('messages.tag_deleted_successfully'), 'success');
- })
- .catch(error => {
- console.error('Error deleting tag:', error);
- showToast(error.message || window.t('messages.failed_to_delete_tag'), 'error'); // Show specific error message
- })
- .finally(() => {
- hideLoadingSpinner(); // Hide loading indicator
- });
-}
-
-// Set up event listeners for UI controls
-function setupUIEventListeners() {
- // --- Global Manage Tags Button ---
- const globalManageTagsBtn = document.getElementById('globalManageTagsBtn');
- if (globalManageTagsBtn) {
- globalManageTagsBtn.addEventListener('click', async () => {
- // Ensure allTags are loaded before opening the modal
- if (!allTags || allTags.length === 0) {
- showLoadingSpinner();
- try {
- await loadTags();
- } catch (error) {
- console.error("Failed to load tags before opening modal:", error);
- showToast(window.t('messages.could_not_load_tags'), "error");
- hideLoadingSpinner();
- return;
- }
- hideLoadingSpinner();
- }
- openTagManagementModal();
- });
- }
- // Initialize edit tabs
- initEditTabs();
-
- // Close modals when clicking outside or on close button
- document.querySelectorAll('.modal-backdrop, [data-dismiss="modal"]').forEach(element => {
- element.addEventListener('click', (e) => {
- // Check if the click is on the backdrop itself OR a dismiss button
- if (e.target === element || e.target.matches('[data-dismiss="modal"]')) {
- // Find the closest modal backdrop to the element clicked
- const modalToClose = e.target.closest('.modal-backdrop');
-
- if (modalToClose) {
- // *** MODIFIED CHECK ***
- // If the click target is the backdrop itself (not a dismiss button)
- // AND the modal is one of the protected modals, then DO NOTHING.
- if ((modalToClose.id === 'addWarrantyModal' || modalToClose.id === 'editModal' ||
- modalToClose.id === 'claimsModal' || modalToClose.id === 'claimFormModal') && e.target === modalToClose) {
- return; // Ignore backdrop click for protected modals
- }
- // *** END MODIFIED CHECK ***
-
- // Otherwise, close the modal (handles other modals' backdrop clicks and all dismiss buttons)
- modalToClose.classList.remove('active');
-
- // Reset forms only when closing the respective modal
- if (modalToClose.id === 'editModal') {
- // Optional: Add any edit form reset logic here if needed
- console.log('Edit modal closed, reset logic (if any) can go here.');
- } else if (modalToClose.id === 'addWarrantyModal') {
- // This reset will now only trigger if closed via dismiss button
- resetAddWarrantyWizard();
- }
- // Add similar reset logic for other modals like deleteModal if needed
- // else if (modalToClose.id === 'deleteModal') { ... }
- }
- }
- });
- });
-
- // Prevent modal content clicks from closing the modal
- document.querySelectorAll('.modal').forEach(modal => {
- modal.addEventListener('click', (e) => {
- e.stopPropagation();
- });
- });
-
- // Filter event listeners
- const searchInput = document.getElementById('searchWarranties');
- const clearSearchBtn = document.getElementById('clearSearch');
- const statusFilter = document.getElementById('statusFilter');
- const tagFilter = document.getElementById('tagFilter');
- const sortBySelect = document.getElementById('sortBy');
- const vendorFilter = document.getElementById('vendorFilter'); // Added vendor filter select
- const warrantyTypeFilter = document.getElementById('warrantyTypeFilter'); // Added warranty type filter select
-
- if (searchInput) {
- // Debounce logic: only apply filters after user stops typing for 300ms
- let searchDebounceTimeout;
- searchInput.addEventListener('input', () => {
- currentFilters.search = searchInput.value.toLowerCase();
- // Show/hide clear button based on search input
- if (clearSearchBtn) {
- clearSearchBtn.style.display = searchInput.value ? 'flex' : 'none';
- }
- // Add visual feedback class to search box when active
- if (searchInput.value) {
- searchInput.parentElement.classList.add('active-search');
- } else {
- searchInput.parentElement.classList.remove('active-search');
- }
- // Debounce applyFilters
- if (searchDebounceTimeout) clearTimeout(searchDebounceTimeout);
- searchDebounceTimeout = setTimeout(() => {
- applyFilters();
- saveFilterPreferences();
- }, 300);
- });
- }
-
- if (clearSearchBtn) {
- clearSearchBtn.addEventListener('click', () => {
- if (searchInput) {
- searchInput.value = '';
- if (window.store && window.store.updateFilter) window.store.updateFilter('search', '');
- currentFilters.search = '';
- clearSearchBtn.style.display = 'none';
- searchInput.parentElement.classList.remove('active-search');
- searchInput.focus();
- applyFilters();
- saveFilterPreferences();
- }
- });
- }
-
- if (statusFilter) {
- statusFilter.addEventListener('change', () => {
- if (window.store && window.store.updateFilter) window.store.updateFilter('status', statusFilter.value);
- currentFilters.status = statusFilter.value;
- applyFilters();
- saveFilterPreferences();
- });
- }
-
- if (tagFilter) {
- tagFilter.addEventListener('change', () => {
- if (window.store && window.store.updateFilter) window.store.updateFilter('tag', tagFilter.value);
- currentFilters.tag = tagFilter.value;
- applyFilters();
- saveFilterPreferences();
- });
- }
-
- if (vendorFilter) { // Added event listener for vendor filter
- vendorFilter.addEventListener('change', () => {
- if (window.store && window.store.updateFilter) window.store.updateFilter('vendor', vendorFilter.value);
- currentFilters.vendor = vendorFilter.value;
- applyFilters();
- saveFilterPreferences();
- });
- }
-
- if (warrantyTypeFilter) { // Added event listener for warranty type filter
- warrantyTypeFilter.addEventListener('change', () => {
- if (window.store && window.store.updateFilter) window.store.updateFilter('warranty_type', warrantyTypeFilter.value);
- currentFilters.warranty_type = warrantyTypeFilter.value;
- applyFilters();
- saveFilterPreferences();
- });
- }
-
- if (sortBySelect) {
- sortBySelect.addEventListener('change', () => {
- if (window.store && window.store.updateFilter) window.store.updateFilter('sortBy', sortBySelect.value);
- currentFilters.sortBy = sortBySelect.value;
- applyFilters();
- saveFilterPreferences();
- });
- }
-
- // Note: Clear Filters button handler is in index.html inline script to close popover
-
- // View switcher event listeners
- const gridViewBtn = document.getElementById('gridViewBtn');
- const listViewBtn = document.getElementById('listViewBtn');
- const tableViewBtn = document.getElementById('tableViewBtn');
-
- if (gridViewBtn) gridViewBtn.addEventListener('click', () => switchView('grid'));
- if (listViewBtn) listViewBtn.addEventListener('click', () => switchView('list'));
- if (tableViewBtn) tableViewBtn.addEventListener('click', () => switchView('table'));
-
- // Export button event listener
- const exportBtn = document.getElementById('exportBtn');
- if (exportBtn) exportBtn.addEventListener('click', exportWarranties);
-
- // Import button event listener
- if (importBtn && csvFileInput) {
- importBtn.addEventListener('click', () => {
- csvFileInput.click(); // Trigger hidden file input
- });
- csvFileInput.addEventListener('change', (event) => {
- if (event.target.files && event.target.files.length > 0) {
- handleImport(event.target.files[0]);
- }
- });
- }
-
- // Refresh button
- const refreshBtn = document.getElementById('refreshBtn');
- if (refreshBtn) refreshBtn.addEventListener('click', loadWarranties);
-
- // Warranty Type dropdown handlers for custom option
- if (warrantyTypeInput && warrantyTypeCustomInput) {
- warrantyTypeInput.addEventListener('change', () => {
- if (warrantyTypeInput.value === 'other') {
- warrantyTypeCustomInput.style.display = 'block';
- warrantyTypeCustomInput.focus();
- } else {
- warrantyTypeCustomInput.style.display = 'none';
- warrantyTypeCustomInput.value = '';
- }
- updateSummary(); // Update summary when warranty type changes
- });
-
- // Also update summary when custom warranty type changes
- warrantyTypeCustomInput.addEventListener('input', updateSummary);
- }
-
- if (editWarrantyTypeInput && editWarrantyTypeCustomInput) {
- editWarrantyTypeInput.addEventListener('change', () => {
- if (editWarrantyTypeInput.value === 'other') {
- editWarrantyTypeCustomInput.style.display = 'block';
- editWarrantyTypeCustomInput.focus();
- } else {
- editWarrantyTypeCustomInput.style.display = 'none';
- editWarrantyTypeCustomInput.value = '';
- }
- });
- }
-
- // Save warranty changes
- const saveWarrantyBtn = document.getElementById('saveWarrantyBtn');
- if (saveWarrantyBtn) {
- let functionToAttachOnClick = saveWarranty; // Default to the original saveWarranty from script.js
-
- // Check if the observer setup function from status.js is available
- if (typeof window.setupSaveWarrantyObserver === 'function') {
- console.log('[script.js] window.setupSaveWarrantyObserver (from status.js) was FOUND. Attempting to wrap local saveWarranty function.');
- try {
- // Call the observer setup function, passing it the original saveWarranty from this script.
- // The observer setup function is expected to return a new function that wraps the original.
- functionToAttachOnClick = window.setupSaveWarrantyObserver(saveWarranty);
-
- // Optional: A flag to let status.js know that script.js has handled the wrapping.
- // This can be useful if status.js has any fallback/polling logic to prevent double-wrapping.
- window.saveWarrantyObserverAttachedByScriptJS = true;
- console.log('[script.js] Local saveWarranty function has been successfully WRAPPED by the observer from status.js.');
- } catch (e) {
- console.error('[script.js] An error occurred while trying to wrap saveWarranty with the observer from status.js:', e);
- // If an error occurs during wrapping, functionToAttachOnClick will remain the original saveWarranty.
- }
- } else {
- console.log('[script.js] window.setupSaveWarrantyObserver (from status.js) was NOT FOUND. Using the original saveWarranty function for the button.');
- }
-
- // Add the event listener using the (potentially) wrapped function.
- saveWarrantyBtn.addEventListener('click', () => {
- console.log('[script.js] Save button (saveWarrantyBtn) clicked. Invoking the determined save function (functionToAttachOnClick).');
- if (typeof functionToAttachOnClick === 'function') {
- functionToAttachOnClick(); // Execute the determined save function
- } else {
- console.error('[script.js] CRITICAL: functionToAttachOnClick is not a function when save button was clicked!');
- }
- });
-
- } else {
- console.warn('[script.js] saveWarrantyBtn DOM element not found. Cannot attach click listener.');
- }
-
- // Confirm delete button
- const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
- if (confirmDeleteBtn) confirmDeleteBtn.addEventListener('click', deleteWarranty);
-
- // Confirm archive button
- const confirmArchiveBtn = document.getElementById('confirmArchiveBtn');
- if (confirmArchiveBtn) confirmArchiveBtn.addEventListener('click', confirmArchive);
-
- // Load saved view preference
- // loadViewPreference(); // Disabled: now called after authStateReady
-}
-
-// Function to show loading spinner
-function showLoadingSpinner() {
- if (loadingContainer) {
- loadingContainer.style.display = 'flex';
- }
-}
-
-// Function to hide loading spinner
-function hideLoadingSpinner() {
- if (loadingContainer) {
- loadingContainer.style.display = 'none';
- }
-}
-
-// Paperless upload loading functions
-function showPaperlessUploadLoading(documentType) {
- // Create or show the Paperless upload overlay
- let overlay = document.getElementById('paperless-upload-overlay');
- if (!overlay) {
- overlay = document.createElement('div');
- overlay.id = 'paperless-upload-overlay';
- overlay.innerHTML = `
- <div class="paperless-upload-modal">
- <div class="paperless-upload-content">
- <div class="paperless-upload-spinner"></div>
- <h3>Uploading to Paperless-ngx</h3>
- <p id="paperless-upload-status">Uploading document...</p>
- <div class="paperless-upload-progress">
- <div class="paperless-upload-progress-bar" id="paperless-progress-bar"></div>
- </div>
- </div>
- </div>
- `;
- document.body.appendChild(overlay);
-
- // Add CSS styles
- const style = document.createElement('style');
- style.textContent = `
- #paperless-upload-overlay {
- position: fixed;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background: rgba(0, 0, 0, 0.7);
- display: flex;
- justify-content: center;
- align-items: center;
- z-index: 10000;
- backdrop-filter: blur(2px);
- }
-
- .paperless-upload-modal {
- background: var(--card-bg, #fff);
- border-radius: 12px;
- padding: 2rem;
- max-width: 400px;
- width: 90%;
- text-align: center;
- box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
- border: 1px solid var(--border-color, #ddd);
- }
-
- .paperless-upload-content h3 {
- margin: 1rem 0 0.5rem 0;
- color: var(--text-color, #333);
- font-size: 1.2rem;
- }
-
- .paperless-upload-content p {
- margin: 0.5rem 0 1.5rem 0;
- color: var(--text-secondary, #666);
- font-size: 0.9rem;
- }
-
- .paperless-upload-spinner {
- width: 40px;
- height: 40px;
- border: 4px solid var(--border-color, #ddd);
- border-top: 4px solid var(--primary-color, #007bff);
- border-radius: 50%;
- animation: paperless-spin 1s linear infinite;
- margin: 0 auto 1rem auto;
- }
-
- @keyframes paperless-spin {
- 0% { transform: rotate(0deg); }
- 100% { transform: rotate(360deg); }
- }
-
- .paperless-upload-progress {
- width: 100%;
- height: 6px;
- background: var(--border-color, #ddd);
- border-radius: 3px;
- overflow: hidden;
- margin-top: 1rem;
- }
-
- .paperless-upload-progress-bar {
- height: 100%;
- background: linear-gradient(90deg, var(--primary-color, #007bff), var(--success-color, #28a745));
- border-radius: 3px;
- width: 0%;
- transition: width 0.3s ease;
- animation: paperless-progress-pulse 2s ease-in-out infinite;
- }
-
- @keyframes paperless-progress-pulse {
- 0%, 100% { opacity: 1; }
- 50% { opacity: 0.7; }
- }
- `;
- document.head.appendChild(style);
- }
-
- overlay.style.display = 'flex';
-
- // Update status text
- const statusEl = document.getElementById('paperless-upload-status');
- if (statusEl) {
- statusEl.textContent = `Uploading ${documentType} to Paperless-ngx...`;
- }
-
- // Animate progress bar
- const progressBar = document.getElementById('paperless-progress-bar');
- if (progressBar) {
- progressBar.style.width = '30%';
- setTimeout(() => {
- progressBar.style.width = '60%';
- }, 1000);
- setTimeout(() => {
- progressBar.style.width = '80%';
- }, 2000);
- }
-}
-
-function updatePaperlessUploadStatus(message, isProcessing = false) {
- const statusEl = document.getElementById('paperless-upload-status');
- const progressBar = document.getElementById('paperless-progress-bar');
-
- if (statusEl) {
- statusEl.textContent = message;
- }
-
- if (isProcessing && progressBar) {
- progressBar.style.width = '90%';
- }
-}
-
-function hidePaperlessUploadLoading() {
- const overlay = document.getElementById('paperless-upload-overlay');
- if (overlay) {
- // Complete the progress bar first
- const progressBar = document.getElementById('paperless-progress-bar');
- if (progressBar) {
- progressBar.style.width = '100%';
- }
-
- // Hide after a short delay to show completion
- setTimeout(() => {
- overlay.style.display = 'none';
- // Reset progress bar for next use
- if (progressBar) {
- progressBar.style.width = '0%';
- }
- }, 500);
- }
-}
-
-// Delete warranty function
-function deleteWarranty() {
- if (!currentWarrantyId) {
- showToast(window.t('messages.no_warranty_selected_for_deletion'), 'error');
- return;
- }
-
- const token = localStorage.getItem('auth_token');
- if (!token) {
- showToast('Authentication required', 'error');
- return;
- }
-
- showLoadingSpinner();
-
- fetch(`/api/warranties/${currentWarrantyId}`, {
- method: 'DELETE',
- headers: {
- 'Authorization': 'Bearer ' + token
- }
- })
- .then(response => {
- if (!response.ok) {
- throw new Error('Failed to delete warranty');
- }
- return response.json();
- })
- .then(data => {
- hideLoadingSpinner();
- showToast('Warranty deleted successfully', 'success');
- closeModals();
-
- // --- BEGIN FIX: Update UI immediately ---
- // Remove the deleted warranty from the global array
- const deletedId = currentWarrantyId; // Store ID before resetting
- if (window.store && window.store.setWarranties) {
- window.store.setWarranties(warranties.filter(warranty => warranty.id !== deletedId));
- }
- warranties = (window.store && window.store.getWarranties) ? window.store.getWarranties() : warranties;
- currentWarrantyId = null; // Reset current ID
-
- // Re-render the list using the updated local array
- applyFilters();
- // --- END FIX ---
- })
- .catch(error => {
- hideLoadingSpinner();
- console.error('Error deleting warranty:', error);
- showToast('Failed to delete warranty', 'error');
- });
-}
-
-// Save warranty updates
-function saveWarranty() {
- console.log("[script.js] CORE saveWarranty (original from script.js) EXECUTING.");
- if (!currentWarrantyId) {
- showToast(window.t('messages.no_warranty_selected_for_update'), 'error');
- return;
- }
-
- // --- Get form values ---
- const productName = document.getElementById('editProductName').value.trim();
- const purchaseDate = document.getElementById('editPurchaseDate').value;
- const isLifetime = document.getElementById('editIsLifetime').checked;
- const isDurationMethod = editDurationMethodRadio && editDurationMethodRadio.checked;
- // Get new duration values
- const years = parseInt(document.getElementById('editWarrantyDurationYears').value || 0);
- const months = parseInt(document.getElementById('editWarrantyDurationMonths').value || 0);
- const days = parseInt(document.getElementById('editWarrantyDurationDays').value || 0);
- const exactDate = editExactExpirationDateInput ? editExactExpirationDateInput.value : '';
-
- // Basic validation
- if (!productName) {
- showToast(window.t('messages.product_name_required'), 'error');
- return;
- }
-
- if (!purchaseDate) {
- showToast(window.t('messages.purchase_date_required'), 'error');
- return;
- }
-
- // --- Updated Validation ---
- if (!isLifetime) {
- if (isDurationMethod) {
- // Validate duration fields
- if (years === 0 && months === 0 && days === 0) {
- showToast(window.t('messages.warranty_duration_required'), 'error');
- // Optional: focus the years input again
- const yearsInput = document.getElementById('editWarrantyDurationYears');
- if (yearsInput) { // Check if element exists
- yearsInput.focus();
- // Add invalid class to container or inputs
- if (editWarrantyDurationFields) editWarrantyDurationFields.classList.add('invalid-duration');
- }
- return;
- }
- } else {
- // Validate exact expiration date
- if (!exactDate) {
- showToast(window.t('messages.exact_expiration_date_required'), 'error');
- if (editExactExpirationDateInput) editExactExpirationDateInput.focus();
- return;
- }
-
- // Validate that expiration date is in the future relative to purchase date
- if (purchaseDate && exactDate <= purchaseDate) {
- showToast(window.t('messages.expiration_date_after_purchase_date'), 'error');
- if (editExactExpirationDateInput) editExactExpirationDateInput.focus();
- return;
- }
- }
- }
-
- // Remove invalid duration class if validation passes
- if (editWarrantyDurationFields) editWarrantyDurationFields.classList.remove('invalid-duration');
- // --- End Updated Validation ---
-
- // Create form data
- const formData = new FormData();
- formData.append('product_name', productName);
- formData.append('purchase_date', purchaseDate);
-
- // Optional fields
- let productUrl = document.getElementById('editProductUrl').value.trim();
- if (productUrl) {
- if (!productUrl.startsWith('http://') && !productUrl.startsWith('https://')) {
- productUrl = 'https://' + productUrl;
- }
- formData.append('product_url', productUrl);
- }
-
- const purchasePrice = document.getElementById('editPurchasePrice').value;
- const currency = document.getElementById('editCurrency').value;
- if (purchasePrice) {
- formData.append('purchase_price', purchasePrice);
- }
- if (currency) {
- formData.append('currency', currency);
- }
-
- // Serial numbers (use correct name 'serial_numbers[]')
- const serialInputs = document.querySelectorAll('#editSerialNumbersContainer input[name="serial_numbers[]"]');
- // Clear existing before appending
- formData.delete('serial_numbers[]');
- serialInputs.forEach(input => {
- if (input.value.trim()) {
- formData.append('serial_numbers[]', input.value.trim()); // Use []
- }
- });
-
- // Tags - add tag IDs as JSON string
- if (editSelectedTags && editSelectedTags.length > 0) {
- const tagIds = editSelectedTags.map(tag => tag.id);
- formData.append('tag_ids', JSON.stringify(tagIds));
- } else {
- // Send empty array to clear tags
- formData.append('tag_ids', JSON.stringify([]));
- }
-
- // Add URL fields for documents (with null checks)
- const editInvoiceUrlField = document.getElementById('editInvoiceUrl');
- formData.append('invoice_url', editInvoiceUrlField ? editInvoiceUrlField.value || '' : '');
-
- const editManualUrlField = document.getElementById('editManualUrl');
- formData.append('manual_url', editManualUrlField ? editManualUrlField.value || '' : '');
-
- const editOtherDocumentUrlField = document.getElementById('editOtherDocumentUrl');
- formData.append('other_document_url', editOtherDocumentUrlField ? editOtherDocumentUrlField.value || '' : '');
-
- // Files
- const invoiceFile = document.getElementById('editInvoice').files[0];
- if (invoiceFile) {
- formData.append('invoice', invoiceFile);
- }
-
- const manualFile = document.getElementById('editManual').files[0];
- if (manualFile) {
- formData.append('manual', manualFile);
- }
-
- const otherDocumentFile = document.getElementById('editOtherDocument').files[0];
- if (otherDocumentFile) {
- formData.append('other_document', otherDocumentFile);
- }
-
- // Product photo
- const productPhotoFile = document.getElementById('editProductPhoto').files[0];
- if (productPhotoFile) {
- formData.append('product_photo', productPhotoFile);
- }
-
- // Document deletion flags
- const deleteInvoiceBtn = document.getElementById('deleteInvoiceBtn');
- if (deleteInvoiceBtn && deleteInvoiceBtn.dataset.delete === 'true') {
- formData.append('delete_invoice', 'true');
- }
- const deleteManualBtn = document.getElementById('deleteManualBtn');
- if (deleteManualBtn && deleteManualBtn.dataset.delete === 'true') {
- formData.append('delete_manual', 'true');
- }
- const deleteOtherDocumentBtn = document.getElementById('deleteOtherDocumentBtn');
- if (deleteOtherDocumentBtn && deleteOtherDocumentBtn.dataset.delete === 'true') {
- formData.append('delete_other_document', 'true');
- }
- const deleteProductPhotoBtn = document.getElementById('deleteProductPhotoBtn');
- if (deleteProductPhotoBtn && deleteProductPhotoBtn.dataset.delete === 'true') {
- formData.append('delete_product_photo', 'true');
- }
-
- // --- Append is_lifetime and duration components ---
- formData.append('is_lifetime', isLifetime.toString());
- if (!isLifetime) {
- if (isDurationMethod) {
- formData.append('warranty_duration_years', years);
- formData.append('warranty_duration_months', months);
- formData.append('warranty_duration_days', days);
- } else {
- // Using exact date method
- formData.append('exact_expiration_date', exactDate);
- // Ensure duration fields are 0 when using exact date
- formData.append('warranty_duration_years', 0);
- formData.append('warranty_duration_months', 0);
- formData.append('warranty_duration_days', 0);
- }
- } else {
- // Ensure duration is 0 if lifetime
- formData.append('warranty_duration_years', 0);
- formData.append('warranty_duration_months', 0);
- formData.append('warranty_duration_days', 0);
- }
- // Add notes
- const notes = document.getElementById('editNotes').value;
- if (notes && notes.trim() !== '') {
- formData.append('notes', notes);
- } else {
- // Explicitly clear notes if empty
- formData.append('notes', '');
- }
-
- // Add model number to form data (optional)
- const editModelNumber = document.getElementById('editModelNumber');
- if (editModelNumber && editModelNumber.value.trim() !== '') {
- formData.append('model_number', editModelNumber.value.trim());
- } else {
- // Explicitly clear if empty
- formData.append('model_number', '');
- }
-
- // Add vendor/retailer to form data
- const editVendorInput = document.getElementById('editVendor'); // Use the correct ID
- formData.append('vendor', editVendorInput ? editVendorInput.value.trim() : ''); // Use the correct variable
-
- // Add warranty type to form data - handle custom type
- const editWarrantyTypeInput = document.getElementById('editWarrantyType');
- const editWarrantyTypeCustomInput = document.getElementById('editWarrantyTypeCustom');
- let warrantyTypeValue = '';
- if (editWarrantyTypeInput) {
- if (editWarrantyTypeInput.value === 'other' && editWarrantyTypeCustomInput && editWarrantyTypeCustomInput.value.trim()) {
- warrantyTypeValue = editWarrantyTypeCustomInput.value.trim();
- } else {
- warrantyTypeValue = editWarrantyTypeInput.value.trim();
- }
- }
- formData.append('warranty_type', warrantyTypeValue);
-
- // Add selected Paperless documents for edit form
- const selectedEditPaperlessProductPhoto = document.getElementById('selectedEditPaperlessProductPhoto');
- const selectedEditPaperlessInvoice = document.getElementById('selectedEditPaperlessInvoice');
- const selectedEditPaperlessManual = document.getElementById('selectedEditPaperlessManual');
- const selectedEditPaperlessOtherDocument = document.getElementById('selectedEditPaperlessOtherDocument');
-
- if (selectedEditPaperlessProductPhoto && selectedEditPaperlessProductPhoto.value) {
- formData.append('paperless_photo_id', selectedEditPaperlessProductPhoto.value);
- }
- if (selectedEditPaperlessInvoice && selectedEditPaperlessInvoice.value) {
- formData.append('paperless_invoice_id', selectedEditPaperlessInvoice.value);
- }
- if (selectedEditPaperlessManual && selectedEditPaperlessManual.value) {
- formData.append('paperless_manual_id', selectedEditPaperlessManual.value);
- }
- if (selectedEditPaperlessOtherDocument && selectedEditPaperlessOtherDocument.value) {
- formData.append('paperless_other_id', selectedEditPaperlessOtherDocument.value);
- }
-
- // DEBUG: Log what we're sending to the backend
- console.log('[DEBUG saveWarranty] Form data being sent:');
- console.log('[DEBUG saveWarranty] isLifetime:', isLifetime);
- console.log('[DEBUG saveWarranty] isDurationMethod:', isDurationMethod);
- console.log('[DEBUG saveWarranty] exactDate:', exactDate);
- console.log('[DEBUG saveWarranty] years/months/days:', years, months, days);
-
- // Log all form data entries
- for (let [key, value] of formData.entries()) {
- console.log(`[DEBUG saveWarranty] FormData: ${key} = ${value}`);
- }
-
- // Get auth token
- const token = localStorage.getItem('auth_token');
- if (!token) {
- showToast('Authentication required', 'error');
- return;
- }
-
- showLoadingSpinner();
-
- // Process Paperless-ngx uploads if enabled
- processEditPaperlessNgxUploads(formData)
- .then(paperlessUploads => {
- // Add Paperless-ngx document IDs to form data
- Object.keys(paperlessUploads).forEach(key => {
- formData.append(key, paperlessUploads[key]);
- });
-
- // Send request
- return fetch(`/api/warranties/${currentWarrantyId}`, {
- method: 'PUT',
- headers: {
- 'Authorization': 'Bearer ' + token
- },
- body: formData
- });
- })
- .then(response => {
- if (!response.ok) {
- return response.json().then(data => {
- throw new Error(data.error || 'Failed to update warranty');
- });
- }
- return response.json();
- })
- .then(data => {
- hideLoadingSpinner();
- showToast('Warranty updated successfully', 'success');
- closeModals();
-
- // Always reload from server to ensure we get the latest data including product photo paths
- console.log('Reloading warranties after edit to ensure latest data including product photos');
- loadWarranties(true).then(() => {
- console.log('Warranties reloaded after editing warranty');
- applyFilters();
- // Load secure images for the updated cards - additional call to ensure they load
- setTimeout(() => {
- console.log('Loading secure images for updated warranty cards');
- loadSecureImages();
- }, 200); // Slightly longer delay to ensure everything is rendered
-
- // Always close the notes modal if open, to ensure UI is in sync
- const notesModal = document.getElementById('notesModal');
- if (notesModal && notesModal.style.display === 'block') {
- notesModal.style.display = 'none';
- }
-
- console.log('Warranty updated and reloaded from server');
-
- // Auto-link any documents that were uploaded to Paperless-ngx
- if ((invoiceFile || manualFile || otherDocumentFile) && currentWarrantyId) {
- console.log('[Auto-Link] Starting automatic document linking after warranty update');
-
- // Collect filename information for intelligent searching
- const fileInfo = {};
- if (invoiceFile) fileInfo.invoice = invoiceFile.name;
- if (manualFile) fileInfo.manual = manualFile.name;
- if (otherDocumentFile) fileInfo.other = otherDocumentFile.name;
-
- setTimeout(() => {
- autoLinkRecentDocuments(currentWarrantyId, ['invoice', 'manual', 'other'], 10, 10000, fileInfo);
- }, 3000); // Wait 3 seconds for Paperless-ngx to process the documents
- }
- }).catch(error => {
- console.error('Error reloading warranties after edit:', error);
- });
- })
- .catch(error => {
- hideLoadingSpinner();
- console.error('Error updating warranty:', error);
- showToast(error.message || 'Failed to update warranty', 'error');
- });
-}
-
-// Function to populate tag filter dropdown
-function populateTagFilter() {
- const tagFilter = document.getElementById('tagFilter');
- if (!tagFilter) return;
-
- // Clear existing options (except "All Tags")
- while (tagFilter.options.length > 1) {
- tagFilter.remove(1);
- }
-
- // Create a Set to store unique tag names
- const uniqueTags = new Set();
-
- // Collect all unique tags from warranties
- warranties.forEach(warranty => {
- if (warranty.tags && Array.isArray(warranty.tags)) {
- warranty.tags.forEach(tag => {
- uniqueTags.add(JSON.stringify({id: tag.id, name: tag.name, color: tag.color}));
- });
- }
- });
-
- // Sort tags alphabetically by name
- const sortedTags = Array.from(uniqueTags)
- .map(tagJson => JSON.parse(tagJson))
- .sort((a, b) => a.name.localeCompare(b.name));
-
- // Add options to the dropdown
- // Add options to the dropdown
- sortedTags.forEach(tag => {
- const option = document.createElement('option');
- option.value = tag.id;
- option.textContent = tag.name; // Reverted to textContent
- // Apply background color directly for now, acknowledging potential contrast issues
- // option.style.backgroundColor = tag.color; // Removed to prevent individual option background colors
- tagFilter.appendChild(option);
- });
-}
-
-// Function to populate vendor filter dropdown
-function populateVendorFilter() {
- const vendorFilterElement = document.getElementById('vendorFilter');
- if (!vendorFilterElement) return;
-
- // Clear existing options (except "All Vendors")
- while (vendorFilterElement.options.length > 1) {
- vendorFilterElement.remove(1);
- }
-
- // Create a Set to store unique vendor names (case-insensitive)
- const uniqueVendors = new Set();
-
- // Collect all unique, non-empty vendors from warranties
- warranties.forEach(warranty => {
- if (warranty.vendor && warranty.vendor.trim() !== '') {
- uniqueVendors.add(warranty.vendor.trim().toLowerCase());
- }
- });
-
- // Sort vendors alphabetically (after converting back to original case for display if needed, or just use lowercase)
- // For simplicity, we'll sort the lowercase versions and display them as is.
- // If original casing is important, a map could be used to store original values.
- const sortedVendors = Array.from(uniqueVendors).sort((a, b) => a.localeCompare(b));
-
- // Add options to the dropdown
- sortedVendors.forEach(vendor => {
- const option = document.createElement('option');
- option.value = vendor; // Use lowercase for value consistency
- // Capitalize first letter for display
- option.textContent = vendor.charAt(0).toUpperCase() + vendor.slice(1);
- vendorFilterElement.appendChild(option);
- });
-}
-
-// Function to populate warranty type filter dropdown
-function populateWarrantyTypeFilter() {
- const warrantyTypeFilterElement = document.getElementById('warrantyTypeFilter');
- if (!warrantyTypeFilterElement) return;
-
- // Clear existing options (except "All Types")
- while (warrantyTypeFilterElement.options.length > 1) {
- warrantyTypeFilterElement.remove(1);
- }
-
- // Create a Set to store unique warranty types (case-insensitive)
- const uniqueWarrantyTypes = new Set();
-
- // Collect all unique, non-empty warranty types from warranties
- warranties.forEach(warranty => {
- if (warranty.warranty_type && warranty.warranty_type.trim() !== '') {
- uniqueWarrantyTypes.add(warranty.warranty_type.trim().toLowerCase());
- }
- });
-
- // Sort warranty types alphabetically
- const sortedWarrantyTypes = Array.from(uniqueWarrantyTypes).sort((a, b) => a.localeCompare(b));
-
- // Add options to the dropdown
- sortedWarrantyTypes.forEach(warrantyType => {
- const option = document.createElement('option');
- option.value = warrantyType; // Use lowercase for value consistency
- // Capitalize first letter for display
- option.textContent = warrantyType.charAt(0).toUpperCase() + warrantyType.slice(1);
- warrantyTypeFilterElement.appendChild(option);
- });
-}
-
-// --- Updated Function ---
-function handleLifetimeChange(event) {
- const checkbox = event ? event.target : isLifetimeCheckbox;
- const durationFields = warrantyDurationFields; // Use new container ID
- const yearsInput = warrantyDurationYearsInput;
- const monthsInput = warrantyDurationMonthsInput;
- const daysInput = warrantyDurationDaysInput;
- const warrantyEntryMethod = document.getElementById('warrantyEntryMethod');
-
- if (!checkbox || !durationFields || !yearsInput || !monthsInput || !daysInput) {
- console.error("Lifetime or duration elements not found in add form");
- return;
- }
-
- if (checkbox.checked) {
- // Hide warranty method selection and both input methods
- if (warrantyEntryMethod) warrantyEntryMethod.style.display = 'none';
- durationFields.style.display = 'none';
- if (exactExpirationField) exactExpirationField.style.display = 'none';
-
- // Clear and make fields not required
- yearsInput.required = false;
- monthsInput.required = false;
- daysInput.required = false;
- yearsInput.value = '';
- monthsInput.value = '';
- daysInput.value = '';
- if (exactExpirationDateInput) exactExpirationDateInput.value = '';
- } else {
- // Show warranty method selection
- if (warrantyEntryMethod) warrantyEntryMethod.style.display = 'block';
-
- // Call method change handler to show appropriate fields
- handleWarrantyMethodChange();
- }
-}
-
-// --- Updated Function ---
-function handleEditLifetimeChange(event) {
- const checkbox = event ? event.target : editIsLifetimeCheckbox;
- const durationFields = editWarrantyDurationFields; // Use new container ID
- const yearsInput = editWarrantyDurationYearsInput;
- const monthsInput = editWarrantyDurationMonthsInput;
- const daysInput = editWarrantyDurationDaysInput;
- const editWarrantyEntryMethod = document.getElementById('editWarrantyEntryMethod');
-
- if (!checkbox || !durationFields || !yearsInput || !monthsInput || !daysInput) {
- console.error("Lifetime or duration elements not found in edit form");
- return;
- }
-
- if (checkbox.checked) {
- // Hide warranty method selection and both input methods
- if (editWarrantyEntryMethod) editWarrantyEntryMethod.style.display = 'none';
- durationFields.style.display = 'none';
- if (editExactExpirationField) editExactExpirationField.style.display = 'none';
-
- // Clear and make fields not required
- yearsInput.required = false;
- monthsInput.required = false;
- daysInput.required = false;
- yearsInput.value = '';
- monthsInput.value = '';
- daysInput.value = '';
- if (editExactExpirationDateInput) editExactExpirationDateInput.value = '';
- } else {
- // Show warranty method selection
- if (editWarrantyEntryMethod) editWarrantyEntryMethod.style.display = 'block';
-
- // Call method change handler to show appropriate fields
- handleEditWarrantyMethodChange();
- }
-}
-
-// --- Add this function to reset the wizard ---
-function resetAddWarrantyWizard() {
- console.log('Resetting Add Warranty Wizard...');
- // Reset the form fields
- if (warrantyForm) {
- warrantyForm.reset();
-
- // Explicitly set storage options to 'local'
- const storageTypes = ['invoice', 'manual'];
- storageTypes.forEach(type => {
- const localRadio = document.querySelector(`input[name="${type}Storage"][value="local"]`);
- if (localRadio) {
- localRadio.checked = true;
- }
- });
- }
-
- // Reset serial numbers container (remove all but the first input structure)
- if (serialNumbersContainer) {
- serialNumbersContainer.innerHTML = ''; // Clear it
- addSerialNumberInput(); // Add the initial input back
- }
-
- // Reset file input displays
- if (fileName) fileName.textContent = '';
- if (manualFileName) manualFileName.textContent = '';
- if (otherDocumentFileName) otherDocumentFileName.textContent = '';
-
- // Clear Paperless document selections (only for invoice and manual)
- clearPaperlessSelection('invoice');
- clearPaperlessSelection('manual');
-
- // Reset selected tags
- selectedTags = [];
- console.log('Resetting Add Warranty Wizard...');
-
- // No need to reset the form again as we already did it above
-
- // Reset serial numbers container (remove all but the first input structure)
- if (serialNumbersContainer) {
- serialNumbersContainer.innerHTML = ''; // Clear it
- addSerialNumberInput(); // Add the initial input back
- }
-
- // Reset file input displays
- if (fileName) fileName.textContent = '';
- if (manualFileName) manualFileName.textContent = '';
- if (otherDocumentFileName) otherDocumentFileName.textContent = '';
-
- // Reset selected tags
- selectedTags = [];
- renderSelectedTags(); // Update the display
-
- // Reset tabs to the first one
- // Use the globally defined tabContents if available
- const tabs = addWarrantyModal?.querySelectorAll('.form-tab');
- const contents = addWarrantyModal?.querySelectorAll('.tab-content');
- if (tabs && contents && tabs.length > 0 && contents.length > 0) {
- currentTabIndex = 0;
- switchToTab(0); // Use the existing function to switch
- } else {
- console.warn("Could not find tabs/contents inside addWarrantyModal to reset.");
- }
-
- // Clear any validation states
- addWarrantyModal?.querySelectorAll('.invalid').forEach(el => el.classList.remove('invalid'));
- addWarrantyModal?.querySelectorAll('.validation-message').forEach(el => el.remove());
-
- // Reset lifetime checkbox state if needed (ensure handler runs)
- if (isLifetimeCheckbox) {
- isLifetimeCheckbox.checked = false; // Explicitly uncheck
- handleLifetimeChange({ target: isLifetimeCheckbox }); // Trigger handler to reset visibility/required state
- }
-}
-
-// --- Modify setupUIEventListeners or add this within DOMContentLoaded ---
-function setupModalTriggers() {
- // Show Add Warranty Modal
- if (showAddWarrantyBtn && addWarrantyModal) {
- showAddWarrantyBtn.addEventListener('click', () => {
- resetAddWarrantyWizard(); // Reset before showing
- addWarrantyModal.classList.add('active');
- initFormTabs(); // Initialize tabs only when modal is shown
- switchToTab(0); // Ensure the first tab content is displayed correctly after reset
-
- // Set currency dropdown to user's preferred currency after form reset
- const preferredCurrencyCode = getCurrencyCode();
- if (currencySelect && preferredCurrencyCode) {
- currencySelect.value = preferredCurrencyCode;
- console.log(`[Modal Open] Set currency dropdown to user preference: ${preferredCurrencyCode}`);
- }
-
- // Update currency symbols and positioning for the add form
- const symbol = getCurrencySymbol();
- const position = getCurrencyPosition();
- updateFormCurrencyPosition(symbol, position);
-
- // Trigger currency positioning after modal is visible
- setTimeout(() => {
- if (position === 'right') {
- const addPriceInput = document.getElementById('purchasePrice');
- const addCurrencySymbol = document.getElementById('addCurrencySymbol');
- if (addPriceInput && addCurrencySymbol) {
- // Force update the currency position now that modal is visible
- const wrapper = addPriceInput.closest('.price-input-wrapper');
- if (wrapper && wrapper.classList.contains('currency-right')) {
- const updateEvent = new Event('focus');
- addPriceInput.dispatchEvent(updateEvent);
- const blurEvent = new Event('blur');
- addPriceInput.dispatchEvent(blurEvent);
- }
- }
- }
- }, 200);
- });
- }
-
- // Hide Add Warranty Modal (using existing close logic)
- if (addWarrantyModal) {
- // Close button inside modal
- const closeBtn = addWarrantyModal.querySelector('.close-btn');
- if (closeBtn) {
- closeBtn.addEventListener('click', () => {
- addWarrantyModal.classList.remove('active');
- resetAddWarrantyWizard(); // Reset on close
- });
- }
- // REMOVED: Backdrop click listener
- /*
- addWarrantyModal.addEventListener('click', (e) => {
- if (e.target === addWarrantyModal) {
- addWarrantyModal.classList.remove('active');
- resetAddWarrantyWizard(); // Reset on close
- }
- });
- */
- // Optional: Cancel button in footer if you add one
- // ... (cancel button logic remains unchanged)
- }
-
- // --- Edit Modal Triggers (Keep existing logic) ---
- // Close edit/delete modals when clicking outside or on close button
- document.querySelectorAll('#editModal, #deleteModal, #archiveModal, [data-dismiss="modal"]').forEach(element => {
- element.addEventListener('click', (e) => {
- // Check if the click is on the backdrop itself OR a dismiss button
- if (e.target === element || e.target.matches('[data-dismiss="modal"]')) {
- // Find the closest modal backdrop to the element clicked
- const modalToClose = e.target.closest('.modal-backdrop');
- if (modalToClose) {
- // *** ADD CHECK: Do NOT close addWarrantyModal or editModal via this general listener for backdrop clicks ***
- if ((modalToClose.id === 'addWarrantyModal' || modalToClose.id === 'editModal') && e.target === modalToClose) {
- return; // Ignore backdrop clicks for the add and edit modals here
- }
- // *** END ADD CHECK ***
-
- modalToClose.classList.remove('active');
- // Reset edit form state if closing edit modal
- if (modalToClose.id === 'editModal') {
- // Optional: Add any edit form reset logic here if needed
- }
- }
- }
- });
- });
-
- // Prevent modal content clicks from closing the modal (Keep for all modals)
- document.querySelectorAll('.modal').forEach(modal => {
- modal.addEventListener('click', (e) => {
- e.stopPropagation();
- });
- });
-}
-
-// --- CSV Import Functionality ---
-
-async function handleImport(file) {
- if (!file) {
- showToast('No file selected.', 'warning');
- return;
- }
-
- if (!file.name.toLowerCase().endsWith('.csv')) {
- showToast('Invalid file type. Please select a .csv file.', 'error');
- return;
- }
-
- // Show loading indicator
- showLoadingSpinner();
-
- const formData = new FormData();
- formData.append('csv_file', file);
-
- try {
- // const token = localStorage.getItem('token'); // Incorrect key
- const token = localStorage.getItem('auth_token'); // Correct key used elsewhere
- if (!token) {
- showToast('Authentication error. Please log in again.', 'error');
- hideLoadingSpinner();
- // Maybe redirect to login: window.location.href = '/login.html';
- return;
- }
-
- const response = await fetch('/api/warranties/import', {
- method: 'POST',
- headers: {
- // Content-Type is automatically set by browser when using FormData
- 'Authorization': `Bearer ${token}`
- },
- body: formData
- });
-
- hideLoadingSpinner();
- const result = await response.json();
-
- if (response.ok) {
- const { success_count, failure_count, errors } = result;
- let message = `${success_count} warranties imported successfully.`;
- if (failure_count > 0) {
- message += ` ${failure_count} rows failed.`;
- // Log detailed errors to the console for now
- console.warn('Import errors:', errors);
- // Consider showing errors in a modal or separate report later
- }
- showToast(message, 'success');
-
- // ***** FIX: Reload the tags list *****
- console.log("Import successful, reloading tags...");
- await loadTags(true); // Fetch the updated list of all tags
- // ***** END FIX *****
-
- // Add a small delay to ensure backend has processed the data
- await new Promise(resolve => setTimeout(resolve, 500));
-
- // Await the warranties load to ensure UI is updated
- await loadWarranties(true);
-
- // Force a UI refresh by reapplying filters
- applyFilters();
- } else {
- showToast(`Import failed: ${result.error || 'Unknown error'}`, 'error');
- if (result.errors) {
- console.error('Detailed import errors:', result.errors);
- }
- }
-
- } catch (error) {
- hideLoadingSpinner();
- console.error('Error during file import:', error);
- showToast('An error occurred during import. Check console for details.', 'error');
- } finally {
- // Reset the file input so the user can select the same file again if needed
- if (csvFileInput) {
- csvFileInput.value = '';
- }
- }
-}
-
-// --- End CSV Import Functionality ---
-
-// --- Add Storage Event Listener for Real-time Sync ---
-window.addEventListener('storage', (event) => {
- const currentPrefix = getPreferenceKeyPrefix(); // Re-calculate prefix
- const viewKeysToWatch = [
- `${currentPrefix}defaultView`,
- 'viewPreference',
- `${currentPrefix}warrantyView`,
- // Add `${currentPrefix}viewPreference` if still used/relevant
- `${currentPrefix}viewPreference`
- ];
-
- // Check for view preference changes
- if (viewKeysToWatch.includes(event.key) && event.newValue) {
- console.log(`Storage event detected for view preference (${event.key}). New value: ${event.newValue}`);
- // Check if the new value is different from the current view to avoid loops
- if (event.newValue !== currentView) {
- // Ensure view buttons exist before switching (we're on the main page)
- if (gridViewBtn || listViewBtn || tableViewBtn) {
- switchView(event.newValue, false); // Apply change, don't re-save to API
- }
- } else {
- console.log('Storage event value matches current view, ignoring.');
- }
- }
-
- // --- Added: Check for date format changes ---
- if (event.key === 'dateFormat' && event.newValue) {
- console.log(`Storage event detected for dateFormat. New value: ${event.newValue}`);
- // Re-apply filters to re-render warranties with the new date format
- if (warrantiesList) { // Only apply if the warranty list exists on the page
- applyFilters();
- showToast('Date format updated.', 'info'); // Optional: Notify user
- }
- }
- // --- End Added Check ---
-
- // --- Added: Check for currency symbol changes ---
- if (event.key === `${currentPrefix}currencySymbol` && event.newValue) {
- console.log(`Storage event detected for ${currentPrefix}currencySymbol. New value: ${event.newValue}`);
- if (warrantiesList) { // Only apply if on the main page
- updateCurrencySymbols(); // Update symbols outside cards (e.g., in forms if they exist)
- applyFilters(); // Re-render cards to update symbols inside them
- showToast('Currency symbol updated.', 'info'); // Optional: Notify user
- }
- }
- // --- End Added Check ---
-});
-// --- End Storage Event Listener ---
-
-// Add modal HTML to the end of the body if not present (componentized)
-if (!document.getElementById('notesModal')) {
- if (window.components && window.components.notes && window.components.notes.ensureNotesModal) {
- window.components.notes.ensureNotesModal();
- } else {
- // Fallback: Build via DOM API
- const notesModal = document.createElement('div');
- notesModal.id = 'notesModal';
- notesModal.className = 'modal-backdrop';
- const modal = document.createElement('div'); modal.className = 'modal'; modal.style.maxWidth = '500px';
- const header = document.createElement('div'); header.className = 'modal-header';
- const title = document.createElement('h3'); title.className = 'modal-title'; title.textContent = 'Warranty Notes';
- const close = document.createElement('button'); close.className = 'close-btn'; close.id = 'closeNotesModal'; close.textContent = '×';
- header.appendChild(title); header.appendChild(close);
- const body = document.createElement('div'); body.className = 'modal-body';
- const content = document.createElement('div'); content.id = 'notesModalContent'; content.style.whiteSpace = 'pre-line';
- const textarea = document.createElement('textarea'); textarea.id = 'notesModalTextarea'; textarea.style.display = 'none'; textarea.style.width = '100%'; textarea.style.minHeight = '100px';
- body.appendChild(content); body.appendChild(textarea);
- const footer = document.createElement('div'); footer.className = 'modal-footer'; footer.id = 'notesModalFooter';
- const editBtn = document.createElement('button'); editBtn.className = 'btn btn-secondary'; editBtn.id = 'editNotesBtn'; editBtn.textContent = 'Edit Notes';
- const editWBtn = document.createElement('button'); editWBtn.className = 'btn btn-info'; editWBtn.id = 'editWarrantyBtn'; editWBtn.textContent = 'Edit Warranty';
- const saveBtn = document.createElement('button'); saveBtn.className = 'btn btn-primary'; saveBtn.id = 'saveNotesBtn'; saveBtn.style.display = 'none'; saveBtn.textContent = 'Save';
- const cancelBtn = document.createElement('button'); cancelBtn.className = 'btn btn-danger'; cancelBtn.id = 'cancelEditNotesBtn'; cancelBtn.style.display = 'none'; cancelBtn.textContent = 'Cancel';
- footer.appendChild(editBtn); footer.appendChild(editWBtn); footer.appendChild(saveBtn); footer.appendChild(cancelBtn);
- modal.appendChild(header); modal.appendChild(body); modal.appendChild(footer);
- notesModal.appendChild(modal); document.body.appendChild(notesModal);
- document.getElementById('closeNotesModal').addEventListener('click', () => notesModal.classList.remove('active'));
- }
-
- // Add event listener for Edit Warranty button
- document.getElementById('editWarrantyBtn').addEventListener('click', async () => {
- // Find the current warranty data from the global array
- const currentWarranty = warranties.find(w => w.id === notesModalWarrantyId);
- if (currentWarranty) {
- console.log('[DEBUG] Edit Warranty button clicked, opening edit modal with warranty:', currentWarranty.id, 'notes:', currentWarranty.notes);
- // Close the notes modal first
- document.getElementById('notesModal').classList.remove('active');
- // Open the edit modal with current data
- await openEditModal(currentWarranty);
- } else {
- showToast(window.t('messages.warranty_not_found_refresh'), 'error');
- }
- });
-}
-
-// Add global to track which warranty is being edited in the notes modal
-let notesModalWarrantyId = null;
-let notesModalWarrantyObj = null;
-
-function showNotesModal(notes, warrantyOrId = null) {
- const notesModal = document.getElementById('notesModal');
- const notesModalContent = document.getElementById('notesModalContent');
- const notesModalTextarea = document.getElementById('notesModalTextarea');
- const editBtn = document.getElementById('editNotesBtn');
- const saveBtn = document.getElementById('saveNotesBtn');
- const cancelBtn = document.getElementById('cancelEditNotesBtn');
-
- // Support both (notes, warrantyObj) and (notes, id) for backward compatibility
- if (typeof warrantyOrId === 'object' && warrantyOrId !== null) {
- notesModalWarrantyId = warrantyOrId.id;
- notesModalWarrantyObj = warrantyOrId;
- } else {
- notesModalWarrantyId = warrantyOrId;
- // Try to find the warranty object from global warranties array
- notesModalWarrantyObj = warranties.find(w => w.id === notesModalWarrantyId) || null;
- }
-
- // Show note content, hide textarea and edit controls
- notesModalContent.style.display = '';
- notesModalContent.textContent = notes;
- notesModalTextarea.style.display = 'none';
- editBtn.style.display = '';
- saveBtn.style.display = 'none';
- cancelBtn.style.display = 'none';
-
- // Edit button handler
- editBtn.onclick = function() {
- notesModalContent.style.display = 'none';
- notesModalTextarea.style.display = '';
- // Use the current content from the modal display instead of the stale notes parameter
- notesModalTextarea.value = notesModalContent.textContent;
- editBtn.style.display = 'none';
- saveBtn.style.display = '';
- cancelBtn.style.display = '';
- notesModalTextarea.focus();
- };
- // Save button handler
- saveBtn.onclick = async function() {
- const newNote = notesModalTextarea.value.trim(); // Trim the note
- if (!notesModalWarrantyId || !notesModalWarrantyObj) {
- showToast('No warranty selected for note update', 'error');
- return;
- }
-
- // Frontend check for invalid duration before attempting to save notes
- if (!notesModalWarrantyObj.is_lifetime &&
- (parseInt(notesModalWarrantyObj.warranty_duration_years) || 0) === 0 &&
- (parseInt(notesModalWarrantyObj.warranty_duration_months) || 0) === 0 &&
- (parseInt(notesModalWarrantyObj.warranty_duration_days) || 0) === 0 &&
- !notesModalWarrantyObj.expiration_date) {
- showToast('Cannot save notes: The warranty has an invalid duration. Please edit the full warranty details to set a valid duration first.', 'error', 7000); // Longer toast duration
- return; // Prevent API call
- }
-
- // Save note via API, sending all required fields
- try {
- showLoadingSpinner();
- const token = localStorage.getItem('auth_token');
- const formData = new FormData();
- // --- Populate with existing data to avoid clearing fields ---
- formData.append('product_name', notesModalWarrantyObj.product_name);
- formData.append('purchase_date', (notesModalWarrantyObj.purchase_date || '').split('T')[0]);
- formData.append('is_lifetime', notesModalWarrantyObj.is_lifetime ? 'true' : 'false');
- if (!notesModalWarrantyObj.is_lifetime) {
- // Append duration components instead of warranty_years
- formData.append('warranty_duration_years', notesModalWarrantyObj.warranty_duration_years || 0);
- formData.append('warranty_duration_months', notesModalWarrantyObj.warranty_duration_months || 0);
- formData.append('warranty_duration_days', notesModalWarrantyObj.warranty_duration_days || 0);
-
- // If all duration fields are 0 but we have an expiration date, this was created with exact date method
- const isExactDateWarranty = (notesModalWarrantyObj.warranty_duration_years || 0) === 0 &&
- (notesModalWarrantyObj.warranty_duration_months || 0) === 0 &&
- (notesModalWarrantyObj.warranty_duration_days || 0) === 0 &&
- notesModalWarrantyObj.expiration_date;
-
- if (isExactDateWarranty) {
- // For exact date warranties, send the expiration date as exact_expiration_date
- formData.append('exact_expiration_date', notesModalWarrantyObj.expiration_date.split('T')[0]);
- }
- }
- if (notesModalWarrantyObj.product_url) {
- formData.append('product_url', notesModalWarrantyObj.product_url);
- }
- if (notesModalWarrantyObj.purchase_price !== null && notesModalWarrantyObj.purchase_price !== undefined) { // Check for null/undefined
- formData.append('purchase_price', notesModalWarrantyObj.purchase_price);
- }
- // Correctly append serial numbers
- if (notesModalWarrantyObj.serial_numbers && Array.isArray(notesModalWarrantyObj.serial_numbers)) {
- notesModalWarrantyObj.serial_numbers.forEach(sn => {
- // Ensure sn is treated as a string before trim, and append with [] for array
- if (sn && String(sn).trim() !== '') {
- formData.append('serial_numbers[]', String(sn).trim());
- }
- });
- }
- // If notesModalWarrantyObj.serial_numbers is empty or not an array,
- // no 'serial_numbers[]' fields will be appended, which is typically interpreted as an empty list by backends.
-
- if (notesModalWarrantyObj.tags && Array.isArray(notesModalWarrantyObj.tags)) {
- const tagIds = notesModalWarrantyObj.tags.map(tag => tag.id);
- formData.append('tag_ids', JSON.stringify(tagIds));
- }
- // Send empty array if no tags exist or are provided
- else {
- formData.append('tag_ids', JSON.stringify([]));
- }
- // --- End Populate ---
-
- formData.append('notes', newNote); // Append the potentially empty, trimmed note
-
- // Add vendor/retailer to form data
- const editVendorOrRetailer = document.getElementById('editVendorOrRetailer');
- formData.append('vendor', editVendorOrRetailer ? editVendorOrRetailer.value.trim() : '');
-
- const response = await fetch(`/api/warranties/${notesModalWarrantyId}`, { // Added await and response handling
- method: 'PUT',
- headers: {
- 'Authorization': 'Bearer ' + token
- },
- body: formData
- });
-
- if (!response.ok) { // Check if the API call was successful
- const errorData = await response.json().catch(() => ({})); // Try to parse error, default to empty object
- throw new Error(errorData.error || `Failed to update note (Status: ${response.status})`);
- }
-
-
- hideLoadingSpinner();
- showToast('Note updated', 'success');
-
- // Update the warranty in the global warranties array immediately
- const warrantyIndex = warranties.findIndex(w => w.id === notesModalWarrantyId);
- if (warrantyIndex !== -1) {
- warranties[warrantyIndex].notes = newNote;
- }
-
- // --- Updated UI logic ---
- if (newNote === '') {
- // If the note is now empty, close the modal
- document.getElementById('notesModal').classList.remove('active');
- } else {
- // If note is not empty, update the view and stay in the modal
- notesModalContent.textContent = newNote;
- notesModalContent.style.display = '';
- notesModalTextarea.style.display = 'none';
- editBtn.style.display = '';
- saveBtn.style.display = 'none';
- cancelBtn.style.display = 'none';
- // Update the local warranty object's notes
- if (notesModalWarrantyObj) {
- notesModalWarrantyObj.notes = newNote;
- }
- }
- // --- End Updated UI logic ---
-
- // Refresh warranties list and THEN update UI
- await loadWarranties(true); // Wait for data refresh
- applyFilters(); // Re-render the list with updated data
-
- } catch (e) {
- hideLoadingSpinner();
- console.error("Error updating note:", e); // Log the error
- showToast(e.message || 'Failed to update note', 'error'); // Show specific error if available
- }
- };
- // Cancel button handler
- cancelBtn.onclick = function() {
- notesModalContent.style.display = '';
- notesModalTextarea.style.display = 'none';
- editBtn.style.display = '';
- saveBtn.style.display = 'none';
- cancelBtn.style.display = 'none';
- };
- notesModal.classList.add('active');
-}
-
-// Utility to get currency symbol from preferences/localStorage
-function getCurrencySymbol() {
- // Use the global prefix determined after auth ready
- let prefix = userPreferencePrefix; // Use let to allow default override
- if (!prefix) {
- console.warn('[getCurrencySymbol] User preference prefix not set yet, defaulting prefix to user_');
- prefix = 'user_'; // Default prefix if called too early
- }
- console.log(`[getCurrencySymbol] Using determined prefix: ${prefix}`);
- let symbol = '$'; // Default value
-
- const rawValue = localStorage.getItem(`${prefix}currencySymbol`);
- console.log(`[getCurrencySymbol Debug] Raw value read from localStorage key '${prefix}currencySymbol':`, rawValue);
- // +++ END ADDED LOG +++
-
- // --- Priority 1: Load from individual key --- (Saved by settings-new.js)
- const individualSymbol = rawValue; // Use the already read value
- if (individualSymbol) { // Check uses the already read value
- symbol = individualSymbol;
- console.log(`[getCurrencySymbol] Loaded symbol from individual key (${prefix}currencySymbol): ${symbol}`);
- return symbol;
- }
-
- // --- Priority 2: Load from preferences object (Legacy/Fallback) ---
- try {
- const prefsString = localStorage.getItem(`${prefix}preferences`);
- console.log(`[getCurrencySymbol] Read prefsString for ${prefix}preferences:`, prefsString);
- if (prefsString) {
- const prefs = JSON.parse(prefsString);
- if (prefs && prefs.currency_symbol) {
- symbol = prefs.currency_symbol;
- console.log(`[getCurrencySymbol] Loaded symbol from object key (${prefix}preferences): ${symbol}`);
- }
- }
- } catch (e) {
- console.error(`Error reading ${prefix}preferences from localStorage:`, e);
- // Keep the default '$' symbol in case of error parsing the object
- }
-
- console.log(`[getCurrencySymbol] Returning symbol (default or from object): ${symbol}`);
- return symbol;
-}
-
-// Function to get user's preferred currency code
-function getCurrencyCode() {
- // Use the global prefix determined after auth ready
- let prefix = userPreferencePrefix;
- if (!prefix) {
- console.warn('[getCurrencyCode] User preference prefix not set yet, defaulting prefix to user_');
- prefix = 'user_';
- }
- console.log(`[getCurrencyCode] Using determined prefix: ${prefix}`);
-
- // Default to USD
- let currencyCode = 'USD';
-
- // Try to get currency code from localStorage
- const rawValue = localStorage.getItem(`${prefix}currencyCode`);
- console.log(`[getCurrencyCode Debug] Raw value read from localStorage key '${prefix}currencyCode':`, rawValue);
-
- if (rawValue) {
- currencyCode = rawValue;
- console.log(`[getCurrencyCode] Loaded currency code from individual key (${prefix}currencyCode): ${currencyCode}`);
- return currencyCode;
- }
-
- // Fallback: Try to derive currency code from symbol
- const symbol = getCurrencySymbol();
- const symbolToCurrencyMap = {
- '$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'JPY', '₹': 'INR', '₩': 'KRW',
- 'CHF': 'CHF', 'C$': 'CAD', 'A$': 'AUD', 'kr': 'SEK', 'zł': 'PLN',
- 'Kč': 'CZK', 'Ft': 'HUF', '₽': 'RUB', 'R$': 'BRL', '₦': 'NGN',
- '₪': 'ILS', '₺': 'TRY', '₨': 'PKR', '৳': 'BDT', '฿': 'THB',
- '₫': 'VND', 'RM': 'MYR', 'S$': 'SGD', 'Rp': 'IDR', '₱': 'PHP',
- 'NT$': 'TWD', 'HK$': 'HKD', '₮': 'MNT', '₸': 'KZT', '₼': 'AZN',
- '₾': 'GEL', '₴': 'UAH', 'NZ$': 'NZD'
- };
-
- if (symbolToCurrencyMap[symbol]) {
- currencyCode = symbolToCurrencyMap[symbol];
- console.log(`[getCurrencyCode] Derived currency code from symbol '${symbol}': ${currencyCode}`);
- } else {
- console.log(`[getCurrencyCode] Could not derive currency code from symbol '${symbol}', using default: ${currencyCode}`);
- }
-
- return currencyCode;
-}
-
-// Function to load currencies from API and populate dropdowns
-async function loadCurrencies() {
- try {
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
- const response = await fetch('/api/currencies', {
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- });
- if (!response.ok) {
- throw new Error('Failed to fetch currencies');
- }
-
- const currencies = await response.json();
-
- // Get user's preferred currency code for default selection
- const preferredCurrencyCode = getCurrencyCode();
-
- // Populate add warranty currency dropdown
- if (currencySelect) {
- currencySelect.innerHTML = '';
- currencies.forEach(currency => {
- const option = document.createElement('option');
- option.value = currency.code;
- option.textContent = `${currency.code} - ${currency.name} (${currency.symbol})`;
- currencySelect.appendChild(option);
- });
-
- // Set default selection to user's preferred currency
- console.log(`[loadCurrencies] Preferred currency code: ${preferredCurrencyCode}`);
- console.log(`[loadCurrencies] Available currency options:`, Array.from(currencySelect.options).map(opt => opt.value));
-
- if (preferredCurrencyCode) {
- // Use setTimeout to ensure DOM is fully updated
- setTimeout(() => {
- currencySelect.value = preferredCurrencyCode;
- console.log(`[loadCurrencies] Set add warranty currency default to: ${preferredCurrencyCode}`);
- console.log(`[loadCurrencies] Current selected value: ${currencySelect.value}`);
-
- // Trigger change event to update any dependent UI
- const changeEvent = new Event('change', { bubbles: true });
- currencySelect.dispatchEvent(changeEvent);
- }, 10);
- } else {
- console.log(`[loadCurrencies] No preferred currency code found, keeping default USD`);
- }
- }
-
- // Populate edit warranty currency dropdown
- if (editCurrencySelect) {
- editCurrencySelect.innerHTML = '';
- currencies.forEach(currency => {
- const option = document.createElement('option');
- option.value = currency.code;
- option.textContent = `${currency.code} - ${currency.name} (${currency.symbol})`;
- editCurrencySelect.appendChild(option);
- });
- }
-
- console.log('Currencies loaded successfully');
- } catch (error) {
- console.error('Error loading currencies:', error);
- // Fallback to USD if loading fails
- if (currencySelect) {
- currencySelect.innerHTML = '<option value="USD">USD - US Dollar ($)</option>';
- }
- if (editCurrencySelect) {
- editCurrencySelect.innerHTML = '<option value="USD">USD - US Dollar ($)</option>';
- }
- }
-}
-
-function getCurrencySymbolByCode(currencyCode) {
- const currencyMap = {
- 'USD': '$', 'EUR': '€', 'GBP': '£', 'JPY': '¥', 'CNY': '¥', 'INR': '₹', 'KRW': '₩',
- 'CHF': 'CHF', 'CAD': 'C$', 'AUD': 'A$', 'SEK': 'kr', 'NOK': 'kr', 'DKK': 'kr',
- 'PLN': 'zł', 'CZK': 'Kč', 'HUF': 'Ft', 'BGN': 'лв', 'RON': 'lei', 'HRK': 'kn',
- 'RUB': '₽', 'BRL': 'R$', 'MXN': '$', 'ARS': '$', 'CLP': '$', 'COP': '$',
- 'PEN': 'S/', 'VES': 'Bs', 'ZAR': 'R', 'EGP': '£', 'NGN': '₦', 'KES': 'KSh',
- 'GHS': '₵', 'MAD': 'DH', 'TND': 'DT', 'AED': 'AED', 'SAR': 'SR', 'QAR': 'QR',
- 'KWD': 'KD', 'BHD': 'BD', 'OMR': 'OR', 'JOD': 'JD', 'LBP': 'LL', 'ILS': '₪',
- 'TRY': '₺', 'IRR': '﷼', 'PKR': '₨', 'BDT': '৳', 'LKR': 'Rs', 'NPR': 'Rs',
- 'BTN': 'Nu', 'MMK': 'K', 'THB': '฿', 'VND': '₫', 'LAK': '₭', 'KHR': '៛',
- 'MYR': 'RM', 'SGD': 'S$', 'IDR': 'Rp', 'PHP': '₱', 'TWD': 'NT$', 'HKD': 'HK$',
- 'MOP': 'MOP', 'KPW': '₩', 'MNT': '₮', 'KZT': '₸', 'UZS': 'soʻm', 'TJS': 'SM',
- 'KGS': 'с', 'TMT': 'T', 'AFN': '؋', 'AMD': '֏', 'AZN': '₼', 'GEL': '₾',
- 'MDL': 'L', 'UAH': '₴', 'BYN': 'Br', 'RSD': 'дин', 'MKD': 'ден', 'ALL': 'L',
- 'BAM': 'KM', 'ISK': 'kr', 'FJD': 'FJ$', 'PGK': 'K', 'SBD': 'SI$', 'TOP': 'T$',
- 'VUV': 'VT', 'WST': 'WS$', 'XPF': '₣', 'NZD': 'NZ$'
- };
- return currencyMap[currencyCode] || currencyCode;
-}
-
-function getCurrencyPosition() {
- let prefix = userPreferencePrefix;
- if (!prefix) {
- console.warn('[getCurrencyPosition] User preference prefix not set yet, defaulting prefix to user_');
- prefix = 'user_';
- }
-
- let position = 'left'; // Default position
- const rawValue = localStorage.getItem(`${prefix}currencyPosition`);
- console.log(`[getCurrencyPosition] Raw value from localStorage (${prefix}currencyPosition):`, rawValue);
-
- if (rawValue) {
- position = rawValue;
- console.log(`[getCurrencyPosition] Loaded position from localStorage: ${position}`);
- } else {
- console.log(`[getCurrencyPosition] No position found, using default: ${position}`);
- }
-
- return position;
-}
-
-function formatCurrencyHTML(amount, symbol, position) {
- const formattedAmount = parseFloat(amount).toFixed(2);
-
- if (position === 'right') {
- return `<span>${formattedAmount}</span><span class="currency-symbol currency-right">${symbol}</span>`;
- } else {
- return `<span class="currency-symbol">${symbol}</span><span>${formattedAmount}</span>`;
- }
-}
-
-function updateCurrencySymbols() {
- const symbol = getCurrencySymbol();
- const position = getCurrencyPosition();
- console.log(`Updating currency symbols to: ${symbol}, position: ${position}`);
-
- // Update all currency symbols
- const elements = document.querySelectorAll('.currency-symbol');
- console.log(`Found ${elements.length} elements with class 'currency-symbol'.`);
- elements.forEach(el => {
- el.textContent = symbol;
- });
-
- // Update form currency positioning
- updateFormCurrencyPosition(symbol, position);
-}
-
-function updateFormCurrencyPosition(symbol, position) {
- // Handle add warranty form
- const addPriceWrapper = document.getElementById('addPriceInputWrapper');
- const addCurrencySymbol = document.getElementById('addCurrencySymbol');
- const addPriceInput = document.getElementById('purchasePrice');
-
- if (addPriceWrapper && addCurrencySymbol) {
- addCurrencySymbol.textContent = symbol;
- if (position === 'right') {
- addPriceWrapper.classList.add('currency-right');
- // Set up dynamic positioning for right-aligned currency
- if (addPriceInput) {
- setupDynamicCurrencyPosition(addPriceInput, addCurrencySymbol);
- }
- } else {
- addPriceWrapper.classList.remove('currency-right');
- // Reset any dynamic positioning
- if (addCurrencySymbol) {
- addCurrencySymbol.style.right = '';
- }
- }
- console.log(`Updated add form currency position: ${position}`);
- }
-
- // Handle edit warranty form
- const editPriceWrapper = document.getElementById('editPriceInputWrapper');
- const editCurrencySymbol = document.getElementById('editCurrencySymbol');
- const editPriceInput = document.getElementById('editPurchasePrice');
-
- if (editPriceWrapper && editCurrencySymbol) {
- editCurrencySymbol.textContent = symbol;
- if (position === 'right') {
- editPriceWrapper.classList.add('currency-right');
- // Set up dynamic positioning for right-aligned currency
- if (editPriceInput) {
- setupDynamicCurrencyPosition(editPriceInput, editCurrencySymbol);
- }
- } else {
- editPriceWrapper.classList.remove('currency-right');
- // Reset any dynamic positioning
- if (editCurrencySymbol) {
- editCurrencySymbol.style.right = '';
- }
- }
- console.log(`Updated edit form currency position: ${position}`);
- }
-}
-
-function setupDynamicCurrencyPosition(input, currencySymbol) {
- if (!input || !currencySymbol) return;
-
- function updatePosition() {
- const wrapper = input.closest('.price-input-wrapper');
- if (!wrapper || !wrapper.classList.contains('currency-right')) return;
-
- // Wait for elements to be fully rendered
- if (wrapper.offsetWidth === 0) {
- setTimeout(updatePosition, 50);
- return;
- }
-
- // Get the input value or placeholder
- const text = input.value || input.placeholder || '0.00';
-
- // Create a temporary element to measure text width
- const tempSpan = document.createElement('span');
- tempSpan.style.visibility = 'hidden';
- tempSpan.style.position = 'absolute';
- tempSpan.style.fontSize = window.getComputedStyle(input).fontSize;
- tempSpan.style.fontFamily = window.getComputedStyle(input).fontFamily;
- tempSpan.style.fontWeight = window.getComputedStyle(input).fontWeight;
- tempSpan.style.letterSpacing = window.getComputedStyle(input).letterSpacing;
- tempSpan.textContent = text;
-
- document.body.appendChild(tempSpan);
- const textWidth = tempSpan.offsetWidth;
- document.body.removeChild(tempSpan);
-
- // Calculate position: input padding + text width + small gap
- const inputPaddingLeft = parseInt(window.getComputedStyle(input).paddingLeft) || 12;
- const gap = 4; // Small gap between text and currency symbol
- const wrapperWidth = wrapper.offsetWidth;
- const rightPosition = Math.max(8, wrapperWidth - inputPaddingLeft - textWidth - gap - 20);
-
- currencySymbol.style.right = rightPosition + 'px';
- console.log(`[Dynamic Currency] Positioned currency symbol at ${rightPosition}px from right for text: "${text}"`);
- }
-
- // Update position on various events
- input.addEventListener('input', updatePosition);
- input.addEventListener('focus', updatePosition);
- input.addEventListener('blur', updatePosition);
-
- // Initial positioning with better timing
- // Use requestAnimationFrame to ensure DOM is ready
- requestAnimationFrame(() => {
- updatePosition();
- // Also set up additional fallback timers
- setTimeout(updatePosition, 100);
- setTimeout(updatePosition, 300);
- });
-}
-
-// If you want to update currency symbols live when storage changes (e.g. settings page open in another tab):
-window.addEventListener('storage', function(e) {
- const prefix = getPreferenceKeyPrefix();
- // Only update if the main preferences object for the current user type changed
- if (e.key === `${prefix}preferences`) {
- console.log(`Storage event detected for ${prefix}preferences. Updating currency symbols.`);
- updateCurrencySymbols();
- }
- // Also update when currency position changes
- if (e.key === `${prefix}currencyPosition`) {
- console.log(`Storage event detected for ${prefix}currencyPosition. Re-rendering warranties to update currency position.`);
- // Update forms immediately
- const symbol = getCurrencySymbol();
- const position = getCurrencyPosition();
- updateFormCurrencyPosition(symbol, position);
- // Re-render warranties to apply new currency position
- if (typeof processAllWarranties === 'function') {
- processAllWarranties();
- }
- }
-});
-
-// +++ NEW FUNCTION TO LOAD PREFS AND SAVE TO LOCALSTORAGE +++
-async function loadAndApplyUserPreferences(isAuthenticated) { // Added isAuthenticated parameter
- // Use the global prefix determined after auth ready
- let prefix = userPreferencePrefix; // <<< CHANGED const to let
- if (!prefix) {
- console.error('[Prefs Loader] Cannot load preferences: User preference prefix not set yet. Defaulting to user_');
- // Setting a default might be risky if the user *is* admin but prefix wasn't set in time.
- // Consider how authStateReady ensures prefix is set before this runs.
- // For now, let's try defaulting, but this might need review.
- prefix = 'user_';
- }
- console.log(`[Prefs Loader] Attempting to load preferences using prefix: ${prefix}, isAuthenticated: ${isAuthenticated}`);
-
- if (isAuthenticated && window.auth) { // Use passed isAuthenticated and check if window.auth exists
- const token = window.auth.getToken(); // Still need token for the API call
- if (!token) {
- console.error('[Prefs Loader] Cannot load preferences: No auth token found, even though isAuthenticated was true.');
- return; // Exit if no token
- }
-
- try {
- console.log('[Prefs Loader] Fetching /api/auth/preferences with token.');
- const response = await fetch('/api/auth/preferences', {
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- });
-
- if (response.ok) {
- const apiPrefs = await response.json();
- console.log('[Prefs Loader] Preferences loaded from API:', apiPrefs);
-
- // Save relevant prefs to localStorage
- if (apiPrefs.currency_symbol) {
- localStorage.setItem(`${prefix}currencySymbol`, apiPrefs.currency_symbol);
- console.log(`[Prefs Loader] Saved ${prefix}currencySymbol: ${apiPrefs.currency_symbol}`);
- }
- if (apiPrefs.currency_position) {
- localStorage.setItem(`${prefix}currencyPosition`, apiPrefs.currency_position);
- console.log(`[Prefs Loader] Saved ${prefix}currencyPosition: ${apiPrefs.currency_position}`);
- }
- if (apiPrefs.default_view) {
- localStorage.setItem(`${prefix}defaultView`, apiPrefs.default_view);
- console.log(`[Prefs Loader] Saved ${prefix}defaultView: ${apiPrefs.default_view}`);
- }
- // Apply theme from API and sync to localStorage
- if (apiPrefs.theme) {
- const isDark = apiPrefs.theme === 'dark';
- // Apply without triggering API save to avoid loops
- await saveThemePreference(isDark, false);
- console.log(`[Prefs Loader] Applied theme from API: ${apiPrefs.theme}`);
- }
- // Save filter preferences from API to localStorage
- if (apiPrefs.saved_filters) {
- localStorage.setItem(`${prefix}warrantyFilters`, JSON.stringify(apiPrefs.saved_filters));
- console.log(`[Prefs Loader] Saved ${prefix}warrantyFilters:`, apiPrefs.saved_filters);
- }
- if (apiPrefs.expiring_soon_days !== undefined) {
- localStorage.setItem(`${prefix}expiringSoonDays`, apiPrefs.expiring_soon_days);
- // Also update the global variable used by processWarrantyData
- expiringSoonDays = apiPrefs.expiring_soon_days;
- console.log(`[Prefs Loader] Saved ${prefix}expiringSoonDays: ${apiPrefs.expiring_soon_days}`);
- console.log(`[Prefs Loader] Updated global expiringSoonDays variable to: ${expiringSoonDays}`);
- }
- if (apiPrefs.date_format) {
- localStorage.setItem('dateFormat', apiPrefs.date_format);
- console.log(`[Prefs Loader] Saved dateFormat: ${apiPrefs.date_format}`);
- }
-
- // Optionally trigger immediate UI updates if needed, although renderWarranties will use these new values
- // updateCurrencySymbols();
-
- } else {
- const errorData = await response.json().catch(() => ({}));
- console.warn(`[Prefs Loader] Failed to load preferences from API: ${response.status}`, errorData.message || '');
- // Set defaults in localStorage maybe?
- if (!localStorage.getItem('dateFormat')) localStorage.setItem('dateFormat', 'MDY');
- if (!localStorage.getItem(`${prefix}currencySymbol`)) localStorage.setItem(`${prefix}currencySymbol`, '$');
- // etc.
- }
- } catch (error) {
- console.error('[Prefs Loader] Error fetching/applying preferences from API:', error);
- // Set defaults in localStorage on error?
- if (!localStorage.getItem('dateFormat')) localStorage.setItem('dateFormat', 'MDY');
- if (!localStorage.getItem(`${prefix}currencySymbol`)) localStorage.setItem(`${prefix}currencySymbol`, '$');
- // etc.
- }
- } else {
- console.warn('[Prefs Loader] Cannot load preferences: User not authenticated or auth module not available.');
- // Apply defaults if not authenticated?
- if (!localStorage.getItem('dateFormat')) localStorage.setItem('dateFormat', 'MDY');
- if (!localStorage.getItem(`${prefix}currencySymbol`)) localStorage.setItem(`${prefix}currencySymbol`, '$');
- // etc.
- }
-}
-// +++ END NEW FUNCTION +++
-
-// Warranty method change handlers
-function handleWarrantyMethodChange() {
- console.log('[DEBUG] handleWarrantyMethodChange called');
- const isLifetime = isLifetimeCheckbox && isLifetimeCheckbox.checked;
- const isDurationMethod = durationMethodRadio && durationMethodRadio.checked;
-
- console.log('[DEBUG] isLifetime:', isLifetime, 'isDurationMethod:', isDurationMethod);
- console.log('[DEBUG] Elements found:', {
- warrantyDurationFields: !!warrantyDurationFields,
- exactExpirationField: !!exactExpirationField,
- exactExpirationDateInput: !!exactExpirationDateInput
- });
-
- if (isLifetime) {
- // Hide both methods when lifetime is selected
- console.log('[DEBUG] Lifetime selected, hiding both methods');
- if (warrantyDurationFields) warrantyDurationFields.style.display = 'none';
- if (exactExpirationField) exactExpirationField.style.display = 'none';
- return;
- }
-
- if (isDurationMethod) {
- console.log('[DEBUG] Duration method selected');
- if (warrantyDurationFields) warrantyDurationFields.style.display = 'block';
- if (exactExpirationField) exactExpirationField.style.display = 'none';
- // Clear exact date when switching to duration
- if (exactExpirationDateInput) exactExpirationDateInput.value = '';
- } else {
- console.log('[DEBUG] Exact date method selected');
- if (warrantyDurationFields) warrantyDurationFields.style.display = 'none';
- if (exactExpirationField) exactExpirationField.style.display = 'block';
- // Clear duration fields when switching to exact date
- if (warrantyDurationYearsInput) warrantyDurationYearsInput.value = '';
- if (warrantyDurationMonthsInput) warrantyDurationMonthsInput.value = '';
- if (warrantyDurationDaysInput) warrantyDurationDaysInput.value = '';
- }
-}
-
-function handleEditWarrantyMethodChange() {
- console.log('[DEBUG] handleEditWarrantyMethodChange called');
- const isLifetime = editIsLifetimeCheckbox && editIsLifetimeCheckbox.checked;
- const isDurationMethod = editDurationMethodRadio && editDurationMethodRadio.checked;
-
- console.log('[DEBUG Edit] isLifetime:', isLifetime, 'isDurationMethod:', isDurationMethod);
- console.log('[DEBUG Edit] Radio button states:', {
- editDurationMethodRadio: editDurationMethodRadio ? editDurationMethodRadio.checked : 'element not found',
- editExactDateMethodRadio: editExactDateMethodRadio ? editExactDateMethodRadio.checked : 'element not found'
- });
- console.log('[DEBUG Edit] Elements found:', {
- editWarrantyDurationFields: !!editWarrantyDurationFields,
- editExactExpirationField: !!editExactExpirationField,
- editExactExpirationDateInput: !!editExactExpirationDateInput
- });
-
- if (isLifetime) {
- // Hide both methods when lifetime is selected
- console.log('[DEBUG Edit] Lifetime selected, hiding both methods');
- if (editWarrantyDurationFields) editWarrantyDurationFields.style.display = 'none';
- if (editExactExpirationField) editExactExpirationField.style.display = 'none';
- return;
- }
-
- if (isDurationMethod) {
- console.log('[DEBUG Edit] Duration method selected');
- if (editWarrantyDurationFields) {
- editWarrantyDurationFields.style.display = 'block';
- console.log('[DEBUG Edit] Set duration fields to block');
- }
- if (editExactExpirationField) {
- editExactExpirationField.style.display = 'none';
- console.log('[DEBUG Edit] Set exact date field to none');
- }
- // Clear exact date when switching to duration
- if (editExactExpirationDateInput) editExactExpirationDateInput.value = '';
- } else {
- console.log('[DEBUG Edit] Exact date method selected');
- if (editWarrantyDurationFields) {
- editWarrantyDurationFields.style.display = 'none';
- console.log('[DEBUG Edit] Set duration fields to none');
- }
- if (editExactExpirationField) {
- editExactExpirationField.style.display = 'block';
- console.log('[DEBUG Edit] Set exact date field to block');
- }
- // Clear duration fields when switching to exact date
- if (editWarrantyDurationYearsInput) editWarrantyDurationYearsInput.value = '';
- if (editWarrantyDurationMonthsInput) editWarrantyDurationMonthsInput.value = '';
- if (editWarrantyDurationDaysInput) editWarrantyDurationDaysInput.value = '';
- }
-}
-
-// Function to calculate duration between two dates
-function calculateDurationFromDates(startDate, endDate) {
- if (!startDate || !endDate) return null;
-
- try {
- const start = new Date(startDate);
- const end = new Date(endDate);
-
- if (isNaN(start.getTime()) || isNaN(end.getTime())) return null;
-
- let years = end.getFullYear() - start.getFullYear();
- let months = end.getMonth() - start.getMonth();
- let days = end.getDate() - start.getDate();
-
- // Adjust for negative days
- if (days < 0) {
- months--;
- const prevMonth = new Date(end.getFullYear(), end.getMonth(), 0);
- days += prevMonth.getDate();
- }
-
- // Adjust for negative months
- if (months < 0) {
- years--;
- months += 12;
- }
-
- return { years, months, days };
- } catch (error) {
- console.error('Error calculating duration:', error);
- return null;
- }
-}
-
-/**
- * Load secure images with authentication
- */
-async function loadSecureImages() {
- const token = localStorage.getItem('auth_token');
- if (!token) {
- console.log('[DEBUG] No auth token available for secure image loading');
- return;
- }
-
- // Also find images that may already have src but need to be refreshed
- const secureImages = document.querySelectorAll('img.secure-image[data-secure-src]');
- console.log(`[DEBUG] Found ${secureImages.length} secure images to load/refresh`);
-
- for (const img of secureImages) {
- try {
- const secureUrl = img.getAttribute('data-secure-src');
- console.log(`[DEBUG] Loading secure image: ${secureUrl}`);
-
- // Clean up existing blob URL if present
- const existingBlobUrl = img.getAttribute('data-blob-url');
- if (existingBlobUrl) {
- URL.revokeObjectURL(existingBlobUrl);
- img.removeAttribute('data-blob-url');
- }
-
- const response = await fetch(secureUrl, {
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- });
-
- if (response.ok) {
- const blob = await response.blob();
- const blobUrl = URL.createObjectURL(blob);
- img.src = blobUrl;
-
- // Clean up blob URL when image is removed from DOM
- img.addEventListener('load', () => {
- console.log(`[DEBUG] Secure image loaded successfully: ${secureUrl}`);
- }, { once: true });
-
- // Store blob URL for cleanup
- img.setAttribute('data-blob-url', blobUrl);
- } else {
- console.error(`[DEBUG] Failed to load secure image: ${secureUrl}, status: ${response.status}`);
- img.style.display = 'none';
- }
- } catch (error) {
- console.error(`[DEBUG] Error loading secure image:`, error);
- img.style.display = 'none';
- }
- }
-}
-
-// ============================================================================
-// Paperless-ngx Integration Functions
-// ============================================================================
-
-// Global variable to store Paperless-ngx enabled state
-let paperlessNgxEnabled = false;
-
-/**
- * Check if Paperless-ngx integration is enabled
- */
-async function checkPaperlessNgxStatus() {
- try {
- const token = localStorage.getItem('auth_token');
- if (!token) return false;
-
- const response = await fetch('/api/admin/settings', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (response.ok) {
- const settings = await response.json();
- paperlessNgxEnabled = settings.paperless_enabled === 'true';
- window.paperlessNgxEnabled = paperlessNgxEnabled; // Set global variable
- console.log('[Paperless-ngx] Integration status:', paperlessNgxEnabled);
- return paperlessNgxEnabled;
- }
- } catch (error) {
- console.error('[Paperless-ngx] Error checking status:', error);
- }
- return false;
-}
-
-/**
- * Initialize Paperless-ngx integration UI
- */
-async function initPaperlessNgxIntegration() {
- // Check if Paperless-ngx is enabled
- const isEnabled = await checkPaperlessNgxStatus();
-
- if (isEnabled) {
- // Show the info alert
- const infoAlert = document.getElementById('paperlessInfoAlert');
- if (infoAlert) {
- infoAlert.style.display = 'block';
- }
-
- // Show storage selection options for add modal (only invoice and manual)
- const storageSelections = [
- 'invoiceStorageSelection',
- 'manualStorageSelection'
- ];
-
- storageSelections.forEach(id => {
- const element = document.getElementById(id);
- if (element) {
- element.style.display = 'block';
- }
- });
-
- // Show storage selection options for edit modal (only invoice and manual)
- const editStorageSelections = [
- 'editInvoiceStorageSelection',
- 'editManualStorageSelection'
- ];
-
- editStorageSelections.forEach(id => {
- const element = document.getElementById(id);
- if (element) {
- element.style.display = 'block';
- }
- });
-
- // Show Paperless browse sections
- console.log('[Paperless-ngx] Calling togglePaperlessBrowseSections...');
- togglePaperlessBrowseSections();
-
- console.log('[Paperless-ngx] UI elements initialized and shown');
- } else {
- console.log('[Paperless-ngx] Integration disabled, hiding UI elements');
-
- // Hide Paperless browse sections
- console.log('[Paperless-ngx] Calling togglePaperlessBrowseSections (disabled)...');
- togglePaperlessBrowseSections();
- }
-}
-
-/**
- * Get selected storage option for a document type
- * @param {string} documentType - The document type (productPhoto, invoice, manual, otherDocument)
- * @param {boolean} isEdit - Whether this is for the edit modal
- * @returns {string} - 'local' or 'paperless'
- */
-function getStorageOption(documentType, isEdit = false) {
- // Only allow Paperless-ngx storage for invoices and manuals
- const paperlessAllowedTypes = ['invoice', 'manual'];
-
- if (!paperlessAllowedTypes.includes(documentType)) {
- return 'local'; // Force local storage for productPhoto and otherDocument
- }
-
- const prefix = isEdit ? 'edit' : '';
- const capitalizedType = documentType.charAt(0).toUpperCase() + documentType.slice(1);
- const name = `${prefix}${capitalizedType}Storage`;
- const radio = document.querySelector(`input[name="${name}"]:checked`);
- return radio ? radio.value : 'local';
-}
-
-/**
- * Upload file to Paperless-ngx
- * @param {File} file - The file to upload
- * @param {string} documentType - The type of document for tagging
- * @returns {Promise<Object>} - Upload result with document ID
- */
-async function uploadToPaperlessNgx(file, documentType) {
- try {
- const token = localStorage.getItem('auth_token');
- if (!token) {
- throw new Error('Authentication token not available');
- }
-
- // Show upload loading screen
- showPaperlessUploadLoading(documentType);
-
- const formData = new FormData();
- formData.append('file', file);
- formData.append('document_type', documentType);
- formData.append('title', `Warracker ${documentType} - ${file.name}`);
-
- // Add tags for organization
- const tags = ['warracker', documentType];
- formData.append('tags', tags.join(','));
-
- console.log('[Paperless-ngx] Upload FormData contents:');
- console.log(' - file:', file.name, '(' + file.size + ' bytes, ' + file.type + ')');
- console.log(' - document_type:', documentType);
- console.log(' - title:', `Warracker ${documentType} - ${file.name}`);
- console.log(' - tags:', tags.join(','));
-
- updatePaperlessUploadStatus('Uploading file to Paperless-ngx...');
-
- const response = await fetch('/api/paperless/upload', {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${token}`
- },
- body: formData
- });
-
- if (!response.ok) {
- let errorMessage = 'Failed to upload to Paperless-ngx';
- try {
- const errorData = await response.json();
- errorMessage = errorData.error || errorData.message || errorMessage;
- console.error('[Paperless-ngx] Server error details:', errorData);
- } catch (parseError) {
- console.error('[Paperless-ngx] Could not parse error response:', parseError);
- errorMessage = `HTTP ${response.status}: ${response.statusText}`;
- }
- hidePaperlessUploadLoading();
- throw new Error(errorMessage);
- }
-
- const result = await response.json();
- console.log('[Paperless-ngx] Upload successful:', result);
-
- // Update status based on result
- if (result.document_id) {
- updatePaperlessUploadStatus('Document uploaded and ready!');
- } else {
- updatePaperlessUploadStatus('Document uploaded, processing...', true);
- }
-
- return {
- success: true,
- document_id: result.document_id,
- message: result.message,
- error: result.error // Add this
- };
-
- } catch (error) {
- console.error('[Paperless-ngx] Upload error:', error);
- hidePaperlessUploadLoading();
- return {
- success: false,
- error: error.message
- };
- }
-}
-
-/**
- * Handle warranty form submission with Paperless-ngx integration
- * This extends the existing saveWarranty function
- */
-async function processPaperlessNgxUploads(formData) {
- if (!paperlessNgxEnabled) {
- return {}; // Return empty object if not enabled
- }
-
- const uploads = {};
- // Only process invoice and manual for Paperless-ngx uploads
- const documentTypes = ['invoice', 'manual'];
-
- for (const docType of documentTypes) {
- // Use storage option from formData, not DOM
- const storageKey = docType + 'Storage';
- const storageOption = formData.get(storageKey) || 'local';
- const fileInput = document.getElementById(docType);
- const file = fileInput?.files[0];
- console.log(`[DEBUG][processPaperlessNgxUploads] docType:`, docType, '| storageOption (from formData):', storageOption, '| file:', file);
- if (storageOption === 'paperless') {
- if (file) {
- console.log(`[Paperless-ngx] Uploading ${docType} to Paperless-ngx`);
- // Upload to Paperless-ngx
- const uploadResult = await uploadToPaperlessNgx(file, docType);
- console.log(`[DEBUG][processPaperlessNgxUploads] uploadResult for ${docType}:`, uploadResult);
- if (uploadResult.success || (uploadResult.error && uploadResult.error.includes("duplicate") && uploadResult.document_id)) {
- // Map frontend document types to database column names
- const fieldMapping = {
- 'productPhoto': 'paperless_photo_id',
- 'invoice': 'paperless_invoice_id',
- 'manual': 'paperless_manual_id',
- 'otherDocument': 'paperless_other_id'
- };
- const dbField = fieldMapping[docType];
- if (dbField && uploadResult.document_id) {
- uploads[dbField] = uploadResult.document_id;
- console.log(`[Paperless-ngx] ${docType} uploaded/linked successfully, ID: ${uploadResult.document_id}, stored as: ${dbField}`);
- // Hide loading screen immediately for direct uploads
- hidePaperlessUploadLoading();
- if (uploadResult.error && uploadResult.error.includes("duplicate")) {
- showToast("Duplicate document detected in Paperless-ngx. Linked to existing document.", 'info');
- }
- } else if (dbField && !uploadResult.document_id) {
- console.log(`[Paperless-ngx] ${docType} uploaded successfully but no document ID received (async processing). Not storing reference.`);
- // Don't hide loading screen yet - auto-link will handle it
- updatePaperlessUploadStatus('Document processing, searching for link...', true);
- }
- // ALWAYS remove the file from FormData since it's been uploaded to Paperless-ngx
- // This prevents the backend from also saving it locally
- if (formData.has(docType)) {
- formData.delete(docType);
- console.log(`[Paperless-ngx] Removed ${docType} from FormData to prevent local storage`);
- }
- } else {
- console.error(`[Paperless-ngx] Failed to upload ${docType} to Paperless-ngx:`, uploadResult.error);
- throw new Error(`Failed to upload ${docType} to Paperless-ngx: ${uploadResult.error}`);
- }
- } else {
- console.log(`[DEBUG][processPaperlessNgxUploads] No file found for ${docType} with paperless storage option.`);
- }
- } else {
- console.log(`[DEBUG][processPaperlessNgxUploads] Skipping ${docType}, storageOption is not paperless.`);
- }
- }
-
- return uploads;
-}
-
-/**
- * Handle warranty edit form submission with Paperless-ngx integration
- * This extends the existing edit warranty functionality
- */
-async function processEditPaperlessNgxUploads(formData) {
- if (!paperlessNgxEnabled) {
- return {}; // Return empty object if not enabled
- }
-
- const uploads = {};
- // Only process invoice and manual for Paperless-ngx uploads
- const documentTypes = ['invoice', 'manual'];
-
- for (const docType of documentTypes) {
- const storageOption = getStorageOption(docType, true); // true for edit modal
-
- if (storageOption === 'paperless') {
- const fileInput = document.getElementById(`edit${docType.charAt(0).toUpperCase() + docType.slice(1)}`);
- const file = fileInput?.files[0];
-
- if (file) {
- console.log(`[Paperless-ngx] Uploading ${docType} to Paperless-ngx (edit mode)`);
-
- // Upload to Paperless-ngx
- const uploadResult = await uploadToPaperlessNgx(file, docType);
-
- if (uploadResult.success || (uploadResult.error && uploadResult.error.includes("duplicate") && uploadResult.document_id)) {
- // Map frontend document types to database column names
- const fieldMapping = {
- 'productPhoto': 'paperless_photo_id',
- 'invoice': 'paperless_invoice_id',
- 'manual': 'paperless_manual_id',
- 'otherDocument': 'paperless_other_id'
- };
-
- const dbField = fieldMapping[docType];
- if (dbField && uploadResult.document_id) {
- uploads[dbField] = uploadResult.document_id;
- console.log(`[Paperless-ngx] ${docType} uploaded/linked successfully (edit), ID: ${uploadResult.document_id}, stored as: ${dbField}`);
- // Hide loading screen immediately for direct uploads
- hidePaperlessUploadLoading();
- if (uploadResult.error && uploadResult.error.includes("duplicate")) {
- showToast("Duplicate document detected in Paperless-ngx. Linked to existing document.", 'info');
- }
- } else if (dbField && !uploadResult.document_id) {
- console.log(`[Paperless-ngx] ${docType} uploaded successfully (edit) but no document ID received (async processing). Not storing reference.`);
- // Don't hide loading screen yet - auto-link will handle it
- updatePaperlessUploadStatus('Document processing, searching for link...', true);
- }
-
- // ALWAYS remove the file from FormData since it's been uploaded to Paperless-ngx
- // This prevents the backend from also saving it locally
- // Note: In edit mode, the form field names don't have 'edit' prefix in FormData
- if (formData.has(docType)) {
- formData.delete(docType);
- console.log(`[Paperless-ngx] Removed ${docType} from FormData to prevent local storage`);
- }
- } else {
- throw new Error(`Failed to upload ${docType} to Paperless-ngx: ${uploadResult.error}`);
- }
- }
- }
- }
-
- return uploads;
-}
-
-// Initialize Paperless-ngx integration when the page loads
-document.addEventListener('DOMContentLoaded', function() {
- // Initialize after a short delay to ensure other components are loaded
- setTimeout(() => {
- initPaperlessNgxIntegration();
- }, 1000);
-});
-
-/**
- * Debug Paperless-ngx configuration
- */
-async function debugPaperlessConfiguration() {
- try {
- const token = localStorage.getItem('auth_token');
- if (!token) {
- console.error('[Paperless Debug] No auth token found');
- return null;
- }
-
- console.log('[Paperless Debug] Checking configuration...');
-
- const response = await fetch('/api/paperless/debug', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- console.error('[Paperless Debug] Debug endpoint failed:', response.status, response.statusText);
- const errorText = await response.text();
- console.error('[Paperless Debug] Error response:', errorText);
- return null;
- }
-
- const result = await response.json();
- console.log('[Paperless Debug] Configuration:', result);
-
- return result;
- } catch (error) {
- console.error('[Paperless Debug] Error:', error);
- return null;
- }
-}
-
-/**
- * Open a Paperless-ngx document either in Warracker interface or in Paperless-ngx directly
- */
-async function openPaperlessDocument(paperlessId, warrantyContext = null) {
- console.log(`[openPaperlessDocument] Opening Paperless document: ${paperlessId}`, warrantyContext);
-
- // First, debug the Paperless configuration
- const debugInfo = await debugPaperlessConfiguration();
- if (debugInfo) {
- console.log('[openPaperlessDocument] Debug info:', debugInfo);
-
- if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {
- showToast('Paperless-ngx integration is not enabled', 'error');
- return;
- }
-
- if (!debugInfo.paperless_handler_available) {
- showToast('Paperless-ngx is not properly configured. Please check the settings.', 'error');
- console.error('[openPaperlessDocument] Paperless handler not available');
- if (debugInfo.paperless_handler_error) {
- console.error('[openPaperlessDocument] Handler error:', debugInfo.paperless_handler_error);
- }
- return;
- }
-
- if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {
- showToast(`Paperless-ngx connection failed: ${debugInfo.test_connection_result.message || debugInfo.test_connection_result.error}`, 'error');
- return;
- }
- }
-
- const token = localStorage.getItem('auth_token');
- if (!token) {
- console.error('[openPaperlessDocument] No auth token available');
- showToast('Authentication required', 'error');
- return;
- }
-
- // Check user preference for viewing documents, considering Global View context
- const viewInApp = await getUserPaperlessViewPreference(warrantyContext);
- console.log(`[openPaperlessDocument] User preference view in app: ${viewInApp}`);
-
- if (viewInApp) {
- // Open document in Warracker interface
- console.log(`[openPaperlessDocument] Opening document ${paperlessId} in Warracker interface`);
- const documentUrl = `/api/paperless-file/${paperlessId}?token=${encodeURIComponent(token)}`;
-
- const newTab = window.open(documentUrl, '_blank');
- if (!newTab) {
- showToast('Please allow popups to view documents', 'warning');
- } else {
- showToast('Opening document in Warracker...', 'info');
- }
- return;
- }
-
- // Default behavior: open in Paperless-ngx interface
- try {
- // Get the Paperless-ngx base URL
- const response = await fetch('/api/paperless/url', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- console.error('[openPaperlessDocument] URL endpoint failed:', response.status, errorText);
- throw new Error(`Failed to get Paperless-ngx URL: ${response.status}`);
- }
-
- const result = await response.json();
- if (!result.success) {
- throw new Error(result.message || 'Failed to get Paperless-ngx URL');
- }
-
- // Construct the direct link to the document in Paperless-ngx
- const paperlessUrl = result.url.replace(/\/$/, ''); // Remove trailing slash
- const documentUrl = `${paperlessUrl}/documents/${paperlessId}/details`;
-
- console.log(`[openPaperlessDocument] Opening Paperless-ngx document at: ${documentUrl}`);
-
- // Open the document directly in Paperless-ngx interface
- const newTab = window.open(documentUrl, '_blank');
- if (!newTab) {
- showToast('Please allow popups to view documents in Paperless-ngx', 'warning');
- } else {
- showToast('Opening document in Paperless-ngx...', 'info');
- }
-
- } catch (error) {
- console.error('Error opening Paperless document:', error);
- showToast(`Error opening document: ${error.message}`, 'error');
-
- // Try to determine the base URL from debug info for fallback
- if (debugInfo && debugInfo.paperless_url) {
- const fallbackUrl = `${debugInfo.paperless_url.replace(/\/$/, '')}/documents/${paperlessId}/details`;
- console.log(`[openPaperlessDocument] Trying fallback URL: ${fallbackUrl}`);
-
- const fallbackTab = window.open(fallbackUrl, '_blank');
- if (fallbackTab) {
- showToast('Opened with fallback URL - please check if Paperless-ngx is accessible', 'warning');
- }
- } else {
- // Last resort fallback
- const genericFallbackUrl = `${window.location.protocol}//${window.location.hostname}:8000/documents/${paperlessId}/details`;
- console.log(`[openPaperlessDocument] Trying generic fallback URL: ${genericFallbackUrl}`);
-
- const genericTab = window.open(genericFallbackUrl, '_blank');
- if (genericTab) {
- showToast('Opened with generic fallback URL', 'warning');
- }
- }
- }
-}
-
-/**
- * Get user preference for viewing Paperless documents in app
- */
-async function getUserPaperlessViewPreference(warrantyContext = null) {
- // Special handling for Global View: default to view in app for other users' documents
- if (warrantyContext && isGlobalView) {
- const currentUserId = (() => {
- try {
- const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
- return userInfo.id;
- } catch (e) {
- return null;
- }
- })();
-
- // If viewing another user's document in Global View, default to view in app
- if (currentUserId && warrantyContext.user_id && warrantyContext.user_id !== currentUserId) {
- console.log(`[getUserPaperlessViewPreference] Global View: Defaulting to view in app for other user's document (warranty user: ${warrantyContext.user_id}, current user: ${currentUserId})`);
- return true;
- }
- }
-
- // First check localStorage
- const prefix = getPreferenceKeyPrefix();
- const localPreference = localStorage.getItem(`${prefix}paperlessViewInApp`);
- if (localPreference !== null) {
- return localPreference === 'true';
- }
-
- // If not in localStorage, check API
- if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
- try {
- const response = await fetch('/api/auth/preferences', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
- }
- });
- if (response.ok) {
- const prefs = await response.json();
- return prefs.paperless_view_in_app || false;
- }
- } catch (e) {
- console.warn('Failed to load preferences from API:', e);
- }
- }
-
- // Default to false (open in Paperless-ngx)
- return false;
-}
-
-/**
- * Debug function to test Paperless document status
- */
-async function debugPaperlessDocument(paperlessId) {
- console.log(`[debugPaperlessDocument] Debugging Paperless document: ${paperlessId}`);
-
- const token = auth.getToken();
- if (!token) {
- console.error('[debugPaperlessDocument] No auth token available');
- return;
- }
-
- try {
- const response = await fetch(`/api/paperless/debug-document/${paperlessId}`, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- console.error(`[debugPaperlessDocument] HTTP ${response.status}: ${errorText}`);
- return;
- }
-
- const debugInfo = await response.json();
- console.log(`[debugPaperlessDocument] Debug info for document ${paperlessId}:`, debugInfo);
-
- // Show debug info in a more readable format
- let debugMessage = `Debug info for Paperless document ${paperlessId}:\n\n`;
- debugMessage += `Document exists: ${debugInfo.document_exists}\n`;
- debugMessage += `Database references: ${debugInfo.database_references?.length || 0}\n\n`;
-
- debugMessage += 'Endpoint test results:\n';
- for (const [endpoint, result] of Object.entries(debugInfo.endpoints_tested || {})) {
- debugMessage += `- ${endpoint}: ${result.success ? 'SUCCESS' : 'FAILED'} (${result.status_code || result.error})\n`;
- }
-
- if (debugInfo.recent_documents && Array.isArray(debugInfo.recent_documents)) {
- debugMessage += `\nDocument in recent list: ${debugInfo.document_in_recent}\n`;
- debugMessage += `Recent documents: ${debugInfo.recent_documents.map(d => `${d.id}: ${d.title}`).join(', ')}\n`;
- }
-
- alert(debugMessage);
-
- } catch (error) {
- console.error('Error debugging Paperless document:', error);
- alert(`Debug failed: ${error.message}`);
- }
-}
-
-/**
- * Clean up invalid Paperless-ngx document references
- */
-async function cleanupInvalidPaperlessDocuments() {
- console.log('[cleanupInvalidPaperlessDocuments] Starting cleanup...');
-
- const token = auth.getToken();
- if (!token) {
- console.error('[cleanupInvalidPaperlessDocuments] No auth token available');
- return;
- }
-
- try {
- const response = await fetch('/api/paperless/cleanup-invalid', {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- const errorText = await response.text();
- console.error(`[cleanupInvalidPaperlessDocuments] HTTP ${response.status}: ${errorText}`);
- return;
- }
-
- const result = await response.json();
- console.log('[cleanupInvalidPaperlessDocuments] Cleanup result:', result);
-
- // Show result to user
- let message = result.message || 'Cleanup completed';
- if (result.details) {
- message += `\n\nDetails:\n`;
- message += `- Documents checked: ${result.details.checked}\n`;
- message += `- Invalid documents found: ${result.details.invalid_found}\n`;
- message += `- References cleaned up: ${result.details.cleaned_up}\n`;
-
- if (result.details.errors && result.details.errors.length > 0) {
- message += `\nErrors:\n${result.details.errors.join('\n')}`;
- }
- }
-
- alert(message);
-
- // Reload warranties to reflect changes
- if (result.details && result.details.cleaned_up > 0) {
- console.log('[cleanupInvalidPaperlessDocuments] Reloading warranties after cleanup...');
- await loadWarranties(true);
- }
-
- } catch (error) {
- console.error('Error cleaning up Paperless documents:', error);
- alert(`Cleanup failed: ${error.message}`);
- }
-}
-
-/**
- * Search for and link a Paperless document by title
- * Used when documents were uploaded with async processing and we lost the document ID
- */
-async function searchAndLinkPaperlessDocument(warrantyId, documentType, searchTitle) {
- try {
- console.log(`[Paperless-ngx] Searching for document: ${searchTitle}`);
-
- const response = await fetch('/api/paperless-search-and-link', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
- },
- body: JSON.stringify({
- warranty_id: warrantyId,
- document_type: documentType,
- search_title: searchTitle
- })
- });
-
- const result = await response.json();
-
- if (result.success) {
- console.log(`[Paperless-ngx] Document linked successfully: ID ${result.document_id}`);
- showToast('Document linked successfully! Refreshing...', 'success');
-
- // Reload warranties to show the updated document links
- setTimeout(async () => {
- console.log('🔄 [Search&Link] Reloading warranties to show updated document links...');
- await loadWarranties(true); // Pass isAuthenticated parameter
-
- // Force re-render of the warranty cards
- applyFilters();
-
- // Also reload secure images to update cloud icons
- await loadSecureImages();
-
- console.log('✅ [Search&Link] Warranties reloaded and UI updated');
- }, 1000);
-
- return { success: true, document_id: result.document_id };
- } else {
- console.error(`[Paperless-ngx] Failed to link document: ${result.message}`);
- showToast(`Failed to link document: ${result.message}`, 'error');
- return { success: false, message: result.message };
- }
- } catch (error) {
- console.error(`[Paperless-ngx] Error searching for document:`, error);
- showToast('Error searching for document', 'error');
- return { success: false, message: error.message };
- }
-}
-
-/**
- * Automatically search for and link recently uploaded documents
- * This handles the case where Paperless-ngx async processing returns task_id instead of document_id
- */
-async function autoLinkRecentDocuments(warrantyId, documentTypes = ['invoice', 'manual'], maxRetries = 10, retryDelay = 10000, fileInfo = {}) {
- console.log(`[Auto-Link] Starting automatic document linking for warranty ${warrantyId}`);
-
- const token = auth.getToken();
- if (!token) {
- console.error('[Auto-Link] No auth token available');
- return;
- }
-
- let attempt = 0;
- let linkedDocuments = [];
-
- const tryLinking = async () => {
- attempt++;
- console.log(`[Auto-Link] Attempt ${attempt}/${maxRetries} for warranty ${warrantyId}`);
-
- try {
- // First check if Paperless-ngx is properly configured
- const debugInfo = await debugPaperlessConfiguration();
- if (!debugInfo) {
- console.error('[Auto-Link] Could not get Paperless debug info');
- return;
- }
-
- if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {
- console.log('[Auto-Link] Paperless-ngx integration is not enabled, skipping auto-link');
- return;
- }
-
- if (!debugInfo.paperless_handler_available) {
- console.error('[Auto-Link] Paperless handler not available:', debugInfo.paperless_handler_error || 'Unknown error');
- return;
- }
-
- if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {
- console.error('[Auto-Link] Paperless connection test failed:', debugInfo.test_connection_result.message || debugInfo.test_connection_result.error);
- return;
- }
-
- console.log(`[Auto-Link] Using intelligent filename-based search. File info:`, fileInfo);
-
- // Strategy 1: Search by exact filename (most reliable)
- let candidateDocuments = [];
-
- for (const [docType, filename] of Object.entries(fileInfo)) {
- if (!documentTypes.includes(docType)) continue;
-
- console.log(`[Auto-Link] Searching for ${docType} with filename: "${filename}"`);
-
- // Remove file extension for searching
- const baseFilename = filename.replace(/\.[^/.]+$/, '');
-
- // Try multiple search strategies
- const searchQueries = [
- filename, // Exact filename with extension
- baseFilename, // Filename without extension
- `"${filename}"`, // Quoted exact match
- `"${baseFilename}"`, // Quoted base filename
- `Warracker ${docType} - ${baseFilename}` // Warracker format
- ];
-
- for (const query of searchQueries) {
- try {
- console.log(`[Auto-Link] Trying search query: "${query}"`);
-
- const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(query)}`, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (response.ok) {
- const result = await response.json();
- const docs = result.results || [];
-
- console.log(`[Auto-Link] Query "${query}" found ${docs.length} documents`);
-
- if (docs.length > 0) {
- // Filter for recent documents (last 24 hours)
- const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
- const recentDocs = docs.filter(doc => {
- try {
- const docDate = new Date(doc.created);
- return docDate > oneDayAgo;
- } catch {
- return true; // Include if we can't parse the date
- }
- });
-
- if (recentDocs.length > 0) {
- console.log(`[Auto-Link] Found ${recentDocs.length} recent documents for ${docType}`);
- candidateDocuments.push({
- docType,
- filename,
- documents: recentDocs,
- searchQuery: query
- });
- break; // Found documents, no need to try other queries for this file
- } else if (docs.length > 0) {
- // If no recent docs but we found some documents, include them anyway
- console.log(`[Auto-Link] Found ${docs.length} older documents for ${docType}, including them anyway`);
- candidateDocuments.push({
- docType,
- filename,
- documents: docs.slice(0, 3), // Take up to 3 most recent
- searchQuery: query
- });
- break;
- }
- }
- }
- } catch (error) {
- console.error(`[Auto-Link] Error searching with query "${query}":`, error);
- }
- }
- }
-
- // Strategy 2: Fallback to Warracker tag search if filename search fails
- if (candidateDocuments.length === 0) {
- console.log('[Auto-Link] No documents found by filename, trying Warracker tag search...');
-
- const response = await fetch('/api/paperless/search?ordering=-created&created__gte=' +
- new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(), {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (response.ok) {
- const searchResult = await response.json();
- let recentDocs = searchResult.results || [];
-
- // Filter for Warracker documents
- const warrackerDocs = recentDocs.filter(doc =>
- doc.title && doc.title.includes('Warracker')
- );
-
- console.log(`[Auto-Link] Found ${warrackerDocs.length} Warracker documents from last 2 hours`);
-
- // Group by document type
- for (const docType of documentTypes) {
- const typeDocs = warrackerDocs.filter(doc =>
- doc.title && doc.title.includes(docType)
- );
-
- if (typeDocs.length > 0) {
- candidateDocuments.push({
- docType,
- filename: fileInfo[docType] || `${docType} document`,
- documents: typeDocs,
- searchQuery: `Warracker ${docType}`
- });
- }
- }
- }
- }
-
- // Debug: Show what candidate documents we found
- if (candidateDocuments.length > 0) {
- console.log('[Auto-Link] Candidate documents found:');
- candidateDocuments.forEach(candidate => {
- console.log(` ${candidate.docType}: ${candidate.documents.length} documents found with query "${candidate.searchQuery}"`);
- candidate.documents.forEach((doc, i) => {
- console.log(` ${i+1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);
- });
- });
- }
-
- // Try to link the best candidate for each document type
- for (const candidate of candidateDocuments) {
- // Use the most recent document (first in the ordered list)
- const doc = candidate.documents[0];
-
- console.log(`[Auto-Link] Attempting to link ${candidate.docType}: ${doc.title} (ID: ${doc.id})`);
-
- try {
- const linkResponse = await fetch('/api/paperless-search-and-link', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
- },
- body: JSON.stringify({
- warranty_id: warrantyId,
- document_type: candidate.docType,
- search_title: doc.title.replace('Warracker ' + candidate.docType + ' - ', '')
- })
- });
-
- const linkResult = await linkResponse.json();
-
- if (linkResult.success) {
- console.log(`[Auto-Link] Successfully linked ${candidate.docType}: ${doc.title}`);
- linkedDocuments.push({
- type: candidate.docType,
- title: doc.title,
- id: doc.id,
- filename: candidate.filename
- });
- } else {
- console.log(`[Auto-Link] Failed to link ${candidate.docType}: ${linkResult.message}`);
- }
- } catch (error) {
- console.error(`[Auto-Link] Error linking ${candidate.docType}:`, error);
- }
- }
-
- // If we found and linked documents, we're done
- if (linkedDocuments.length > 0) {
- console.log(`[Auto-Link] Successfully linked ${linkedDocuments.length} documents:`, linkedDocuments);
-
- // Update loading screen to show success
- updatePaperlessUploadStatus('Documents linked successfully!');
-
- // Show success message with filenames
- const docInfo = linkedDocuments.map(d => `${d.type} (${d.filename || d.title})`).join(', ');
- showToast(`Automatically linked ${linkedDocuments.length} document(s): ${docInfo}`, 'success');
-
- // Reload warranties to show the updated document links
- setTimeout(async () => {
- console.log('🔄 [Auto-Link] Reloading warranties to show updated document links...');
- await loadWarranties(true); // Pass isAuthenticated parameter
-
- // Force re-render of the warranty cards
- applyFilters();
-
- // Also reload secure images to update cloud icons
- await loadSecureImages();
-
- console.log('✅ [Auto-Link] Warranties reloaded and UI updated');
-
- // Hide loading screen after successful completion
- hidePaperlessUploadLoading();
- }, 1000);
-
- return true;
- }
-
- // If no documents found and we have retries left, try again
- if (attempt < maxRetries) {
- console.log(`[Auto-Link] No documents found, retrying in ${retryDelay}ms...`);
- updatePaperlessUploadStatus(`Searching for documents (attempt ${attempt + 1}/${maxRetries})...`, true);
- setTimeout(tryLinking, retryDelay);
- } else {
- console.log(`[Auto-Link] No documents found after ${maxRetries} attempts`);
- updatePaperlessUploadStatus('Document uploaded but could not auto-link');
- showToast('Document uploaded to Paperless-ngx but could not be automatically linked. You can manually link it later.', 'warning');
- // Hide loading screen after failed auto-link
- setTimeout(() => {
- hidePaperlessUploadLoading();
- }, 2000);
- }
-
- } catch (error) {
- console.error(`[Auto-Link] Error in attempt ${attempt}:`, error);
-
- if (attempt < maxRetries) {
- console.log(`[Auto-Link] Retrying in ${retryDelay}ms...`);
- updatePaperlessUploadStatus(`Error occurred, retrying (${attempt + 1}/${maxRetries})...`, true);
- setTimeout(tryLinking, retryDelay);
- } else {
- updatePaperlessUploadStatus('Upload completed with errors');
- showToast('Document uploaded but auto-linking failed due to errors. You can manually link it later.', 'warning');
- // Hide loading screen after final error
- setTimeout(() => {
- hidePaperlessUploadLoading();
- }, 2000);
- }
- }
- };
-
- // Start the linking process
- tryLinking();
-}
-
-// Make debug and cleanup functions available globally for console testing
-window.debugPaperlessDocument = debugPaperlessDocument;
-window.cleanupInvalidPaperlessDocuments = cleanupInvalidPaperlessDocuments;
-window.searchAndLinkPaperlessDocument = searchAndLinkPaperlessDocument;
-window.autoLinkRecentDocuments = autoLinkRecentDocuments;
-
-// Helper function to manually link a specific document by title
-window.manualLinkDocument = async function(warrantyId, documentType, titleSearchTerm) {
- console.log(`🔗 Manually linking document for warranty ${warrantyId}`);
- console.log(` Document type: ${documentType}`);
- console.log(` Searching for title containing: "${titleSearchTerm}"`);
-
- const token = auth.getToken();
- if (!token) {
- console.error('❌ No auth token available');
- return;
- }
-
- try {
- // Search for documents containing the search term
- const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(titleSearchTerm)}`, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- console.error(`❌ Search failed: ${response.status}`);
- return;
- }
-
- const result = await response.json();
- const docs = result.results || [];
-
- console.log(`📄 Found ${docs.length} documents matching "${titleSearchTerm}"`);
-
- if (docs.length === 0) {
- console.log('❌ No documents found. The document might still be processing in Paperless-ngx.');
- return;
- }
-
- // Show all matching documents
- docs.forEach((doc, index) => {
- console.log(` ${index + 1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);
- });
-
- // Try to link the first matching document
- const docToLink = docs[0];
- console.log(`🔗 Attempting to link document ID ${docToLink.id}: "${docToLink.title}"`);
-
- const linkResponse = await fetch('/api/paperless-search-and-link', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'Authorization': `Bearer ${token}`
- },
- body: JSON.stringify({
- warranty_id: warrantyId,
- document_type: documentType,
- search_title: docToLink.title.replace('Warracker ' + documentType + ' - ', '')
- })
- });
-
- const linkResult = await linkResponse.json();
-
- if (linkResult.success) {
- console.log(`✅ Successfully linked ${documentType}: ${docToLink.title}`);
- showToast(`Document linked successfully: ${documentType}`, 'success');
-
- // Reload warranties to show the updated document links
- setTimeout(async () => {
- console.log('🔄 Reloading warranties to show updated document links...');
- await loadWarranties(true); // Pass isAuthenticated parameter
-
- // Force re-render of the warranty cards
- applyFilters();
-
- // Also reload secure images to update cloud icons
- await loadSecureImages();
-
- console.log('✅ Warranties reloaded and UI updated');
- }, 1000);
- } else {
- console.error(`❌ Failed to link ${documentType}: ${linkResult.message}`);
- }
-
- return docToLink;
-
- } catch (error) {
- console.error('❌ Error in manual linking:', error);
- }
-};
-
-// Helper function to search for documents in Paperless-ngx (debug function)
-window.debugSearchPaperlessDocuments = async function(searchTerm = 'Warracker', limit = 10) {
- console.log(`🔍 Searching for documents containing: "${searchTerm}"`);
-
- const token = auth.getToken();
- if (!token) {
- console.error('❌ No auth token available');
- return;
- }
-
- try {
- const response = await fetch(`/api/paperless/search?ordering=-created&query=${encodeURIComponent(searchTerm)}`, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- console.error(`❌ Search failed: ${response.status}`);
- return;
- }
-
- const result = await response.json();
- const docs = result.results || [];
-
- console.log(`📄 Found ${docs.length} documents:`);
- docs.slice(0, limit).forEach((doc, index) => {
- console.log(` ${index + 1}. ID: ${doc.id}, Title: "${doc.title}", Created: ${doc.created}`);
- });
-
- if (docs.length > limit) {
- console.log(` ... and ${docs.length - limit} more documents`);
- }
-
- return docs;
- } catch (error) {
- console.error('❌ Error searching documents:', error);
- }
-};
-
-// Helper function for users to debug Paperless-ngx configuration
-window.debugPaperlessSetup = async function() {
- console.log('🔍 Debugging Paperless-ngx setup...');
-
- const debugInfo = await debugPaperlessConfiguration();
- if (!debugInfo) {
- console.error('❌ Could not get debug information');
- return;
- }
-
- console.log('📋 Paperless-ngx Configuration:');
- console.log(` Enabled: ${debugInfo.paperless_enabled}`);
- console.log(` URL: ${debugInfo.paperless_url || 'Not set'}`);
- console.log(` API Token Set: ${debugInfo.paperless_api_token_set}`);
- console.log(` Handler Available: ${debugInfo.paperless_handler_available}`);
-
- if (debugInfo.paperless_handler_error) {
- console.error(` Handler Error: ${debugInfo.paperless_handler_error}`);
- }
-
- if (debugInfo.test_connection_result) {
- console.log(` Connection Test: ${debugInfo.test_connection_result.success ? '✅ Success' : '❌ Failed'}`);
- console.log(` Message: ${debugInfo.test_connection_result.message || debugInfo.test_connection_result.error}`);
- }
-
- // Provide recommendations
- console.log('\n💡 Recommendations:');
-
- if (!debugInfo.paperless_enabled || debugInfo.paperless_enabled === 'false') {
- console.log(' - Enable Paperless-ngx integration in Settings');
- }
-
- if (!debugInfo.paperless_url) {
- console.log(' - Set Paperless-ngx URL in Settings (e.g., http://paperless:8000)');
- }
-
- if (!debugInfo.paperless_api_token_set) {
- console.log(' - Set API token in Settings (generate from Paperless-ngx → Settings → API Tokens)');
- }
-
- if (debugInfo.test_connection_result && !debugInfo.test_connection_result.success) {
- console.log(' - Check if Paperless-ngx is running and accessible');
- console.log(' - Verify URL and API token are correct');
- console.log(' - Check network connectivity between Warracker and Paperless-ngx');
- }
-
- return debugInfo;
-};
-
-// ===== PAPERLESS DOCUMENT BROWSER FUNCTIONALITY =====
-
-// Global variables for paperless browser
-let currentPaperlessDocuments = [];
-let selectedPaperlessDocument = null;
-let currentPaperlessPage = 1;
-let totalPaperlessPages = 1;
-let currentDocumentType = '';
-let paperlessSearchQuery = '';
-
-/**
- * Open the Paperless document browser modal
- * @param {string} documentType - Type of document being selected (invoice, manual, product_photo, other_document)
- */
-function openPaperlessBrowser(documentType) {
- currentDocumentType = documentType;
- selectedPaperlessDocument = null;
-
- // Reset pagination state
- currentPaperlessPage = 1;
- totalPaperlessPages = 1;
- paperlessSearchQuery = '';
-
- // Show the modal
- const modal = document.getElementById('paperlessBrowserModal');
- modal.classList.add('active');
-
- // Reset search and filters
- document.getElementById('paperlessSearchInput').value = '';
- document.getElementById('paperlessTypeFilter').value = '';
- document.getElementById('paperlessTagFilter').value = '';
-
- // Load documents
- loadAllPaperlessDocuments();
-
- // Load tags for filter
- loadPaperlessTags();
-
- // Hide select button initially
- const selectBtn = document.getElementById('selectPaperlessDocBtn');
- if (selectBtn) {
- selectBtn.style.display = 'none';
- }
-}
-
-/**
- * Load all Paperless documents
- */
-async function loadAllPaperlessDocuments() {
- try {
- showPaperlessLoading();
-
- const params = new URLSearchParams();
- const offset = (currentPaperlessPage - 1) * 25;
- params.append('limit', '25');
- params.append('offset', offset.toString());
-
- const response = await fetch(`/api/paperless/search?${params.toString()}`, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
-
- const data = await response.json();
- currentPaperlessDocuments = data.results || [];
- totalPaperlessPages = Math.ceil(data.count / 25) || 1;
-
- renderPaperlessDocuments();
- updatePaperlessPagination();
-
- } catch (error) {
- console.error('Error loading Paperless documents:', error);
- showPaperlessError('Failed to load documents from Paperless-ngx');
- }
-}
-
-/**
- * Search Paperless documents
- */
-async function searchPaperlessDocuments() {
- const searchInput = document.getElementById('paperlessSearchInput');
- const typeFilter = document.getElementById('paperlessTypeFilter');
- const tagFilter = document.getElementById('paperlessTagFilter');
-
- paperlessSearchQuery = searchInput.value.trim();
-
- try {
- showPaperlessLoading();
-
- const params = new URLSearchParams();
- if (paperlessSearchQuery) {
- params.append('query', paperlessSearchQuery);
- }
- if (typeFilter.value) {
- params.append('document_type', typeFilter.value);
- }
- if (tagFilter.value) {
- params.append('tags__id__in', tagFilter.value);
- }
-
- // Add pagination
- const offset = (currentPaperlessPage - 1) * 25;
- params.append('limit', '25');
- params.append('offset', offset.toString());
-
- const response = await fetch(`/api/paperless/search?${params.toString()}`, {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- throw new Error(`HTTP error! status: ${response.status}`);
- }
-
- const data = await response.json();
- currentPaperlessDocuments = data.results || [];
- totalPaperlessPages = Math.ceil(data.count / 25) || 1;
-
- renderPaperlessDocuments();
- updatePaperlessPagination();
-
- } catch (error) {
- console.error('Error searching Paperless documents:', error);
- showPaperlessError('Failed to search documents');
- }
-}
-
-/**
- * Load Paperless tags for filter dropdown
- */
-async function loadPaperlessTags() {
- try {
- const response = await fetch('/api/paperless/tags', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${localStorage.getItem('auth_token')}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (response.ok) {
- const data = await response.json();
- const tagFilter = document.getElementById('paperlessTagFilter');
-
- // Clear existing options except the first one
- tagFilter.innerHTML = '<option value="">All Tags</option>';
-
- // Add tag options
- if (data.results) {
- data.results.forEach(tag => {
- const option = document.createElement('option');
- option.value = tag.id;
- option.textContent = tag.name;
- tagFilter.appendChild(option);
- });
- }
- }
- } catch (error) {
- console.error('Error loading Paperless tags:', error);
- }
-}
-
-/**
- * Render the list of Paperless documents
- */
-function renderPaperlessDocuments() {
- const container = document.getElementById('paperlessDocumentsList');
-
- if (window.components && window.components.paperless && window.components.paperless.renderDocumentsList) {
- window.components.paperless.renderDocumentsList(container, currentPaperlessDocuments);
- return;
- }
- // Fallback to existing HTML assembly
- if (currentPaperlessDocuments.length === 0) {
- container.innerHTML = `
- <div class="no-documents-message">
- <i class="fas fa-file-alt"></i>
- <h4>No documents found</h4>
- <p>Try adjusting your search terms or filters.</p>
- </div>
- `;
- return;
- }
- const documentsHtml = currentPaperlessDocuments.map(doc => {
- const createdDate = new Date(doc.created).toLocaleDateString();
- const fileType = doc.mime_type || 'Unknown';
- const tags = doc.tags || [];
- return `
- <div class="paperless-document-item" data-id="${doc.id}" onclick="selectPaperlessDocument(${doc.id})">
- <div class="document-title">${escapeHtml(doc.title)}</div>
- <div class="document-meta">
- <span><i class="fas fa-calendar"></i> ${createdDate}</span>
- <span><i class="fas fa-file"></i> ${fileType}</span>
- ${doc.correspondent ? `<span><i class=\"fas fa-user\"></i> ${escapeHtml(doc.correspondent)}</span>` : ''}
- </div>
- ${tags.length > 0 ? `
- <div class="document-tags">
- ${tags.map(tag => `<span class=\"document-tag\">${escapeHtml(tag)}</span>`).join('')}
- </div>
- ` : ''}
- </div>
- `;
- }).join('');
- container.innerHTML = documentsHtml;
-}
-
-/**
- * Select a Paperless document
- * @param {number} documentId - ID of the document to select
- */
-function selectPaperlessDocument(documentId) {
- // Remove previous selection
- document.querySelectorAll('.paperless-document-item').forEach(item => {
- item.classList.remove('selected');
- });
-
- // Add selection to clicked item
- const selectedItem = document.querySelector(`[data-id="${documentId}"]`);
- if (selectedItem) {
- selectedItem.classList.add('selected');
- selectedPaperlessDocument = currentPaperlessDocuments.find(doc => doc.id === documentId);
-
- // Show select button
- const selectBtn = document.getElementById('selectPaperlessDocBtn');
- selectBtn.style.display = 'inline-block';
- selectBtn.onclick = () => confirmPaperlessSelection();
- }
-}
-
-/**
- * Confirm the selection of a Paperless document
- */
-function confirmPaperlessSelection() {
- if (!selectedPaperlessDocument) return;
-
- // Update the UI to show the selected document
- updatePaperlessSelectionUI();
-
- // Close the modal
- closePaperlessBrowser();
-}
-
-/**
- * Update the UI to show the selected Paperless document
- */
-function updatePaperlessSelectionUI() {
- if (!selectedPaperlessDocument || !currentDocumentType) return;
-
- const docName = selectedPaperlessDocument.title;
- const docId = selectedPaperlessDocument.id;
-
- // Map document types to their UI elements (only for invoice and manual)
- const typeMapping = {
- 'invoice': {
- selectedDiv: 'selectedInvoiceFromPaperless',
- hiddenInput: 'selectedPaperlessInvoice'
- },
- 'manual': {
- selectedDiv: 'selectedManualFromPaperless',
- hiddenInput: 'selectedPaperlessManual'
- },
- // Edit modal versions
- 'edit_invoice': {
- selectedDiv: 'selectedEditInvoiceFromPaperless',
- hiddenInput: 'selectedEditPaperlessInvoice'
- },
- 'edit_manual': {
- selectedDiv: 'selectedEditManualFromPaperless',
- hiddenInput: 'selectedEditPaperlessManual'
- }
- };
-
- const mapping = typeMapping[currentDocumentType];
- if (!mapping) return;
-
- // Show the selected document
- const selectedDiv = document.getElementById(mapping.selectedDiv);
- if (selectedDiv) {
- selectedDiv.style.display = 'flex';
- selectedDiv.querySelector('.selected-doc-name').textContent = docName;
- }
-
- // Create or update hidden input to store the document ID
- let hiddenInput = document.getElementById(mapping.hiddenInput);
- if (!hiddenInput) {
- hiddenInput = document.createElement('input');
- hiddenInput.type = 'hidden';
- hiddenInput.id = mapping.hiddenInput;
- hiddenInput.name = mapping.hiddenInput;
- document.body.appendChild(hiddenInput);
- }
- hiddenInput.value = docId;
-}
-
-/**
- * Clear the Paperless document selection
- * @param {string} documentType - Type of document to clear
- */
-function clearPaperlessSelection(documentType) {
- const typeMapping = {
- 'invoice': {
- selectedDiv: 'selectedInvoiceFromPaperless',
- hiddenInput: 'selectedPaperlessInvoice'
- },
- 'manual': {
- selectedDiv: 'selectedManualFromPaperless',
- hiddenInput: 'selectedPaperlessManual'
- },
- // Edit modal versions
- 'edit_invoice': {
- selectedDiv: 'selectedEditInvoiceFromPaperless',
- hiddenInput: 'selectedEditPaperlessInvoice'
- },
- 'edit_manual': {
- selectedDiv: 'selectedEditManualFromPaperless',
- hiddenInput: 'selectedEditPaperlessManual'
- }
- };
-
- const mapping = typeMapping[documentType];
- if (!mapping) return;
-
- // Hide the selected document display
- const selectedDiv = document.getElementById(mapping.selectedDiv);
- if (selectedDiv) {
- selectedDiv.style.display = 'none';
- }
-
- // Clear the hidden input
- const hiddenInput = document.getElementById(mapping.hiddenInput);
- if (hiddenInput) {
- hiddenInput.value = '';
- }
-}
-
-/**
- * Close the Paperless browser modal
- */
-function closePaperlessBrowser() {
- const modal = document.getElementById('paperlessBrowserModal');
- modal.classList.remove('active');
-
- // Reset state
- selectedPaperlessDocument = null;
- currentDocumentType = '';
-
- // Hide select button
- const selectBtn = document.getElementById('selectPaperlessDocBtn');
- selectBtn.style.display = 'none';
-}
-
-/**
- * Change page in Paperless document browser
- * @param {number} direction - Direction to change page (-1 for previous, 1 for next)
- */
-function changePage(direction) {
- const newPage = currentPaperlessPage + direction;
- if (newPage < 1 || newPage > totalPaperlessPages) return;
-
- currentPaperlessPage = newPage;
-
- // Check if we have any active filters
- const searchInput = document.getElementById('paperlessSearchInput');
- const typeFilter = document.getElementById('paperlessTypeFilter');
- const tagFilter = document.getElementById('paperlessTagFilter');
-
- const hasFilters = (searchInput && searchInput.value.trim()) ||
- (typeFilter && typeFilter.value) ||
- (tagFilter && tagFilter.value);
-
- if (hasFilters) {
- searchPaperlessDocuments();
- } else {
- loadAllPaperlessDocuments();
- }
-}
-
-/**
- * Update pagination controls
- */
-function updatePaperlessPagination() {
- const paginationDiv = document.getElementById('paperlessPagination');
- const prevBtn = document.getElementById('prevPageBtn');
- const nextBtn = document.getElementById('nextPageBtn');
- const pageInfo = document.getElementById('pageInfo');
-
- if (totalPaperlessPages <= 1) {
- paginationDiv.style.display = 'none';
- return;
- }
-
- paginationDiv.style.display = 'flex';
- prevBtn.disabled = currentPaperlessPage <= 1;
- nextBtn.disabled = currentPaperlessPage >= totalPaperlessPages;
- pageInfo.textContent = `Page ${currentPaperlessPage} of ${totalPaperlessPages}`;
-}
-
-/**
- * Show loading state in Paperless browser
- */
-function showPaperlessLoading() {
- const container = document.getElementById('paperlessDocumentsList');
- if (window.components && window.components.paperless && window.components.paperless.renderLoading) {
- window.components.paperless.renderLoading(container);
- return;
- }
- container.innerHTML = `
- <div class="loading-message" style="text-align: center; padding: 40px;">
- <i class="fas fa-spinner fa-spin"></i> Loading documents...
- </div>
- `;
-}
-
-/**
- * Show error message in Paperless browser
- * @param {string} message - Error message to display
- */
-function showPaperlessError(message) {
- const container = document.getElementById('paperlessDocumentsList');
- if (window.components && window.components.paperless && window.components.paperless.renderError) {
- window.components.paperless.renderError(container, message);
- return;
- }
- container.innerHTML = `
- <div class="no-documents-message">
- <i class="fas fa-exclamation-triangle"></i>
- <h4>Error</h4>
- <p>${escapeHtml(message)}</p>
- </div>
- `;
-}
-
-/**
- * Show/hide Paperless browse sections based on Paperless-ngx availability
- */
-function togglePaperlessBrowseSections() {
- const paperlessEnabled = window.paperlessNgxEnabled || false;
- console.log('[togglePaperlessBrowseSections] Paperless enabled:', paperlessEnabled);
-
- // List of paperless browse section IDs (only for invoice and manual)
- const browseSectionIds = [
- 'invoicePaperlessBrowse',
- 'manualPaperlessBrowse',
- 'editInvoicePaperlessBrowse',
- 'editManualPaperlessBrowse'
- ];
-
- let foundSections = 0;
- browseSectionIds.forEach(id => {
- const section = document.getElementById(id);
- if (section) {
- foundSections++;
- section.style.display = paperlessEnabled ? 'block' : 'none';
- console.log(`[togglePaperlessBrowseSections] ${id}: ${paperlessEnabled ? 'shown' : 'hidden'}`);
- } else {
- console.warn(`[togglePaperlessBrowseSections] Section not found: ${id}`);
- }
- });
-
- console.log(`[togglePaperlessBrowseSections] Found ${foundSections} of ${browseSectionIds.length} sections`);
-}
-
-// Initialize Paperless browser functionality when DOM is loaded
-document.addEventListener('DOMContentLoaded', function() {
- // Add event listeners for modal close buttons
- const paperlessModal = document.getElementById('paperlessBrowserModal');
- if (paperlessModal) {
- // Close on backdrop click
- paperlessModal.addEventListener('click', function(e) {
- if (e.target === paperlessModal) {
- closePaperlessBrowser();
- }
- });
-
- // Close on close button click
- const closeBtn = paperlessModal.querySelector('.close-btn');
- if (closeBtn) {
- closeBtn.addEventListener('click', closePaperlessBrowser);
- }
-
- // Close on cancel button click - but only the Cancel button, not all secondary buttons
- const cancelBtn = paperlessModal.querySelector('.modal-footer .btn-secondary');
- if (cancelBtn) {
- cancelBtn.addEventListener('click', closePaperlessBrowser);
- }
- }
-
- // Add event listeners for search and filters
- const searchInput = document.getElementById('paperlessSearchInput');
- if (searchInput) {
- // Search on Enter key
- searchInput.addEventListener('keypress', function(e) {
- if (e.key === 'Enter') {
- currentPaperlessPage = 1; // Reset to first page
- searchPaperlessDocuments();
- }
- });
-
- // Search on input change (with debounce)
- let searchTimeout;
- searchInput.addEventListener('input', function() {
- clearTimeout(searchTimeout);
- searchTimeout = setTimeout(() => {
- currentPaperlessPage = 1; // Reset to first page
- searchPaperlessDocuments();
- }, 500);
- });
- }
-
- // Add event listeners for filter dropdowns
- const typeFilter = document.getElementById('paperlessTypeFilter');
- if (typeFilter) {
- typeFilter.addEventListener('change', function() {
- currentPaperlessPage = 1; // Reset to first page
- searchPaperlessDocuments();
- });
- }
-
- const tagFilter = document.getElementById('paperlessTagFilter');
- if (tagFilter) {
- tagFilter.addEventListener('change', function() {
- currentPaperlessPage = 1; // Reset to first page
- searchPaperlessDocuments();
- });
- }
-
- // Add event listener for search button
- const searchBtn = document.getElementById('paperlessSearchBtn');
- if (searchBtn) {
- searchBtn.addEventListener('click', function(e) {
- e.preventDefault();
- e.stopPropagation();
- currentPaperlessPage = 1; // Reset to first page
- searchPaperlessDocuments();
- });
- }
-
- // Add event listener for "Show All" button
- const showAllBtn = document.getElementById('paperlessShowAllBtn');
- if (showAllBtn) {
- showAllBtn.addEventListener('click', function(e) {
- e.preventDefault();
- e.stopPropagation();
-
- // Clear all filters
- if (searchInput) searchInput.value = '';
- if (typeFilter) typeFilter.value = '';
- if (tagFilter) tagFilter.value = '';
-
- // Reset page and load all documents
- currentPaperlessPage = 1;
- paperlessSearchQuery = '';
- loadAllPaperlessDocuments();
- });
- }
-
- // Toggle browse sections will be handled by initPaperlessNgxIntegration()
- // togglePaperlessBrowseSections();
-});
-
-// Make functions available globally
-window.openPaperlessBrowser = openPaperlessBrowser;
-window.loadAllPaperlessDocuments = loadAllPaperlessDocuments;
-window.selectPaperlessDocument = selectPaperlessDocument;
-window.clearPaperlessSelection = clearPaperlessSelection;
-window.changePage = changePage;
-window.openPaperlessDocument = openPaperlessDocument;
-window.openSecureFile = openSecureFile;
-
-// ===== END PAPERLESS BROWSER FUNCTIONALITY =====
diff --git a/frontend/src/settings-new.js b/frontend/src/settings-new.js
deleted file mode 100644
index f9feb43..0000000
--- a/frontend/src/settings-new.js
+++ /dev/null
@@ -1,5202 +0,0 @@
-// DOM Elements
-const darkModeToggle = document.getElementById('darkModeToggle');
-const darkModeToggleSetting = document.getElementById('darkModeToggleSetting');
-const languageSelect = document.getElementById('languageSelect');
-const defaultViewSelect = document.getElementById('defaultView');
-const expiringSoonDaysInput = document.getElementById('expiringSoonDays');
-const notificationChannel = document.getElementById('notificationChannel');
-const notificationFrequencySelect = document.getElementById('notificationFrequency');
-const notificationTimeInput = document.getElementById('notificationTime');
-const timezoneSelect = document.getElementById('timezone');
-const saveProfileBtn = document.getElementById('saveProfileBtn');
-const savePreferencesBtn = document.getElementById('savePreferencesBtn');
-const saveNotificationSettingsBtn = document.getElementById('saveNotificationSettingsBtn');
-const changePasswordBtn = document.getElementById('changePasswordBtn');
-const emailSettingsContainer = document.getElementById('emailSettingsContainer');
-const appriseSettingsContainer = document.getElementById('appriseSettingsContainer');
-const userAppriseSettingsContainer = document.getElementById('userAppriseSettingsContainer');
-const passwordChangeForm = document.getElementById('passwordChangeForm');
-const savePasswordBtn = document.getElementById('savePasswordBtn');
-const cancelPasswordBtn = document.getElementById('cancelPasswordBtn');
-const deleteAccountBtn = document.getElementById('deleteAccountBtn');
-const deleteAccountModal = document.getElementById('deleteAccountModal');
-const deleteConfirmInput = document.getElementById('deleteConfirmInput');
-const confirmDeleteAccountBtn = document.getElementById('confirmDeleteAccountBtn');
-const passwordSuccessModal = document.getElementById('passwordSuccessModal');
-const loadingContainer = document.getElementById('loadingContainer');
-const toastContainer = document.getElementById('toastContainer');
-const settingsBtn = document.getElementById('settingsBtn');
-const settingsMenu = document.getElementById('settingsMenu');
-const usersTableBody = document.getElementById('usersTableBody');
-
-// Edit User Modal Elements
-const editUserModal = document.getElementById('editUserModal');
-const editUserId = document.getElementById('editUserId');
-const editUsername = document.getElementById('editUsername');
-const editEmail = document.getElementById('editEmail');
-const editUserActive = document.getElementById('editUserActive');
-const editUserAdmin = document.getElementById('editUserAdmin');
-
-// Form fields
-const firstNameInput = document.getElementById('firstName');
-const lastNameInput = document.getElementById('lastName');
-const emailInput = document.getElementById('email');
-const currentPasswordInput = document.getElementById('currentPassword');
-const newPasswordInput = document.getElementById('newPassword');
-const confirmPasswordInput = document.getElementById('confirmPassword');
-
-// DOM Elements for admin section
-const adminSection = document.getElementById('adminSection');
-const refreshUsersBtn = document.getElementById('refreshUsersBtn');
-const checkAdminBtn = document.getElementById('checkAdminBtn');
-const showUsersBtn = document.getElementById('showUsersBtn');
-const testApiBtn = document.getElementById('testApiBtn');
-const triggerNotificationsBtn = document.getElementById('triggerNotificationsBtn');
-const schedulerStatusBtn = document.getElementById('schedulerStatusBtn');
-const registrationEnabled = document.getElementById('registrationEnabled');
-const saveSiteSettingsBtn = document.getElementById('saveSiteSettingsBtn');
-const emailBaseUrlInput = document.getElementById('emailBaseUrl'); // Added for email base URL
-
-// OIDC Settings DOM Elements
-const oidcEnabledToggle = document.getElementById('oidcEnabled');
-const oidcOnlyModeToggle = document.getElementById('oidcOnlyMode');
-const oidcProviderNameInput = document.getElementById('oidcProviderName');
-const oidcClientIdInput = document.getElementById('oidcClientId');
-const oidcClientSecretInput = document.getElementById('oidcClientSecret');
-const oidcIssuerUrlInput = document.getElementById('oidcIssuerUrl');
-const oidcScopeInput = document.getElementById('oidcScope');
-const oidcAdminGroupInput = document.getElementById('oidcAdminGroup');
-const saveOidcSettingsBtn = document.getElementById('saveOidcSettingsBtn');
-const oidcRestartMessage = document.getElementById('oidcRestartMessage');
-
-// Apprise Settings DOM Elements
-const appriseEnabledToggle = document.getElementById('appriseEnabled');
-const appriseNotificationModeSelect = document.getElementById('appriseNotificationMode');
-const appriseModeDescription = document.getElementById('appriseModeDescription');
-const appriseWarrantyScopeSelect = document.getElementById('appriseWarrantyScope');
-const appriseScopeDescription = document.getElementById('appriseScopeDescription');
-const appriseUrlsTextarea = document.getElementById('appriseUrls');
-const appriseExpirationDaysInput = document.getElementById('appriseExpirationDays');
-const appriseNotificationFrequency = document.getElementById('appriseNotificationFrequency');
-
-// User-specific Apprise settings (in notification settings section)
-const userAppriseNotificationTimeInput = document.getElementById('userAppriseNotificationTime');
-const userAppriseTimezoneSelect = document.getElementById('userAppriseTimezone');
-const userAppriseNotificationFrequency = document.getElementById('userAppriseNotificationFrequency');
-const appriseTitlePrefixInput = document.getElementById('appriseTitlePrefix');
-const appriseTestUrlInput = document.getElementById('appriseTestUrl');
-const saveAppriseSettingsBtn = document.getElementById('saveAppriseSettingsBtn');
-const testAppriseBtn = document.getElementById('testAppriseBtn');
-const validateAppriseUrlBtn = document.getElementById('validateAppriseUrlBtn');
-const triggerAppriseNotificationsBtn = document.getElementById('triggerAppriseNotificationsBtn');
-const appriseStatusBadge = document.getElementById('appriseStatusBadge');
-const appriseUrlsCount = document.getElementById('appriseUrlsCount');
-const currentAppriseExpirationDays = document.getElementById('currentAppriseExpirationDays');
-
-const viewSupportedServicesBtn = document.getElementById('viewSupportedServicesBtn');
-const appriseNotAvailable = document.getElementById('appriseNotAvailable');
-
-const currencySymbolInput = document.getElementById('currencySymbol');
-const currencySymbolSelect = document.getElementById('currencySymbolSelect');
-const currencySymbolCustom = document.getElementById('currencySymbolCustom');
-const currencyPositionSelect = document.getElementById('currencyPositionSelect');
-
-// Add dateFormatSelect near other DOM element declarations if not already there
-const dateFormatSelect = document.getElementById('dateFormat');
-
-// Paperless-ngx Settings DOM Elements
-const paperlessEnabledToggle = document.getElementById('paperlessEnabled');
-const paperlessUrlInput = document.getElementById('paperlessUrl');
-const paperlessApiTokenInput = document.getElementById('paperlessApiToken');
-const paperlessViewInAppToggle = document.getElementById('paperlessViewInApp');
-const paperlessSettingsContainer = document.getElementById('paperlessSettingsContainer');
-const testPaperlessConnectionBtn = document.getElementById('testPaperlessConnectionBtn');
-const savePaperlessSettingsBtn = document.getElementById('savePaperlessSettingsBtn');
-const paperlessConnectionStatus = document.getElementById('paperlessConnectionStatus');
-
-// Global variable to store currencies data for currency code lookup
-let globalCurrenciesData = [];
-
-/**
- * Load currencies from the API and populate the currency dropdown
- */
-async function loadCurrenciesForSettings() {
- try {
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
- const response = await fetch('/api/currencies', {
- headers: {
- 'Authorization': `Bearer ${token}`
- }
- });
- if (!response.ok) {
- throw new Error('Failed to fetch currencies');
- }
-
- const currencies = await response.json();
-
- // Store currencies data globally for currency code lookup
- globalCurrenciesData = currencies;
-
- // Populate currency symbol dropdown
- if (currencySymbolSelect) {
- // Clear existing options
- currencySymbolSelect.innerHTML = '';
-
- // Add currencies from API
- currencies.forEach(currency => {
- const option = document.createElement('option');
- option.value = currency.symbol;
- option.textContent = `${currency.symbol} (${currency.code} - ${currency.name})`;
- currencySymbolSelect.appendChild(option);
- });
-
- // Add "Other..." option at the end
- const otherOption = document.createElement('option');
- otherOption.value = 'other';
- otherOption.textContent = 'Other...';
- currencySymbolSelect.appendChild(otherOption);
- }
-
- console.log('Currencies loaded successfully for settings page');
- } catch (error) {
- console.error('Error loading currencies for settings:', error);
- // Fallback to default currencies if loading fails
- if (currencySymbolSelect) {
- currencySymbolSelect.innerHTML = `
- <option value="$">$ (USD - US Dollar)</option>
- <option value="€">€ (EUR - Euro)</option>
- <option value="£">£ (GBP - British Pound)</option>
- <option value="¥">¥ (JPY - Japanese Yen)</option>
- <option value="other">Other...</option>
- `;
- }
- }
-}
-
-/**
- * Initialize language selector
- */
-function initLanguageSelector() {
- console.log('initLanguageSelector called');
- console.log('languageSelect element exists:', !!languageSelect);
-
- if (!languageSelect) {
- console.error('Language select element not found!');
- return;
- }
-
- // Check if already initialized
- if (languageSelect.hasAttribute('data-initialized')) {
- console.log('Language selector already initialized, skipping');
- return;
- }
-
- // Get current language
- const currentLang = window.i18n?.getCurrentLanguage() || 'en';
- console.log('Setting language selector to current language:', currentLang);
- languageSelect.value = currentLang;
-
- // Mark as initialized
- languageSelect.setAttribute('data-initialized', 'true');
-
- // Add event listener for language changes
- languageSelect.addEventListener('change', async function() {
- const selectedLanguage = this.value;
- console.log('Language changed to:', selectedLanguage);
-
- if (window.i18n?.changeLanguage) {
- try {
- showToast('Changing language...', 'info');
- await window.i18n.changeLanguage(selectedLanguage);
- showToast(window.t('messages.saved') || 'Language changed successfully', 'success');
-
- // Reload page after a short delay to apply all translations
- setTimeout(() => {
- window.location.reload();
- }, 1000);
- } catch (error) {
- console.error('Failed to change language:', error);
- showToast(window.t('messages.error') || 'Failed to change language', 'error');
- }
- } else {
- console.warn('i18n changeLanguage function not available');
- showToast('Language system not ready. Please try again.', 'error');
- }
- });
-
- console.log('Language selector initialized successfully with current language:', currentLang);
-}
-
-/**
- * Initialize language selector after i18n is ready
- */
-function initLanguageSelectorWhenReady() {
- console.log('initLanguageSelectorWhenReady called');
- console.log('window.i18n available:', !!window.i18n);
- console.log('window.i18n.getCurrentLanguage available:', !!(window.i18n && window.i18n.getCurrentLanguage));
-
- if (window.i18n && window.i18n.getCurrentLanguage) {
- // i18n is already ready
- console.log('i18n already ready, initializing language selector');
- initLanguageSelector();
- } else {
- // Wait for i18n to be ready
- console.log('Waiting for i18n to be ready...');
- window.addEventListener('i18nReady', function(event) {
- console.log('i18n is now ready, initializing language selector');
- initLanguageSelector();
- }, { once: true }); // Use once: true to ensure this only runs once
-
- // Also try again after a short delay as backup
- setTimeout(() => {
- if (window.i18n && window.i18n.getCurrentLanguage && !languageSelect.hasAttribute('data-initialized')) {
- console.log('Backup initialization: i18n ready, initializing language selector');
- initLanguageSelector();
- }
- }, 2000);
- }
-}
-
-/**
- * Set theme (dark/light) - Unified and persistent
- * @param {boolean} isDark - Whether to use dark mode
- */
-function setTheme(isDark) {
- const theme = isDark ? 'dark' : 'light';
- // Apply theme to document
- document.documentElement.setAttribute('data-theme', theme);
- if (isDark) {
- document.body.classList.add('dark-mode');
- } else {
- document.body.classList.remove('dark-mode');
- }
- // Save to localStorage (single source of truth)
- localStorage.setItem('darkMode', isDark);
- // Sync both toggles if present
- if (typeof darkModeToggle !== 'undefined' && darkModeToggle) {
- darkModeToggle.checked = isDark;
- }
- if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) {
- darkModeToggleSetting.checked = isDark;
- }
- // Also update user_preferences.theme for backward compatibility
- try {
- let userPrefs = {};
- const storedPrefs = localStorage.getItem('user_preferences');
- if (storedPrefs) {
- userPrefs = JSON.parse(storedPrefs);
- }
- userPrefs.theme = theme;
- localStorage.setItem('user_preferences', JSON.stringify(userPrefs));
- } catch (e) {
- console.error('Error updating theme in user_preferences:', e);
- }
-}
-
-/**
- * Initialize dark mode toggle and synchronize state
- */
-function initDarkModeToggle() {
- // Always check the single source of truth in localStorage (fallback)
- const isDarkMode = localStorage.getItem('darkMode') === 'true';
- // Apply theme to DOM if not already set
- document.documentElement.setAttribute('data-theme', isDarkMode ? 'dark' : 'light');
- document.body.classList.toggle('dark-mode', isDarkMode);
- // Sync both toggles and add unified handler
- const syncToggles = (val) => {
- if (typeof darkModeToggle !== 'undefined' && darkModeToggle) darkModeToggle.checked = val;
- if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) darkModeToggleSetting.checked = val;
- };
- syncToggles(isDarkMode);
- // Handler to update theme, localStorage, backend
- const handleToggle = async function(checked) {
- setTheme(checked);
- syncToggles(checked);
- // Save to backend if authenticated
- if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
- try {
- let prefs = {};
- const storedPrefs = localStorage.getItem('user_preferences');
- if (storedPrefs) prefs = JSON.parse(storedPrefs);
- prefs.theme = checked ? 'dark' : 'light';
- await fetch('/api/auth/preferences', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(prefs)
- });
- } catch (e) {
- console.warn('Failed to save dark mode to backend:', e);
- }
- }
- };
- if (typeof darkModeToggle !== 'undefined' && darkModeToggle) {
- darkModeToggle.onchange = function() { handleToggle(this.checked); };
- }
- if (typeof darkModeToggleSetting !== 'undefined' && darkModeToggleSetting) {
- darkModeToggleSetting.onchange = function() { handleToggle(this.checked); };
- }
-}
-
-// Initialize settings page
-document.addEventListener('DOMContentLoaded', function() {
- console.log('DOM fully loaded, initializing settings page');
-
- // DEBUG: Check current user data
- const debugCurrentUser = window.auth && window.auth.getCurrentUser ? window.auth.getCurrentUser() : null;
- console.log('DEBUG: Current user data:', debugCurrentUser);
-
- // Also listen for i18nReady event to ensure language selector gets initialized
- console.log('Setting up i18nReady event listener from DOMContentLoaded');
- window.addEventListener('i18nReady', function(event) {
- console.log('i18nReady event received in DOMContentLoaded listener, initializing language selector');
- // Small delay to ensure all DOM elements are ready
- setTimeout(() => {
- if (!document.getElementById('languageSelect').hasAttribute('data-initialized')) {
- console.log('Language selector not yet initialized, doing it now');
- initLanguageSelector();
- } else {
- console.log('Language selector already initialized');
- }
- }, 100);
- }, { once: true });
- if (debugCurrentUser) {
- console.log('DEBUG: User has is_owner field:', 'is_owner' in debugCurrentUser, 'Value:', debugCurrentUser.is_owner);
- }
-
- // Set up event listeners
- setupEventListeners(); // Ensure this doesn't also try to init settings menu
-
- // Set up direct event listeners for critical elements
- setupCriticalEventListeners();
-
- // Make functions globally accessible if needed
- window.deleteUser = deleteUser;
- window.directDeleteUserAPI = directDeleteUserAPI;
-
- // Add global click handlers if needed
- // ... (existing delete button handler logic) ...
-
- // Initialize dark mode toggle
- initDarkModeToggle();
- // Clear dark mode preference on logout for privacy
- if (window.auth && window.auth.onLogout) {
- window.auth.onLogout(() => {
- localStorage.removeItem('darkMode');
- });
- }
-
- // REMOVED initSettingsMenu() call - Handled by auth.js
-
- // Load initial data for the settings page
- loadUserData();
- loadTimezones().then(() => loadPreferences()).catch(err => {
- console.error('Error loading timezones/prefs:', err);
- loadPreferences(); // Try loading prefs anyway
- });
-
- // --- ADD THIS LINE TO INITIALIZE MODALS ---
- initModals();
-
- // Initialize collapsible cards
- initCollapsibleCards();
-
- // Load admin-only settings if user is admin
- // Note: These will also be loaded later in loadUserData() with proper checks
- // This is a redundant call that should be conditional
- const currentUser = window.auth && window.auth.getCurrentUser ? window.auth.getCurrentUser() : null;
- if (currentUser && currentUser.is_admin) {
- // Load site settings (for admins) - includes OIDC settings
- loadSiteSettings();
-
- // Load Apprise settings
- loadAppriseSettings();
-
- // Load Apprise site settings (also loads overall Apprise settings)
- loadAppriseSiteSettings();
-
- // Initialize ownership management if user is owner
- if (currentUser.is_owner) {
- console.log('DEBUG: User is owner, initializing ownership management');
- setTimeout(() => {
- const ownershipSection = document.getElementById('ownershipSection');
- if (ownershipSection) {
- ownershipSection.style.display = 'block';
- console.log('DEBUG: Ownership section made visible');
- }
- // Don't load users here - wait for modal to open
- console.log('DEBUG: Ownership management initialized, users will load when modal opens');
- }, 500); // Wait for DOM to be ready
- }
- } else {
- console.log('User is not admin, skipping admin-only settings load during initialization');
- }
-
- // Setup Apprise event listeners
- setupAppriseEventListeners();
-
- // Audit Trail button handler (admin section)
- const viewAuditTrailBtn = document.getElementById('viewAuditTrailBtn');
- if (viewAuditTrailBtn) {
- viewAuditTrailBtn.addEventListener('click', loadAndDisplayAuditTrail);
- }
-
- // Initialize delete button handling
- setupDeleteButton();
-});
-
-/**
- * Initialize the settings page
- */
-function initPage() {
- console.log('Initializing settings page');
-
- // Initialize language selector when i18n is ready
- initLanguageSelectorWhenReady();
-
- // Check authentication
- if (window.auth) {
- window.auth.checkAuthState();
-
- // Redirect to login if not authenticated
- if (!window.auth.isAuthenticated()) {
- console.log('User not authenticated, redirecting to login');
- window.location.href = 'login.html';
- return;
- }
- } else {
- // Auth module not loaded
- console.error('Auth module not loaded');
- window.location.href = 'login.html';
- return;
- }
-
- // Load user data and preferences with error handling
- try {
- // First load timezones, then load preferences to ensure correct order
- loadTimezones().then(() => {
- console.log('Timezones loaded, now loading preferences');
- loadPreferences();
- }).catch(err => {
- console.error('Error loading timezones:', err);
- // Still try to load preferences even if timezones fail
- loadPreferences();
- });
-
- loadUserData().catch(err => {
- console.error('Error loading user data:', err);
- // Continue with page initialization even if user data fails
- });
- } catch (err) {
- console.error('Error during page initialization:', err);
- // Continue despite errors to allow basic functionality
- }
-
- // Fix for settings button - not needed anymore as we've removed it
- if (settingsBtn) {
- console.log('Settings button found, adding event listener');
- settingsBtn.addEventListener('click', function(e) {
- e.stopPropagation();
- settingsMenu.classList.toggle('active');
- console.log('Settings button clicked, menu toggled');
- });
-
- // Close settings menu when clicking outside
- document.addEventListener('click', function(e) {
- if (settingsMenu.classList.contains('active') &&
- !settingsMenu.contains(e.target) &&
- !settingsBtn.contains(e.target)) {
- settingsMenu.classList.remove('active');
- }
- });
- } else {
- console.log('Settings button not found - this is expected after UI update');
- }
-
- console.log('Settings page initialization complete');
-}
-
-// ============================
-// Audit Trail functions
-// ============================
-
-async function loadAndDisplayAuditTrail() {
- const displayArea = document.getElementById('auditTrailDisplay');
- const loadingIndicator = document.getElementById('auditTrailLoading');
- const table = document.getElementById('auditTrailTable');
- const tableBody = document.getElementById('auditTrailTableBody');
-
- if (!displayArea || !loadingIndicator || !table || !tableBody) return;
-
- displayArea.style.display = 'block';
- loadingIndicator.style.display = 'block';
- table.style.display = 'none';
- tableBody.innerHTML = '';
-
- try {
- const token = window.auth && window.auth.getToken ? window.auth.getToken() : localStorage.getItem('auth_token');
- const response = await fetch('/api/admin/audit-trail?limit=200', {
- headers: { 'Authorization': `Bearer ${token}` }
- });
-
- if (!response.ok) {
- throw new Error('Failed to fetch audit log');
- }
-
- const logs = await response.json();
- renderAuditTrail(logs);
-
- } catch (error) {
- console.error('Error loading audit trail:', error);
- loadingIndicator.textContent = 'Error loading audit trail.';
- }
-}
-
-function renderAuditTrail(logs) {
- const loadingIndicator = document.getElementById('auditTrailLoading');
- const table = document.getElementById('auditTrailTable');
- const tableBody = document.getElementById('auditTrailTableBody');
-
- loadingIndicator.style.display = 'none';
-
- if (!Array.isArray(logs) || logs.length === 0) {
- tableBody.innerHTML = '<tr><td colspan="4" style="text-align: center;">No audit records found.</td></tr>';
- } else {
- logs.forEach(log => {
- const row = tableBody.insertRow();
- const timestamp = log.timestamp ? new Date(log.timestamp).toLocaleString() : '';
- const username = (log.username || 'System');
- const action = (log.action || '');
- const details = log.details ? escapeHtmlSafe(log.details) : 'N/A';
-
- row.innerHTML = `
- <td title='${log.ip_address || ''}'>${timestamp}</td>
- <td>${escapeHtmlSafe(username)}</td>
- <td><span class='badge'>${escapeHtmlSafe(action)}</span></td>
- <td style='white-space: pre-wrap; word-break: break-word;'>${details}</td>
- `;
- });
- }
- table.style.display = 'table';
-}
-
-function escapeHtmlSafe(text) {
- if (typeof text !== 'string') return text;
- const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
- return text.replace(/[&<>"']/g, m => map[m]);
-}
-
-/**
- * Setup critical event listeners that must work for core functionality
- */
-function setupCriticalEventListeners() {
- console.log('Setting up critical event listeners');
-
- // Set up delete user modal close buttons
- const closeModalButtons = document.querySelectorAll('.close-modal');
- closeModalButtons.forEach(button => {
- button.addEventListener('click', function() {
- closeAllModals();
- });
- });
-
- // Set up delete user button in the modal
- const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');
- if (confirmDeleteUserBtn) {
- console.log('Setting up confirmDeleteUserBtn');
-
- // Add multiple event handlers for redundancy
- confirmDeleteUserBtn.addEventListener('click', function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Delete button clicked via addEventListener in setupCriticalEventListeners');
- deleteUser();
- return false;
- });
-
- confirmDeleteUserBtn.onclick = function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Delete button clicked via onclick in setupCriticalEventListeners');
- deleteUser();
- return false;
- };
- }
-
- // Set up direct delete link
- const directDeleteLink = document.getElementById('directDeleteLink');
- if (directDeleteLink) {
- directDeleteLink.addEventListener('click', function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Direct delete link clicked in setupCriticalEventListeners');
- deleteUser();
- return false;
- });
- }
-
- // Set up direct API link
- const directAPILink = document.getElementById('directAPILink');
- if (directAPILink) {
- directAPILink.addEventListener('click', function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Direct API link clicked in setupCriticalEventListeners');
- const userId = window.currentDeleteUserId ||
- (document.getElementById('deleteUserId') ? document.getElementById('deleteUserId').value : null);
- directDeleteUserAPI(userId);
- return false;
- });
- }
-
- // Set up delete user form
- const deleteUserForm = document.getElementById('deleteUserForm');
- if (deleteUserForm) {
- deleteUserForm.addEventListener('submit', function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Delete user form submitted in setupCriticalEventListeners');
- deleteUser();
- return false;
- });
- }
-}
-
-/**
- * Load user data from localStorage and API
- */
-async function loadUserData() {
- showLoading();
- // Get the new display elements
- const userNameDisplay = document.getElementById('currentUserNameDisplay');
- const userEmailDisplay = document.getElementById('currentUserEmailDisplay');
-
- try {
- // Get user from localStorage first
- const currentUser = window.auth.getCurrentUser();
-
- if (currentUser) {
- // Populate form fields
- if (firstNameInput) firstNameInput.value = currentUser.first_name || ''; // Add null checks
- if (lastNameInput) lastNameInput.value = currentUser.last_name || ''; // Add null checks
- if (emailInput) emailInput.value = currentUser.email || ''; // Add null checks
-
- // --- UPDATE DISPLAY ELEMENT (Initial Load) ---
- let displayName;
- if (currentUser.first_name && currentUser.last_name) {
- displayName = `${currentUser.first_name} ${currentUser.last_name}`;
- } else {
- displayName = currentUser.username || 'User';
- }
- if (userNameDisplay) userNameDisplay.textContent = displayName;
- if (userEmailDisplay) userEmailDisplay.textContent = currentUser.email || 'N/A';
-
- if (currentUser.oidc_managed) {
- if (firstNameInput) firstNameInput.disabled = true;
- if (lastNameInput) lastNameInput.disabled = true;
- if (emailInput) emailInput.disabled = true;
- if (saveProfileBtn) saveProfileBtn.style.display = 'none';
- userEditDesc = document.querySelector('#currentUserInfoDisplay > p > strong')
- if (userEditDesc) {
- userEditDesc.setAttribute('data-i18n', 'settings.current_user_oidc')
- userEditDesc.textContent = 'OIDC managed profile for:'
- }
- securitySection = document.getElementById('securitySection');
- if (securitySection) securitySection.style.display = 'none';
- }
- // --- END UPDATE ---
-
- // Admin section visibility will be determined after API call
- }
-
- // Fetch fresh user data from API
- try {
- const response = await fetch('/api/auth/user', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
- }
- });
-
- if (response.ok) {
- const userData = await response.json();
-
- // Update form fields with fresh data
- if (firstNameInput) firstNameInput.value = userData.first_name || ''; // Add null checks
- if (lastNameInput) lastNameInput.value = userData.last_name || ''; // Add null checks
- if (emailInput) emailInput.value = userData.email || ''; // Add null checks
-
- // --- UPDATE DISPLAY ELEMENT (After API Load) ---
- let displayName;
- if (userData.first_name && userData.last_name) {
- displayName = `${userData.first_name} ${userData.last_name}`;
- } else {
- displayName = userData.username || 'User';
- }
- if (userNameDisplay) userNameDisplay.textContent = displayName;
- if (userEmailDisplay) userEmailDisplay.textContent = userData.email || 'N/A';
- // --- END UPDATE ---
-
- // Show admin section if user is admin and load admin-specific data
- if (userData.is_admin) {
- if (adminSection) {
- adminSection.style.display = 'block';
- // Ensure admin-specific data is loaded AFTER section is visible
- if (usersTableBody) loadUsers();
- // Check for site settings elements directly to avoid cache timing issues
- const hasRegistrationToggle = document.getElementById('registrationEnabled');
- const hasOidcToggle = document.getElementById('oidcEnabled');
- if (hasRegistrationToggle || hasOidcToggle) {
- console.log('Admin settings elements found, loading site settings...');
- loadSiteSettings();
- } else {
- console.warn('Admin settings elements not found - this might be a timing/cache issue');
- }
- }
- } else {
- if (adminSection) adminSection.style.display = 'none';
- }
-
- // Update localStorage ONLY if data has changed
- const currentUser = window.auth.getCurrentUser();
- let first_name = userData.first_name;
- let last_name = userData.last_name;
- if (!last_name) first_name = ''; // Reset first name if last name is empty
-
- const updatedUser = {
- ...(currentUser || {}), // Preserve existing fields
- first_name, // Update first name
- last_name, // Update last name
- // Preserve other essential fields from fetched data if currentUser was null
- email: currentUser ? currentUser.email : userData.email,
- username: currentUser ? currentUser.username : userData.username,
- is_admin: currentUser ? currentUser.is_admin : userData.is_admin,
- id: currentUser ? currentUser.id : userData.id
- };
-
- // Convert both to JSON strings for reliable comparison
- const currentUserString = JSON.stringify(currentUser);
- const updatedUserString = JSON.stringify(updatedUser);
-
- if (currentUserString !== updatedUserString) {
- console.log('User data changed, updating localStorage.');
- localStorage.setItem('user_info', updatedUserString);
- } else {
- console.log('User data from API matches localStorage, skipping update.');
- }
- // localStorage.setItem('user_info', JSON.stringify(updatedUser)); // OLD LINE
- } else {
- const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
- console.warn('API error fetching user data:', errorData.message);
- if (!currentUser) {
- showToast(errorData.message || 'Failed to load fresh user data', 'warning');
- }
- }
- } catch (apiError) {
- console.warn('API error, using localStorage data:', apiError);
- if (!currentUser) {
- showToast('Could not connect to fetch user data. Displaying cached info.', 'warning');
- }
- }
- } catch (error) {
- console.error('Error loading user data:', error);
- showToast('Failed to load user data. Please try again.', 'error');
- if (userNameDisplay) userNameDisplay.textContent = 'Error';
- if (userEmailDisplay) userEmailDisplay.textContent = 'Error';
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Get current user type (admin or user)
- * @returns {string} 'admin' or 'user'
- */
-function getUserType() {
- try {
- const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
- return userInfo.is_admin === true ? 'admin' : 'user';
- } catch (e) {
- console.error('Error determining user type:', e);
- return 'user'; // Default to user if we can't determine
- }
-}
-
-/**
- * Get the appropriate localStorage key prefix based on user type
- * @returns {string} The prefix to use for localStorage keys
- */
-function getPreferenceKeyPrefix() {
- return getUserType() === 'admin' ? 'admin_' : 'user_';
-}
-
-// Prevent multiple simultaneous preference loads
-let isLoadingPreferences = false;
-
-/**
- * Load user preferences
- */
-async function loadPreferences() {
- // Prevent multiple simultaneous loads
- if (isLoadingPreferences) {
- console.log('Preferences already loading, skipping duplicate call');
- return;
- }
-
- isLoadingPreferences = true;
- console.log('Loading preferences...');
- const prefix = getPreferenceKeyPrefix();
- console.log('Loading preferences with prefix:', prefix);
-
- let apiPrefs = null;
-
- // FIXED: Load all preferences from API first, then apply to UI
- if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
- try {
- const response = await fetch('/api/auth/preferences', {
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
- }
- });
- if (response.ok) {
- apiPrefs = await response.json();
- console.log('API preferences loaded:', apiPrefs);
-
- // Apply theme from API immediately (highest priority)
- if (apiPrefs && apiPrefs.theme) {
- const isDark = apiPrefs.theme === 'dark';
- console.log('Applying theme from API:', apiPrefs.theme, 'isDark:', isDark);
- setTheme(isDark);
- // Sync localStorage to match API
- localStorage.setItem('darkMode', isDark);
- // Ensure the dark mode toggle reflects the API setting
- if (darkModeToggleSetting) {
- darkModeToggleSetting.checked = isDark;
- console.log('Synced dark mode toggle to API value:', isDark);
- }
- } else {
- console.log('No theme in API preferences, using localStorage fallback');
- const storedDarkMode = localStorage.getItem('darkMode') === 'true';
- setTheme(storedDarkMode);
- if (darkModeToggleSetting) {
- darkModeToggleSetting.checked = storedDarkMode;
- }
- }
- } else {
- console.warn('API preferences request failed, using localStorage');
- const storedDarkMode = localStorage.getItem('darkMode') === 'true';
- setTheme(storedDarkMode);
- }
- } catch (e) {
- console.warn('Failed to load preferences from backend:', e);
- // Fallback to localStorage
- const storedDarkMode = localStorage.getItem('darkMode') === 'true';
- setTheme(storedDarkMode);
- }
- } else {
- console.log('Not authenticated, using localStorage for theme');
- const storedDarkMode = localStorage.getItem('darkMode') === 'true';
- setTheme(storedDarkMode);
- }
- // --- Load Date Format --- Add this section
- const storedDateFormat = localStorage.getItem('dateFormat');
- if (storedDateFormat && dateFormatSelect) {
- dateFormatSelect.value = storedDateFormat;
- console.log(`Loaded dateFormat from localStorage: ${storedDateFormat}`);
- } else if (dateFormatSelect) {
- dateFormatSelect.value = 'MDY'; // Default if not found
- console.log('dateFormat not found in localStorage, defaulting to MDY');
- }
- // --- End Date Format Section ---
-
- // Default View
- const storedView = localStorage.getItem(`${prefix}defaultView`);
- if (storedView && defaultViewSelect) {
- defaultViewSelect.value = storedView;
- console.log(`Loaded default view from ${prefix}defaultView: ${storedView}`);
- } else if (defaultViewSelect) {
- defaultViewSelect.value = 'grid'; // Default
- console.log(`${prefix}defaultView not found, defaulting view to grid`);
- }
-
- // Currency Symbol - Load stored preference first
- const storedCurrency = localStorage.getItem(`${prefix}currencySymbol`);
-
- // Load currencies from API and set the saved preference
- await loadCurrenciesForSettings();
-
- if (storedCurrency) {
- if (currencySymbolSelect) {
- // Check if the stored symbol is a standard option
- const standardOption = Array.from(currencySymbolSelect.options).find(opt => opt.value === storedCurrency);
- if (standardOption) {
- currencySymbolSelect.value = storedCurrency;
- if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
- console.log(`Set currency dropdown to stored value: ${storedCurrency}`);
- } else {
- // It's a custom symbol
- currencySymbolSelect.value = 'other';
- if (currencySymbolCustom) {
- currencySymbolCustom.value = storedCurrency;
- currencySymbolCustom.style.display = 'inline-block';
- }
- console.log(`Set currency to custom value: ${storedCurrency}`);
- }
- console.log(`Loaded currency symbol from ${prefix}currencySymbol: ${storedCurrency}`);
- }
- } else {
- // Default to '$' if nothing stored
- if (currencySymbolSelect) currencySymbolSelect.value = '$';
- if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
- console.log(`${prefix}currencySymbol not found, defaulting to $`);
- }
-
- // Currency Position
- const storedCurrencyPosition = localStorage.getItem(`${prefix}currencyPosition`);
- if (storedCurrencyPosition && currencyPositionSelect) {
- currencyPositionSelect.value = storedCurrencyPosition;
- console.log(`Loaded currency position from ${prefix}currencyPosition: ${storedCurrencyPosition}`);
- } else if (currencyPositionSelect) {
- currencyPositionSelect.value = 'left'; // Default
- console.log(`${prefix}currencyPosition not found, defaulting to left`);
- }
-
- // Expiring Soon Days
- const storedExpiringDays = localStorage.getItem(`${prefix}expiringSoonDays`);
- if (storedExpiringDays && expiringSoonDaysInput) {
- expiringSoonDaysInput.value = storedExpiringDays;
- console.log(`Loaded expiring soon days from ${prefix}expiringSoonDays: ${storedExpiringDays}`);
- } else if (expiringSoonDaysInput) {
- expiringSoonDaysInput.value = 30; // Default
- console.log(`${prefix}expiringSoonDays not found, defaulting to 30`);
- }
-
- // Paperless View in App
- const storedPaperlessViewInApp = localStorage.getItem(`${prefix}paperlessViewInApp`);
- if (storedPaperlessViewInApp !== null && paperlessViewInAppToggle) {
- paperlessViewInAppToggle.checked = storedPaperlessViewInApp === 'true';
- console.log(`Loaded Paperless view in app from ${prefix}paperlessViewInApp: ${storedPaperlessViewInApp}`);
- } else if (paperlessViewInAppToggle) {
- paperlessViewInAppToggle.checked = false; // Default
- console.log(`${prefix}paperlessViewInApp not found, defaulting to false`);
- }
-
- // Apply API preferences to form elements (apiPrefs already loaded above)
- if (apiPrefs) {
- console.log('Applying API preferences to form elements:', apiPrefs);
-
- // Update UI elements with API data where available
- if (apiPrefs.default_view && defaultViewSelect) {
- // Only update if different from localStorage value (or if localStorage was empty)
- const storedView = localStorage.getItem(`${prefix}defaultView`) || 'grid'; // Default if null
- if (apiPrefs.default_view !== storedView) {
- console.log(`API default_view (${apiPrefs.default_view}) differs from localStorage (${storedView}). Updating UI.`);
- defaultViewSelect.value = apiPrefs.default_view;
- }
- }
- // --- MODIFIED CURRENCY SYMBOL HANDLING ---
- const storedCurrency = localStorage.getItem(`${prefix}currencySymbol`); // Get localStorage value again for comparison
- if (apiPrefs.currency_symbol && currencySymbolSelect) {
- // Only update UI from API if the API value is different from what was in localStorage
- // Or if localStorage didn't have a value initially
- if (!storedCurrency || apiPrefs.currency_symbol !== storedCurrency) {
- console.log(`API currency_symbol (${apiPrefs.currency_symbol}) differs from localStorage (${storedCurrency}). Updating UI.`);
- // Logic to handle standard vs custom symbol from API
- const standardOption = Array.from(currencySymbolSelect.options).find(opt => opt.value === apiPrefs.currency_symbol);
- if (standardOption) {
- currencySymbolSelect.value = apiPrefs.currency_symbol;
- if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
- } else {
- currencySymbolSelect.value = 'other';
- if (currencySymbolCustom) {
- currencySymbolCustom.value = apiPrefs.currency_symbol;
- currencySymbolCustom.style.display = 'inline-block';
- }
- }
- } else {
- console.log(`API currency_symbol (${apiPrefs.currency_symbol}) matches localStorage (${storedCurrency}). Skipping UI update.`);
- }
- }
- // --- END MODIFIED CURRENCY SYMBOL HANDLING ---
-
- // --- CURRENCY POSITION HANDLING ---
- const storedCurrencyPosition = localStorage.getItem(`${prefix}currencyPosition`);
- if (apiPrefs.currency_position && currencyPositionSelect) {
- if (!storedCurrencyPosition || apiPrefs.currency_position !== storedCurrencyPosition) {
- console.log(`API currency_position (${apiPrefs.currency_position}) differs from localStorage (${storedCurrencyPosition}). Updating UI.`);
- currencyPositionSelect.value = apiPrefs.currency_position;
- } else {
- console.log(`API currency_position (${apiPrefs.currency_position}) matches localStorage (${storedCurrencyPosition}). Skipping UI update.`);
- }
- }
- // --- END CURRENCY POSITION HANDLING ---
- if (apiPrefs.expiring_soon_days && expiringSoonDaysInput) {
- // Only update if different from localStorage value (or if localStorage was empty)
- const storedExpiringDays = localStorage.getItem(`${prefix}expiringSoonDays`) || '30'; // Default if null
- if (String(apiPrefs.expiring_soon_days) !== storedExpiringDays) {
- console.log(`API expiring_soon_days (${apiPrefs.expiring_soon_days}) differs from localStorage (${storedExpiringDays}). Updating UI.`);
- expiringSoonDaysInput.value = apiPrefs.expiring_soon_days;
- }
- }
-
- // --- Update Date Format from API Prefs --- Add this check
- const storedDateFormat = localStorage.getItem('dateFormat') || 'MDY'; // Default if null
- if (apiPrefs.date_format && dateFormatSelect) {
- if (apiPrefs.date_format !== storedDateFormat) {
- console.log(`API date_format (${apiPrefs.date_format}) differs from localStorage (${storedDateFormat}). Updating UI.`);
- dateFormatSelect.value = apiPrefs.date_format;
- }
- }
- // --- End Date Format Check ---
-
- // --- Update Paperless View in App from API Prefs ---
- if (apiPrefs.paperless_view_in_app !== undefined && paperlessViewInAppToggle) {
- paperlessViewInAppToggle.checked = apiPrefs.paperless_view_in_app;
- console.log(`Set Paperless view in app from API: ${apiPrefs.paperless_view_in_app}`);
- }
- // --- End Paperless View in App from API Prefs ---
-
- // Update Email Settings from API
- if (notificationChannel) {
- const channelValue = apiPrefs.notification_channel || 'email'; // Default to email if not present
- notificationChannel.value = channelValue;
- toggleNotificationSettings(channelValue);
- console.log('Set notification channel to:', channelValue);
- }
- if (notificationFrequencySelect && apiPrefs.notification_frequency) {
- notificationFrequencySelect.value = apiPrefs.notification_frequency;
- }
- if (notificationTimeInput && apiPrefs.notification_time) {
- notificationTimeInput.value = apiPrefs.notification_time.substring(0, 5); // HH:MM format
- }
- // Admin Apprise settings (in Apprise card)
- if (appriseNotificationFrequency && apiPrefs.apprise_notification_frequency) {
- appriseNotificationFrequency.value = apiPrefs.apprise_notification_frequency;
- }
-
- // User-specific Apprise settings (in notification settings section)
- if (userAppriseNotificationTimeInput && apiPrefs.apprise_notification_time) {
- userAppriseNotificationTimeInput.value = apiPrefs.apprise_notification_time.substring(0, 5);
- }
- if (userAppriseTimezoneSelect && apiPrefs.apprise_timezone) {
- if (Array.from(userAppriseTimezoneSelect.options).some(option => option.value === apiPrefs.apprise_timezone)) {
- userAppriseTimezoneSelect.value = apiPrefs.apprise_timezone;
- } else {
- console.warn(`User Apprise timezone '${apiPrefs.apprise_timezone}' from API not found in dropdown.`);
- }
- }
- if (userAppriseNotificationFrequency && apiPrefs.apprise_notification_frequency) {
- userAppriseNotificationFrequency.value = apiPrefs.apprise_notification_frequency;
- }
-
- // Update Apprise timezone display
- updateAppriseTimezoneDisplay(apiPrefs.timezone);
- // Load and set timezone from API
- if (timezoneSelect && apiPrefs.timezone) {
- console.log('API provided timezone:', apiPrefs.timezone);
- // Ensure the option exists before setting
- if (Array.from(timezoneSelect.options).some(option => option.value === apiPrefs.timezone)) {
- timezoneSelect.value = apiPrefs.timezone;
- console.log('Applied timezone from API:', timezoneSelect.value, 'Current select value:', timezoneSelect.value);
-
- // Update Apprise timezone display when timezone is loaded
- updateAppriseTimezoneDisplay(apiPrefs.timezone);
- } else {
- console.warn(`Timezone '${apiPrefs.timezone}' from API not found in dropdown.`);
- }
- } else {
- console.log('No timezone preference found in API or timezone select element missing.');
- }
-
- // Load and set language preference
- if (apiPrefs.preferred_language && languageSelect) {
- console.log('API provided language:', apiPrefs.preferred_language);
- // Ensure the option exists before setting
- if (Array.from(languageSelect.options).some(option => option.value === apiPrefs.preferred_language)) {
- languageSelect.value = apiPrefs.preferred_language;
- console.log('Applied language from API:', languageSelect.value);
-
- // Trigger language change if different from current
- if (window.i18n?.changeLanguage && window.i18n?.getCurrentLanguage) {
- const currentLang = window.i18n.getCurrentLanguage();
- if (apiPrefs.preferred_language !== currentLang) {
- console.log(`Language preference (${apiPrefs.preferred_language}) differs from current (${currentLang}), changing language`);
- window.i18n.changeLanguage(apiPrefs.preferred_language).catch(error => {
- console.error('Failed to change language from API preference:', error);
- });
- }
- }
- } else {
- console.warn(`Language '${apiPrefs.preferred_language}' from API not found in dropdown.`);
- }
- } else {
- // Load from localStorage if no API preference
- const storedLanguage = localStorage.getItem('preferred_language') || 'en';
- if (languageSelect) {
- languageSelect.value = storedLanguage;
- console.log('Applied language from localStorage:', storedLanguage);
-
- // Trigger language change if different from current
- if (window.i18n?.changeLanguage && window.i18n?.getCurrentLanguage) {
- const currentLang = window.i18n.getCurrentLanguage();
- if (storedLanguage !== currentLang) {
- console.log(`Stored language (${storedLanguage}) differs from current (${currentLang}), changing language`);
- window.i18n.changeLanguage(storedLanguage).catch(error => {
- console.error('Failed to change language from localStorage:', error);
- });
- }
- }
- }
- }
- } else {
- // No API preferences, load language from localStorage
- const storedLanguage = localStorage.getItem('preferred_language') || 'en';
- if (languageSelect) {
- languageSelect.value = storedLanguage;
- console.log('Applied language from localStorage (no API):', storedLanguage);
-
- // Trigger language change if different from current
- if (window.i18n?.changeLanguage && window.i18n?.getCurrentLanguage) {
- const currentLang = window.i18n.getCurrentLanguage();
- if (storedLanguage !== currentLang) {
- console.log(`Stored language (${storedLanguage}) differs from current (${currentLang}), changing language`);
- window.i18n.changeLanguage(storedLanguage).catch(error => {
- console.error('Failed to change language from localStorage (no API):', error);
- });
- }
- }
- }
- }
-
- // Reset the loading flag
- isLoadingPreferences = false;
- console.log('Preferences loading completed');
-}
-
-/**
- * Update the Apprise timezone display to show which timezone will be used
- */
-function updateAppriseTimezoneDisplay(timezone) {
- const appriseTimezoneDisplay = document.getElementById('appriseTimezoneDisplay');
- if (appriseTimezoneDisplay) {
- if (timezone) {
- appriseTimezoneDisplay.textContent = `(using timezone: ${timezone})`;
- appriseTimezoneDisplay.style.display = 'inline';
- } else {
- appriseTimezoneDisplay.textContent = '(timezone not set)';
- appriseTimezoneDisplay.style.display = 'inline';
- }
- }
-}
-
-/**
- * Setup event listeners for the settings page
- */
-function setupEventListeners() {
- console.log('Setting up event listeners');
-
- // Set up user menu button click handler
- // const userMenuBtn = document.getElementById('userMenuBtn'); // REMOVE/COMMENT OUT
- // const userMenuDropdown = document.getElementById('userMenuDropdown'); // REMOVE/COMMENT OUT
-
- // if (userMenuBtn && userMenuDropdown) { // REMOVE/COMMENT OUT THIS ENTIRE BLOCK
- // console.log('Setting up user menu button click handler');
- // userMenuBtn.addEventListener('click', function(e) {
- // e.stopPropagation();
- // userMenuDropdown.classList.toggle('active');
- // });
- // document.addEventListener('click', function(e) {
- // if (userMenuDropdown.classList.contains('active') &&
- // !userMenuDropdown.contains(e.target) &&
- // !userMenuBtn.contains(e.target)) {
- // userMenuDropdown.classList.remove('active');
- // }
- // });
- // }
-
- // Dark mode toggle in header (no longer exists)
- if (darkModeToggle) {
- darkModeToggle.addEventListener('change', function() {
- setTheme(this.checked);
-
- // Also update the settings page toggle
- if (darkModeToggleSetting) {
- darkModeToggleSetting.checked = this.checked;
- }
- });
- }
-
- // Dark mode toggle in settings
- if (darkModeToggleSetting) {
- darkModeToggleSetting.addEventListener('change', function() {
- setTheme(this.checked);
-
- // Also update the header toggle if it exists
- if (darkModeToggle) {
- darkModeToggle.checked = this.checked;
- }
- });
- }
-
- // Save profile button
- if (saveProfileBtn) {
- saveProfileBtn.addEventListener('click', saveProfile);
- }
-
- // Save preferences button
- if (savePreferencesBtn) {
- savePreferencesBtn.addEventListener('click', savePreferences);
- }
-
- // Change password button
- if (changePasswordBtn) {
- changePasswordBtn.addEventListener('click', function() {
- passwordChangeForm.style.display = 'block';
- this.style.display = 'none';
- });
- }
-
- // Save password button
- if (savePasswordBtn) {
- savePasswordBtn.addEventListener('click', changePassword);
- }
-
- // Cancel password button
- if (cancelPasswordBtn) {
- cancelPasswordBtn.addEventListener('click', function() {
- resetPasswordForm();
- passwordChangeForm.style.display = 'none';
- changePasswordBtn.style.display = 'block';
- });
- }
-
- // Delete account button
- if (deleteAccountBtn) {
- deleteAccountBtn.addEventListener('click', function() {
- openModal(deleteAccountModal);
- });
- }
-
- // Delete confirm input
- if (deleteConfirmInput) {
- deleteConfirmInput.addEventListener('input', function() {
- confirmDeleteAccountBtn.disabled = this.value !== 'DELETE';
- });
- }
-
- // Confirm delete account button
- if (confirmDeleteAccountBtn) {
- confirmDeleteAccountBtn.addEventListener('click', deleteAccount);
- }
-
- // Add event listener for logout menu item
- const logoutMenuItem = document.getElementById('logoutMenuItem');
- if (logoutMenuItem) {
- logoutMenuItem.addEventListener('click', function() {
- if (window.auth && window.auth.logout) {
- window.auth.logout();
- }
- });
- }
-
- // Admin section buttons
- if (refreshUsersBtn) {
- refreshUsersBtn.addEventListener('click', function() {
- loadUsers();
- });
- }
-
- if (checkAdminBtn) {
- checkAdminBtn.addEventListener('click', function() {
- checkAdminPermissions();
- });
- }
-
- if (showUsersBtn) {
- showUsersBtn.addEventListener('click', function() {
- console.log('Show Users List button clicked');
- // Open the proper users modal that has crown icons and ownership management
- const usersModal = document.getElementById('usersModal');
- if (usersModal) {
- openModal(usersModal);
- loadUsers(); // This will populate the table with crown icons
- } else {
- console.error('usersModal not found, falling back to showUsersList');
- showUsersList();
- }
- });
- }
-
- if (testApiBtn) {
- testApiBtn.addEventListener('click', function() {
- checkApiEndpoint();
- });
- }
-
- if (triggerNotificationsBtn) {
- triggerNotificationsBtn.addEventListener('click', function() {
- triggerWarrantyNotifications();
- });
- }
-
- if (schedulerStatusBtn) {
- schedulerStatusBtn.addEventListener('click', function() {
- checkSchedulerStatus();
- });
- }
-
- // Site settings save button
- if (saveSiteSettingsBtn) {
- saveSiteSettingsBtn.addEventListener('click', function() {
- saveSiteSettings(); // This will now also handle non-OIDC site settings
- });
- }
-
- // Save OIDC settings button
- if (saveOidcSettingsBtn) {
- saveOidcSettingsBtn.addEventListener('click', function() {
- saveOidcSettings();
- });
- }
-
- // Save email settings button
- if (saveNotificationSettingsBtn) {
- saveNotificationSettingsBtn.addEventListener('click', saveNotificationSettings);
- }
-
- // Save user changes button (Edit User Modal)
- const saveUserBtn = document.getElementById('saveUserBtn');
- if (saveUserBtn) {
- saveUserBtn.addEventListener('click', function(e) {
- e.preventDefault();
- console.log('Save User button clicked');
- saveUserChanges();
- });
- }
-
- // Add timezone change listener to update Apprise timezone display
- const timezoneSelect = document.getElementById('timezone');
- if (timezoneSelect) {
- timezoneSelect.addEventListener('change', function() {
- updateAppriseTimezoneDisplay(this.value);
- });
- }
-
-
-
- if (userAppriseTimezoneSelect) {
- loadTimezonesIntoSelect(userAppriseTimezoneSelect);
- }
-
- if (notificationChannel) {
- notificationChannel.addEventListener('change', (e) => {
- toggleNotificationSettings(e.target.value);
- });
- }
-
- // Paperless-ngx event listeners
- if (paperlessEnabledToggle) {
- paperlessEnabledToggle.addEventListener('change', function() {
- togglePaperlessSettings(this.checked);
- });
- }
-
- if (testPaperlessConnectionBtn) {
- testPaperlessConnectionBtn.addEventListener('click', testPaperlessConnection);
- }
-
- if (savePaperlessSettingsBtn) {
- savePaperlessSettingsBtn.addEventListener('click', savePaperlessSettings);
- }
-
- // Add debug button event listener
- const debugPaperlessBtn = document.getElementById('debugPaperlessBtn');
- if (debugPaperlessBtn) {
- debugPaperlessBtn.addEventListener('click', debugPaperlessConfiguration);
- }
-
- // Add test upload button event listener
- const testFileUploadBtn = document.getElementById('testFileUploadBtn');
- if (testFileUploadBtn) {
- testFileUploadBtn.addEventListener('click', testFileUpload);
- }
-
- // Clear status message when inputs are changed
- if (paperlessUrlInput) {
- paperlessUrlInput.addEventListener('input', function() {
- if (paperlessConnectionStatus) {
- paperlessConnectionStatus.className = 'paperless-status-message';
- paperlessConnectionStatus.innerHTML = '';
- }
- });
- }
-
- if (paperlessApiTokenInput) {
- paperlessApiTokenInput.addEventListener('input', function() {
- if (paperlessConnectionStatus) {
- paperlessConnectionStatus.className = 'paperless-status-message';
- paperlessConnectionStatus.innerHTML = '';
- }
- });
- }
-
- console.log('Event listeners setup complete');
-}
-
-/**
- * Initialize modals
- */
-function initModals() {
- // Helper to close all modals and reset forms
- function closeModalHandler(e) {
- if (e) e.preventDefault();
- document.querySelectorAll('.modal-backdrop').forEach(modal => {
- modal.style.display = 'none';
- });
- // Reset delete confirm input
- if (deleteConfirmInput) {
- deleteConfirmInput.value = '';
- confirmDeleteAccountBtn.disabled = true;
- }
- // Reset password form
- resetPasswordForm();
- }
-
- // Close modal when clicking on X or outside
- document.querySelectorAll('.close-btn, [data-dismiss="modal"]').forEach(closeBtn => {
- closeBtn.addEventListener('click', closeModalHandler);
- closeBtn.addEventListener('touchend', closeModalHandler);
- });
-
- // Close modal when clicking outside (backdrop)
- function backdropHandler(event) {
- document.querySelectorAll('.modal-backdrop').forEach(modal => {
- if (event.target === modal) {
- closeModalHandler(event);
- }
- });
- }
- window.addEventListener('click', backdropHandler);
- window.addEventListener('touchend', backdropHandler);
-
- // Add direct click handler to delete user modal
- if (deleteUserModal) {
- console.log('Adding click handler to deleteUserModal');
- deleteUserModal.addEventListener('click', function(event) {
- // Check if the click was on the confirm delete button
- if (event.target && event.target.id === 'confirmDeleteUserBtn') {
- event.preventDefault();
- console.log('Confirm delete button clicked through modal event delegation');
- deleteUser();
- }
- });
- } else {
- console.error('deleteUserModal not found in initModals');
- }
-
- // Set up transfer ownership modal close handlers
- const transferOwnershipModal = document.getElementById('transferOwnershipModal');
- if (transferOwnershipModal) {
- const transferConfirmInput = document.getElementById('transferConfirmInput');
- const confirmTransferBtn = document.getElementById('confirmTransferOwnershipBtn');
-
- if (transferConfirmInput && confirmTransferBtn) {
- transferConfirmInput.addEventListener('input', function() {
- confirmTransferBtn.disabled = this.value.toUpperCase() !== 'TRANSFER';
- });
- }
- }
-}
-
-/**
- * Initialize collapsible cards functionality
- */
-function initCollapsibleCards() {
- console.log('Initializing collapsible cards...');
-
- // Get all collapsible headers
- const collapsibleHeaders = document.querySelectorAll('.collapsible-header');
-
- // Retrieve saved states from localStorage
- const savedStates = JSON.parse(localStorage.getItem('collapsibleStates') || '{}');
-
- collapsibleHeaders.forEach(header => {
- const targetId = header.getAttribute('data-target');
- const card = header.closest('.collapsible-card');
-
- // Apply saved state or default to expanded
- const isCollapsed = savedStates[targetId] === true;
- if (isCollapsed) {
- card.classList.add('collapsed');
- }
-
- // Add click event listener
- header.addEventListener('click', function() {
- const targetId = this.getAttribute('data-target');
- const card = this.closest('.collapsible-card');
-
- // Toggle collapsed state
- card.classList.toggle('collapsed');
-
- // Save state to localStorage
- const currentStates = JSON.parse(localStorage.getItem('collapsibleStates') || '{}');
- currentStates[targetId] = card.classList.contains('collapsed');
- localStorage.setItem('collapsibleStates', JSON.stringify(currentStates));
-
- console.log(`Toggled ${targetId}: ${card.classList.contains('collapsed') ? 'collapsed' : 'expanded'}`);
- });
- });
-
- console.log('Collapsible cards initialized');
-}
-
-/**
- * Open a modal
- * @param {HTMLElement} modal - The modal to open
- */
-function openModal(modal) {
- console.log('Opening modal:', modal.id, 'Current display:', modal.style.display);
-
- // First close all modals
- closeAllModals();
-
- // Then open this modal
- modal.style.display = 'flex';
- console.log('Modal display after opening:', modal.style.display);
-
- // If this is the delete user modal, set up the delete button
- if (modal.id === 'deleteUserModal') {
- console.log('This is the delete user modal, setting up delete button');
- // Use setTimeout to ensure the DOM is fully updated
- setTimeout(() => {
- setupDeleteButton();
- }, 100);
- }
-}
-
-/**
- * Reset password form
- */
-function resetPasswordForm() {
- currentPasswordInput.value = '';
- newPasswordInput.value = '';
- confirmPasswordInput.value = '';
-}
-
-/**
- * Save user profile
- */
-async function saveProfile() {
- // Validate form
- if (!firstNameInput || !lastNameInput || !firstNameInput.value.trim() || !lastNameInput.value.trim()) {
- showToast('Please fill in First Name and Last Name', 'error');
- return;
- }
-
- // Get the new email value
- const newEmail = emailInput.value.trim();
- if (!newEmail) {
- showToast('Email address cannot be empty.', 'error');
- return;
- }
- // Basic email format validation
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
- if (!emailRegex.test(newEmail)) {
- showToast('Please enter a valid email address.', 'error');
- return;
- }
-
- showLoading();
- const userNameDisplay = document.getElementById('currentUserNameDisplay');
-
- try {
- const response = await fetch('/api/auth/profile', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- first_name: firstNameInput.value.trim(),
- last_name: lastNameInput.value.trim(),
- email: newEmail
- })
- });
-
- if (response.ok) {
- const userData = await response.json();
- // Update localStorage
- const currentUser = window.auth.getCurrentUser();
- let first_name = userData.first_name;
- let last_name = userData.last_name;
- if (!last_name) first_name = '';
- const updatedUser = {
- ...(currentUser || {}),
- first_name,
- last_name,
- email: userData.email, // Use the email returned from the backend
- username: currentUser ? currentUser.username : userData.username,
- is_admin: currentUser ? currentUser.is_admin : userData.is_admin,
- id: currentUser ? currentUser.id : userData.id
- };
- // Update the email input field with the (potentially new) email from the backend
- if (emailInput) emailInput.value = userData.email || '';
- localStorage.setItem('user_info', JSON.stringify(updatedUser));
-
- // --- UPDATE DISPLAY ELEMENT IMMEDIATELY ---
- let displayName;
- if (userData.first_name && userData.last_name) {
- displayName = `${userData.first_name} ${userData.last_name}`;
- } else {
- displayName = updatedUser.username || 'User';
- }
- if (userNameDisplay) userNameDisplay.textContent = displayName;
- // --- END UPDATE ---
-
- // Update UI (Header, etc.) - Ensure auth module is loaded
- if (window.auth && window.auth.checkAuthState) {
- window.auth.checkAuthState();
- } else {
- console.warn("Auth module or checkAuthState not found, header might not update immediately.");
- }
-
- showToast('Profile updated successfully', 'success');
- } else {
- const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
- throw new Error(errorData.message || 'Failed to update profile');
- }
- } catch (error) {
- console.error('Error updating profile:', error);
- showToast(`Failed to update profile: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Save user preferences
- */
-async function savePreferences() {
- console.log('Saving preferences...');
- const prefix = getPreferenceKeyPrefix();
-
- // Get current UI state FIRST (before building preferencesToSave)
- const isDark = darkModeToggleSetting ? darkModeToggleSetting.checked : false;
- console.log(`Current dark mode UI state: ${isDark}`);
-
- // --- Prepare data to save --- Add dateFormat and dark mode
- const preferencesToSave = {
- default_view: defaultViewSelect ? defaultViewSelect.value : 'grid',
- expiring_soon_days: expiringSoonDaysInput ? parseInt(expiringSoonDaysInput.value) : 30,
- date_format: dateFormatSelect ? dateFormatSelect.value : 'MDY',
- theme: isDark ? 'dark' : 'light', // Use current UI state, not old localStorage
- paperless_view_in_app: paperlessViewInAppToggle ? paperlessViewInAppToggle.checked : false,
- preferred_language: languageSelect ? languageSelect.value : 'en', // Include language preference
- };
-
- // Handle currency symbol (standard or custom)
- let currencySymbol = '$'; // Default
- let currencyCode = 'USD'; // Default
- if (currencySymbolSelect) {
- if (currencySymbolSelect.value === 'other' && currencySymbolCustom) {
- currencySymbol = currencySymbolCustom.value.trim() || '$'; // Use custom or default to $ if empty
- // For custom symbols, try to derive currency code or default to USD
- currencyCode = 'USD'; // Default for custom symbols
- } else {
- currencySymbol = currencySymbolSelect.value;
- // Find the currency code for the selected symbol
- const selectedCurrency = globalCurrenciesData.find(currency => currency.symbol === currencySymbol);
- if (selectedCurrency) {
- currencyCode = selectedCurrency.code;
- }
- }
- }
- preferencesToSave.currency_symbol = currencySymbol;
-
- // Handle currency position
- let currencyPosition = 'left'; // Default
- if (currencyPositionSelect) {
- currencyPosition = currencyPositionSelect.value;
- }
- preferencesToSave.currency_position = currencyPosition;
- // --- End data preparation ---
-
- // +++ ADDED DEBUG LOGGING +++
- console.log(`[SavePrefs Debug] Currency Select Value: ${currencySymbolSelect ? currencySymbolSelect.value : 'N/A'}`);
- console.log(`[SavePrefs Debug] Custom Input Value: ${currencySymbolCustom ? currencySymbolCustom.value : 'N/A'}`);
- console.log(`[SavePrefs Debug] Final currencySymbol value determined: ${currencySymbol}`);
- console.log(`[SavePrefs Debug] Final currencyCode value determined: ${currencyCode}`);
- console.log(`[SavePrefs Debug] Currency Position Value: ${currencyPosition}`);
- console.log(`[SavePrefs Debug] Theme being saved: ${preferencesToSave.theme} (from isDark: ${isDark})`);
- console.log(`[SavePrefs Debug] Language being saved: ${preferencesToSave.preferred_language}`);
- // +++ END DEBUG LOGGING +++
-
- // Apply the theme to the UI (this updates localStorage too)
- setTheme(isDark);
- console.log(`Saved dark mode: ${isDark}`);
-
- // Save simple preferences to localStorage immediately
- localStorage.setItem('dateFormat', preferencesToSave.date_format); // Added
- localStorage.setItem(`${prefix}defaultView`, preferencesToSave.default_view);
- localStorage.setItem(`${prefix}currencySymbol`, preferencesToSave.currency_symbol);
- localStorage.setItem(`${prefix}currencyCode`, currencyCode); // Save currency code
- localStorage.setItem(`${prefix}currencyPosition`, preferencesToSave.currency_position);
- localStorage.setItem(`${prefix}expiringSoonDays`, preferencesToSave.expiring_soon_days);
- localStorage.setItem(`${prefix}paperlessViewInApp`, preferencesToSave.paperless_view_in_app);
- localStorage.setItem('preferred_language', preferencesToSave.preferred_language); // Save language preference
-
- console.log('Preferences saved to localStorage (prefix:', prefix, '):', preferencesToSave);
- console.log(`Value of dateFormat in localStorage: ${localStorage.getItem('dateFormat')}`);
-
- // Try saving to API
- if (window.auth && window.auth.isAuthenticated()) {
- try {
- showLoading();
- const token = window.auth.getToken();
- console.log('Saving preferences with token:', token ? 'present' : 'missing');
- const response = await fetch('/api/auth/preferences', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(preferencesToSave)
- });
-
- hideLoading();
- if (response.ok) {
- showToast('Preferences saved successfully.', 'success');
- console.log('Preferences successfully saved to API.');
-
- // If language was changed, trigger the actual language change
- if (preferencesToSave.preferred_language && window.i18n?.changeLanguage) {
- const currentLang = window.i18n.getCurrentLanguage ? window.i18n.getCurrentLanguage() : 'en';
- if (preferencesToSave.preferred_language !== currentLang) {
- console.log(`Language changed from ${currentLang} to ${preferencesToSave.preferred_language}, triggering page translation`);
- try {
- await window.i18n.changeLanguage(preferencesToSave.preferred_language);
- // Reload page after a short delay to apply all translations
- setTimeout(() => {
- window.location.reload();
- }, 1000);
- } catch (error) {
- console.error('Failed to change language after saving preferences:', error);
- showToast('Failed to change language. Please try again.', 'error');
- }
- }
- } else if (preferencesToSave.preferred_language) {
- console.warn('i18n changeLanguage function not available when saving preferences');
- showToast('Language system not ready. Settings saved but language not changed. Please refresh and try again.', 'warning');
- }
- } else {
- console.error('Preferences save failed. Response status:', response.status);
- console.error('Response headers:', Object.fromEntries(response.headers.entries()));
- const errorData = await response.json().catch((e) => {
- console.error('Failed to parse error response as JSON:', e);
- return {};
- });
- console.error('Error response data:', errorData);
- throw new Error(errorData.message || `Failed to save preferences to API: ${response.status}`);
- }
- } catch (error) {
- hideLoading();
- console.error('Error saving preferences to API:', error);
- showToast(`Preferences saved locally, but failed to sync with server: ${error.message}`, 'warning');
- }
- } else {
- // No auth, just show local save success
- showToast('Preferences saved locally.', 'success');
- }
-}
-
-/**
- * Change user password
- */
-async function changePassword() {
- // Validate form
- if (!currentPasswordInput.value || !newPasswordInput.value || !confirmPasswordInput.value) {
- showToast('Please fill in all password fields', 'error');
- return;
- }
-
- if (newPasswordInput.value !== confirmPasswordInput.value) {
- showToast('New passwords do not match', 'error');
- return;
- }
-
- // Validate password strength
- if (newPasswordInput.value.length < 8) {
- showToast('Password must be at least 8 characters long', 'error');
- return;
- }
-
- showLoading();
-
- try {
- const response = await fetch('/api/auth/password/change', {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- current_password: currentPasswordInput.value,
- new_password: newPasswordInput.value
- })
- });
-
- if (response.ok) {
- // Reset form and hide it
- resetPasswordForm();
- passwordChangeForm.style.display = 'none';
- changePasswordBtn.style.display = 'block';
-
- // Show success modal
- openModal(passwordSuccessModal);
- } else {
- // Handle error
- const errorData = await response.json().catch(() => ({ message: 'Failed to parse error response' }));
- throw new Error(errorData.message || 'Failed to change password');
- }
- } catch (error) {
- console.error('Error changing password:', error);
- showToast(`Failed to change password: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Delete user account
- */
-async function deleteAccount() {
- if (deleteConfirmInput.value !== 'DELETE') {
- showToast('Please type DELETE to confirm', 'error');
- return;
- }
-
- showLoading();
-
- try {
- const response = await fetch('/api/auth/account', {
- method: 'DELETE',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
- }
- });
-
- if (response.ok) {
- // Clear auth data
- if (window.auth.logout) {
- window.auth.logout();
- } else {
- localStorage.removeItem('auth_token');
- localStorage.removeItem('user_info');
- }
-
- // Show success message
- showToast('Account deleted successfully', 'success');
-
- // Redirect to home page after a short delay
- setTimeout(() => {
- window.location.href = 'index.html';
- }, 2000);
- } else {
- // Handle error - show the actual error message from the API
- let errorMessage = 'Failed to delete account';
- try {
- const errorData = await response.json();
- errorMessage = errorData.message || errorMessage;
- } catch (parseError) {
- console.warn('Could not parse error response:', parseError);
- }
-
- console.error('API error response:', errorMessage);
- showToast(errorMessage, 'error');
- }
- } catch (error) {
- console.error('Network error deleting account:', error);
- // Only show offline message for actual network errors
- if (error.name === 'TypeError' && error.message.includes('fetch')) {
- showToast('Account cannot be deleted in offline mode', 'warning');
- } else {
- showToast('Failed to delete account. Please try again.', 'error');
- }
- } finally {
- hideLoading();
-
- // Close modal
- deleteAccountModal.style.display = 'none';
-
- // Reset delete confirm input
- deleteConfirmInput.value = '';
- confirmDeleteAccountBtn.disabled = true;
- }
-}
-
-/**
- * Show loading spinner
- */
-function showLoading() {
- loadingContainer.style.display = 'flex';
-}
-
-/**
- * Hide loading spinner
- */
-function hideLoading() {
- loadingContainer.style.display = 'none';
-}
-
-/**
- * Show a toast notification
- * @param {string} message - The message to display
- * @param {string} type - The type of toast (info, success, error, warning)
- * @param {number} duration - Duration in milliseconds, 0 for no auto-hide
- * @returns {HTMLElement} - The toast element
- */
-function showToast(message, type = 'info', duration = 5000) {
- const toast = document.createElement('div');
- toast.className = `toast toast-${type}`;
-
- const icon = document.createElement('i');
- switch (type) {
- case 'success':
- icon.className = 'fas fa-check-circle';
- break;
- case 'error':
- icon.className = 'fas fa-exclamation-circle';
- break;
- case 'warning':
- icon.className = 'fas fa-exclamation-triangle';
- break;
- default:
- icon.className = 'fas fa-info-circle';
- }
-
- const messageSpan = document.createElement('span');
- messageSpan.textContent = message;
-
- toast.appendChild(icon);
- toast.appendChild(messageSpan);
-
- toastContainer.appendChild(toast);
-
- // Add a method to remove the toast
- toast.remove = function() {
- toast.classList.add('toast-fade-out');
- setTimeout(() => {
- if (toast.parentNode) {
- toast.parentNode.removeChild(toast);
- }
- }, 300);
- };
-
- // Auto-hide toast after specified duration (if not 0)
- if (duration > 0) {
- setTimeout(() => {
- toast.remove();
- }, duration);
- }
-
- return toast;
-}
-
-/**
- * Load users for admin
- */
-async function loadUsers() {
- // Exit if usersTableBody doesn't exist
- if (!usersTableBody) {
- console.log('usersTableBody element not found, skipping loadUsers');
- return;
- }
-
- showLoading();
-
- try {
- const response = await fetch('/api/admin/users', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
- }
- });
-
- if (response.ok) {
- const users = await response.json();
-
- // DEBUG: Check users data
- console.log('DEBUG: Users data from API:', users);
- users.forEach((user, index) => {
- console.log(`DEBUG: User ${index} (${user.username}):`, {
- id: user.id,
- is_owner: user.is_owner,
- is_admin: user.is_admin
- });
- });
-
- // Clear table
- usersTableBody.innerHTML = '';
-
- // Add users to table
- users.forEach(user => {
- const row = document.createElement('tr');
- row.style.borderBottom = '1px solid var(--border-color)';
- row.style.transition = 'background-color 0.2s ease';
-
- // Add hover effect
- row.addEventListener('mouseenter', () => {
- row.style.backgroundColor = 'var(--hover-bg, rgba(0,0,0,0.05))';
- });
- row.addEventListener('mouseleave', () => {
- row.style.backgroundColor = 'transparent';
- });
-
- // ID
- const idCell = document.createElement('td');
- idCell.textContent = user.id;
- idCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-weight: 500;';
- row.appendChild(idCell);
-
- // Username with crown
- const usernameCell = document.createElement('td');
- const crownIcon = user.is_owner ? ' <i class="fas fa-crown" title="Application Owner" style="color: #f39c12; margin-left: 5px;"></i>' : '';
- console.log(`DEBUG: User ${user.username} (ID: ${user.id}) - is_owner: ${user.is_owner}, adding crown: ${!!user.is_owner}`);
- usernameCell.innerHTML = user.username + crownIcon;
- usernameCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-weight: 500;';
- row.appendChild(usernameCell);
-
- // Email
- const emailCell = document.createElement('td');
- emailCell.textContent = user.email;
- emailCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color); font-size: 0.9em;';
- row.appendChild(emailCell);
-
- // Name
- const nameCell = document.createElement('td');
- const fullName = `${user.first_name || ''} ${user.last_name || ''}`.trim();
- nameCell.textContent = fullName || '-';
- nameCell.style.cssText = 'padding: 12px 8px; color: var(--text-color); border-right: 1px solid var(--border-color);';
- row.appendChild(nameCell);
-
- // Admin
- const adminCell = document.createElement('td');
- const adminBadge = document.createElement('span');
- adminBadge.className = `badge ${user.is_admin ? 'badge-success' : 'badge-secondary'}`;
- adminBadge.textContent = user.is_admin ? 'Yes' : 'No';
- adminBadge.style.cssText = 'padding: 4px 8px; border-radius: 12px; font-size: 0.75em; font-weight: 600;';
- adminCell.appendChild(adminBadge);
- adminCell.style.cssText = 'padding: 12px 8px; text-align: center; border-right: 1px solid var(--border-color);';
- row.appendChild(adminCell);
-
- // Active Status
- const statusCell = document.createElement('td');
- const statusBadge = document.createElement('span');
- statusBadge.className = `badge ${user.is_active ? 'badge-success' : 'badge-danger'}`;
- statusBadge.textContent = user.is_active ? 'Yes' : 'No';
- statusBadge.style.cssText = 'padding: 4px 8px; border-radius: 12px; font-size: 0.75em; font-weight: 600;';
- statusCell.appendChild(statusBadge);
- statusCell.style.cssText = 'padding: 12px 8px; text-align: center; border-right: 1px solid var(--border-color);';
- row.appendChild(statusCell);
-
- // Actions
- const actionsCell = document.createElement('td');
- actionsCell.style.cssText = 'padding: 12px 8px; text-align: center;';
-
- // Create button container for better spacing
- const buttonContainer = document.createElement('div');
- buttonContainer.style.cssText = 'display: flex; gap: 6px; justify-content: center; align-items: center;';
-
- // Edit button
- const editBtn = document.createElement('button');
- editBtn.className = 'btn btn-sm';
- editBtn.innerHTML = '<i class="fas fa-edit"></i>';
- editBtn.title = 'Edit User';
- editBtn.style.cssText = `
- padding: 8px 10px;
- border-radius: 6px;
- border: 1px solid var(--primary-color, #007bff);
- background-color: transparent;
- color: var(--primary-color, #007bff);
- transition: all 0.2s ease;
- cursor: pointer;
- min-width: 36px;
- height: 36px;
- display: flex;
- align-items: center;
- justify-content: center;
- `;
-
- // Edit button hover effects
- editBtn.addEventListener('mouseenter', () => {
- if (!editBtn.disabled) {
- editBtn.style.backgroundColor = 'var(--primary-color, #007bff)';
- editBtn.style.color = 'white';
- editBtn.style.transform = 'translateY(-1px)';
- editBtn.style.boxShadow = '0 2px 4px rgba(0,123,255,0.3)';
- }
- });
- editBtn.addEventListener('mouseleave', () => {
- if (!editBtn.disabled) {
- editBtn.style.backgroundColor = 'transparent';
- editBtn.style.color = 'var(--primary-color, #007bff)';
- editBtn.style.transform = 'translateY(0)';
- editBtn.style.boxShadow = 'none';
- }
- });
- editBtn.addEventListener('click', () => openEditUserModal(user));
-
- // Delete button
- const deleteBtn = document.createElement('button');
- deleteBtn.className = 'btn btn-sm';
- deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i>';
- deleteBtn.title = 'Delete User';
- deleteBtn.style.cssText = `
- padding: 8px 10px;
- border-radius: 6px;
- border: 1px solid var(--danger-color, #dc3545);
- background-color: transparent;
- color: var(--danger-color, #dc3545);
- transition: all 0.2s ease;
- cursor: pointer;
- min-width: 36px;
- height: 36px;
- display: flex;
- align-items: center;
- justify-content: center;
- `;
-
- // Delete button hover effects
- deleteBtn.addEventListener('mouseenter', () => {
- if (!deleteBtn.disabled) {
- deleteBtn.style.backgroundColor = 'var(--danger-color, #dc3545)';
- deleteBtn.style.color = 'white';
- deleteBtn.style.transform = 'translateY(-1px)';
- deleteBtn.style.boxShadow = '0 2px 4px rgba(220,53,69,0.3)';
- }
- });
- deleteBtn.addEventListener('mouseleave', () => {
- if (!deleteBtn.disabled) {
- deleteBtn.style.backgroundColor = 'transparent';
- deleteBtn.style.color = 'var(--danger-color, #dc3545)';
- deleteBtn.style.transform = 'translateY(0)';
- deleteBtn.style.boxShadow = 'none';
- }
- });
-
- // Add multiple event handlers for redundancy
- deleteBtn.addEventListener('click', (event) => {
- event.preventDefault();
- event.stopPropagation();
- console.log('Delete button clicked for user:', user);
- openDeleteUserModal(user);
- });
-
- // Also set onclick property
- deleteBtn.onclick = function(event) {
- event.preventDefault();
- event.stopPropagation();
- console.log('Delete button onclick property triggered for user:', user);
- openDeleteUserModal(user);
- return false;
- };
-
- // Don't allow editing or deleting self, and disable actions for the owner
- const currentUser = window.auth.getCurrentUser();
- const isOwner = user.is_owner;
- const isCurrentUser = (user.id === currentUser.id);
-
- console.log(`DEBUG: Button logic for ${user.username} - isOwner: ${isOwner}, isCurrentUser: ${isCurrentUser}, currentUser.id: ${currentUser?.id}, user.id: ${user.id}`);
-
- if (isOwner || isCurrentUser) {
- editBtn.disabled = true;
- deleteBtn.disabled = true;
- editBtn.title = isOwner ? 'Cannot edit the application owner' : 'Cannot edit yourself';
- deleteBtn.title = isOwner ? 'Cannot delete the application owner' : 'Cannot delete yourself';
-
- // Enhanced disabled styling
- editBtn.style.opacity = '0.4';
- editBtn.style.cursor = 'not-allowed';
- editBtn.style.border = '1px solid var(--text-muted, #6c757d)';
- editBtn.style.color = 'var(--text-muted, #6c757d)';
-
- deleteBtn.style.opacity = '0.4';
- deleteBtn.style.cursor = 'not-allowed';
- deleteBtn.style.border = '1px solid var(--text-muted, #6c757d)';
- deleteBtn.style.color = 'var(--text-muted, #6c757d)';
-
- console.log('DEBUG: Disabled edit/delete for', isOwner ? 'owner' : 'current user', ':', user.id);
- } else {
- console.log('DEBUG: Buttons enabled for user:', user.id);
- }
-
- // Add buttons to container
- buttonContainer.appendChild(editBtn);
- buttonContainer.appendChild(deleteBtn);
-
- // Add container to cell
- actionsCell.appendChild(buttonContainer);
- row.appendChild(actionsCell);
-
- usersTableBody.appendChild(row);
- });
-
- console.log('Users loaded successfully:', users.length);
-
- // Set up ownership management after loading users
- setupOwnershipManagement(users);
- } else {
- console.error('Failed to load users:', response.status);
- showToast('Failed to load users', 'error');
- }
- } catch (error) {
- console.error('Error loading users:', error);
- showToast('Error loading users', 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Open edit user modal
- * @param {Object} user - The user to edit
- */
-function openEditUserModal(user) {
- editUserId.value = user.id;
- editUsername.value = user.username;
- editEmail.value = user.email;
- editUserActive.checked = user.is_active;
- editUserAdmin.checked = user.is_admin;
-
- openModal(editUserModal);
-}
-
-/**
- * Save user changes
- */
-async function saveUserChanges() {
- const userId = editUserId.value;
-
- if (!userId) {
- showToast('User ID is missing', 'error');
- return;
- }
-
- showLoading();
-
- try {
- const response = await fetch(`/api/admin/users/${userId}`, {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- is_active: editUserActive.checked,
- is_admin: editUserAdmin.checked
- })
- });
-
- if (response.ok) {
- showToast('User updated successfully', 'success');
- closeAllModals();
- loadUsers();
- } else {
- const errorData = await response.json();
- showToast(errorData.message || 'Failed to update user', 'error');
- }
- } catch (error) {
- console.error('Error updating user:', error);
- showToast('Failed to update user. Please try again.', 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Open delete user modal
- * @param {Object} user - User object
- */
-function openDeleteUserModal(user) {
- console.log('Opening delete modal for user:', user);
-
- // Store the user ID in a global variable for easier access
- window.currentDeleteUserId = user.id;
- console.log('Set global currentDeleteUserId to:', user.id);
-
- // Set the user ID in the form
- const deleteUserIdField = document.getElementById('deleteUserId');
- if (deleteUserIdField) {
- deleteUserIdField.value = user.id;
- console.log('Set deleteUserId field to:', user.id);
- } else {
- console.error('deleteUserId field not found in the DOM');
- }
-
- // Display user ID for debugging
- const displayUserIdField = document.getElementById('displayUserId');
- if (displayUserIdField) {
- displayUserIdField.textContent = user.id;
- console.log('Set displayUserId field to:', user.id);
- }
-
- // Also set in editUserId for backward compatibility
- if (editUserId) {
- editUserId.value = user.id;
- console.log('Set editUserId.value to:', user.id);
- }
-
- // Set the username in the modal
- const deleteUserNameElement = document.getElementById('deleteUserName');
- if (deleteUserNameElement) {
- deleteUserNameElement.textContent = user.username;
- console.log('Set deleteUserName to:', user.username);
- } else {
- console.error('deleteUserName element not found in the DOM');
- }
-
- // Make sure the modal is visible
- const deleteUserModal = document.getElementById('deleteUserModal');
- if (deleteUserModal) {
- // First ensure all modals are closed
- closeAllModals();
-
- // Then open this modal
- deleteUserModal.style.display = 'flex';
- console.log('Delete user modal opened');
-
- // Ensure the delete button has the correct click handler
- const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');
- if (confirmDeleteUserBtn) {
- // Remove existing event listeners by cloning
- const newBtn = confirmDeleteUserBtn.cloneNode(true);
- confirmDeleteUserBtn.parentNode.replaceChild(newBtn, confirmDeleteUserBtn);
-
- // Add the click event listener
- newBtn.addEventListener('click', function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Delete button clicked for user ID:', user.id);
- deleteUser();
- return false;
- });
-
- // Also set the direct onclick attribute as a simple function call
- newBtn.setAttribute('onclick', 'console.log("Direct onclick attribute clicked"); deleteUser(); return false;');
- console.log('Added click event listener to delete button');
-
- // Add a direct click handler
- newBtn.onclick = function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Direct onclick property handler clicked for user ID:', user.id);
- deleteUser();
- return false;
- };
- } else {
- console.error('confirmDeleteUserBtn not found in the DOM');
- }
-
- // Set up the direct delete link
- const directDeleteLink = document.getElementById('directDeleteLink');
- if (directDeleteLink) {
- directDeleteLink.onclick = function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Direct delete link clicked for user ID:', user.id);
- deleteUser();
- return false;
- };
- console.log('Added onclick handler to direct delete link');
- }
-
- // Set up the direct API link
- const directAPILink = document.getElementById('directAPILink');
- if (directAPILink) {
- directAPILink.onclick = function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Direct API link clicked for user ID:', user.id);
- directDeleteUserAPI(user.id);
- return false;
- };
- console.log('Added onclick handler to direct API link');
- }
-
- // Also set up form submit handler
- const deleteUserForm = document.getElementById('deleteUserForm');
- if (deleteUserForm) {
- deleteUserForm.onsubmit = function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Delete user form submitted for user ID:', user.id);
- deleteUser();
- return false;
- };
- console.log('Added onsubmit handler to delete user form');
- }
-
- // Add a direct click handler to the modal for event delegation
- deleteUserModal.addEventListener('click', function(e) {
- if (e.target && e.target.id === 'confirmDeleteUserBtn') {
- e.preventDefault();
- e.stopPropagation();
- console.log('Delete button clicked through modal event delegation for user ID:', user.id);
- deleteUser();
- return false;
- }
- });
- } else {
- console.error('deleteUserModal not found in the DOM');
- }
-}
-
-/**
- * Delete user
- */
-function deleteUser() {
- console.log('=== DELETE USER FUNCTION STARTED ===');
- console.log('Function caller:', arguments.callee.caller ? arguments.callee.caller.name : 'unknown');
-
- try {
- // Get the user ID from various possible sources
- const userId = window.currentDeleteUserId ||
- (document.getElementById('deleteUserId') ? document.getElementById('deleteUserId').value : null) ||
- (document.getElementById('editUserId') ? document.getElementById('editUserId').value : null) ||
- (document.getElementById('displayUserId') ? document.getElementById('displayUserId').textContent : null);
-
- console.log('Final User ID to delete:', userId);
-
- if (!userId) {
- showToast('User ID is missing', 'error');
- console.error('Delete user failed: User ID is missing');
- return;
- }
-
- console.log('Starting user deletion process for ID:', userId);
- showLoading();
-
- // Use our improved deletion function
- superEmergencyDelete(userId)
- .then(success => {
- if (success) {
- console.log('User deletion successful');
- showToast('User deleted successfully', 'success');
- closeAllModals();
- loadUsers(); // Refresh the user list
-
- // Refresh the users list if it's currently displayed
- const usersModal = document.querySelector('div[style*="z-index: 10000"]');
- if (usersModal) {
- document.body.removeChild(usersModal);
- showUsersList();
- }
- } else {
- console.error('User deletion failed');
- showToast('Failed to delete user. Check console for details.', 'error');
- }
- hideLoading();
- })
- .catch(error => {
- console.error('Error during user deletion:', error);
- showToast(window.t('messages.error_during_user_deletion', { error: error.message }), 'error');
- hideLoading();
-
- // Try the direct API call as a fallback
- if (confirm('Would you like to try a direct API call to delete the user?')) {
- const directToast = showToast(`Trying direct API call for user ID ${userId}...`, 'info', 0);
-
- directDeleteUserAPI(userId)
- .then(directSuccess => {
- directToast.remove();
-
- if (directSuccess) {
- showToast(`User ID ${userId} deleted successfully with direct API call!`, 'success');
-
- // Refresh the users list if it's currently displayed
- const usersModal = document.querySelector('div[style*="z-index: 10000"]');
- if (usersModal) {
- document.body.removeChild(usersModal);
- setTimeout(() => {
- showUsersList();
- }, 500);
- }
- } else {
- showToast(window.t('messages.failed_to_delete_user_with_direct_api_call', { username: user.username }), 'error');
- }
- })
- .catch(error => {
- directToast.remove();
- console.error('Error with direct API call:', error);
- showToast('Error with direct API call: ' + error.message, 'error');
- });
- }
- })
- .catch(error => {
- console.error('Error checking if user exists:', error);
- showToast('Error checking if user exists: ' + error.message, 'error');
- });
- } catch (error) {
- console.error('Error in deleteUser function:', error);
- console.error('Error details:', error.message, error.stack);
- showToast('Failed to delete user. Please try again.', 'error');
- hideLoading();
- }
-
- console.log('=== DELETE USER FUNCTION COMPLETED ===');
-}
-
-/**
- * Set up ownership management functionality
- * @param {Array} users - List of all users
- */
-function setupOwnershipManagement(users) {
- const currentUser = window.auth.getCurrentUser();
- const ownershipCard = document.getElementById('ownershipCard');
- const newOwnerSelect = document.getElementById('newOwnerSelect');
- const transferOwnershipBtn = document.getElementById('transferOwnershipBtn');
-
- // DEBUG: Check ownership management setup
- console.log('DEBUG: setupOwnershipManagement called');
- console.log('DEBUG: currentUser:', currentUser);
- console.log('DEBUG: currentUser.is_owner:', currentUser ? currentUser.is_owner : 'no currentUser');
- console.log('DEBUG: ownershipCard element:', ownershipCard);
-
- if (!currentUser || !currentUser.is_owner) {
- // Hide ownership section if user is not the owner
- console.log('DEBUG: Hiding ownership section - user is not owner');
- const ownershipSection = document.getElementById('ownershipSection');
- if (ownershipSection) {
- ownershipSection.style.display = 'none';
- }
- return;
- }
-
- // Show ownership section for the owner
- const ownershipSection = document.getElementById('ownershipSection');
- if (ownershipSection) {
- ownershipSection.style.display = 'block';
- }
-
- // Populate the select dropdown with admin users (excluding current owner)
- if (newOwnerSelect) {
- newOwnerSelect.innerHTML = '<option value="">Select an admin user...</option>';
-
- users.forEach(user => {
- if (user.is_admin && user.id !== currentUser.id && user.is_active && !user.is_owner) {
- const option = document.createElement('option');
- option.value = user.id;
- option.textContent = `${user.username} (${user.email})`;
- newOwnerSelect.appendChild(option);
- }
- });
-
- // Enable/disable transfer button based on selection
- newOwnerSelect.addEventListener('change', function() {
- if (transferOwnershipBtn) {
- transferOwnershipBtn.disabled = !this.value;
- }
- });
- }
-
- // Set up transfer button click handler
- if (transferOwnershipBtn) {
- transferOwnershipBtn.addEventListener('click', function() {
- const selectedUserId = newOwnerSelect.value;
- if (!selectedUserId) {
- showToast('Please select a user to transfer ownership to', 'error');
- return;
- }
-
- const selectedUser = users.find(u => u.id == selectedUserId);
- if (selectedUser) {
- openTransferOwnershipModal(selectedUser);
- }
- });
- }
-}
-
-/**
- * Open the transfer ownership confirmation modal
- * @param {Object} targetUser - The user to transfer ownership to
- */
-function openTransferOwnershipModal(targetUser) {
- const modal = document.getElementById('transferOwnershipModal');
- const targetUsernameSpan = document.getElementById('transferTargetUsername');
- const confirmInput = document.getElementById('transferConfirmInput');
- const confirmBtn = document.getElementById('confirmTransferOwnershipBtn');
-
- if (!modal || !targetUsernameSpan || !confirmInput || !confirmBtn) {
- showToast('Error: Transfer ownership modal elements not found', 'error');
- return;
- }
-
- // Set target username
- targetUsernameSpan.textContent = targetUser.username;
-
- // Clear and set up confirm input
- confirmInput.value = '';
- confirmInput.addEventListener('input', function() {
- confirmBtn.disabled = this.value.toUpperCase() !== 'TRANSFER';
- });
-
- // Set up confirm button
- confirmBtn.disabled = true;
- confirmBtn.onclick = function() {
- if (confirmInput.value.toUpperCase() === 'TRANSFER') {
- performOwnershipTransfer(targetUser.id);
- }
- };
-
- // Show modal
- modal.style.display = 'flex';
-}
-
-/**
- * Perform the actual ownership transfer
- * @param {number} newOwnerId - ID of the user to transfer ownership to
- */
-async function performOwnershipTransfer(newOwnerId) {
- const modal = document.getElementById('transferOwnershipModal');
-
- try {
- showLoading();
-
- const response = await fetch('/api/admin/transfer-ownership', {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- new_owner_id: newOwnerId
- })
- });
-
- if (response.ok) {
- showToast('Ownership transferred successfully! Refreshing page...', 'success');
-
- // Close modal
- if (modal) {
- modal.style.display = 'none';
- }
-
- // Refresh the page after a short delay to allow the user to see the success message
- setTimeout(() => {
- window.location.reload();
- }, 2000);
- } else {
- const errorData = await response.json();
- showToast(errorData.message || 'Failed to transfer ownership', 'error');
- }
- } catch (error) {
- console.error('Error transferring ownership:', error);
- showToast('Failed to transfer ownership. Please try again.', 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Super emergency delete function for user deletion
- * @param {string|number} userId - The user ID or username to delete
- * @returns {Promise<boolean>} - Promise that resolves to true if deletion was successful, false otherwise
- */
-function superEmergencyDelete(userId) {
- console.log('=== SUPER EMERGENCY DELETE STARTED ===');
- console.log('User ID or username to delete:', userId);
-
- return new Promise((resolve, reject) => {
- if (!userId) {
- console.error('No user ID provided');
- reject(new Error('No user ID provided'));
- return;
- }
-
- // Check if the input is a username rather than a numeric ID
- if (isNaN(userId)) {
- console.log('Input appears to be a username, not a numeric ID');
- // Try to find the user ID by username using the Promise-based function
- findUserIdByUsernameAsync(userId)
- .then(numericId => {
- if (numericId) {
- console.log(`Found numeric ID ${numericId} for username ${userId}`);
- // Call this function again with the numeric ID
- return superEmergencyDelete(numericId);
- } else {
- throw new Error(`Could not find a user with username "${userId}"`);
- }
- })
- .then(resolve)
- .catch(reject);
- return;
- }
-
- console.log('Proceeding with numeric user ID:', userId);
-
- // Get the token
- const token = localStorage.getItem('auth_token');
- if (!token) {
- console.error('Authentication token is missing');
- reject(new Error('Authentication token is missing'));
- return;
- }
-
- // Create a new XMLHttpRequest
- const xhr = new XMLHttpRequest();
- xhr.open('DELETE', `/api/admin/users/${userId}`, true);
-
- // Set headers
- xhr.setRequestHeader('Authorization', `Bearer ${token}`);
- xhr.setRequestHeader('Content-Type', 'application/json');
- xhr.setRequestHeader('Accept', 'application/json');
-
- // Set up event handlers
- xhr.onload = function() {
- console.log('XHR status:', xhr.status);
- console.log('XHR response text:', xhr.responseText);
-
- if (xhr.status >= 200 && xhr.status < 300) {
- console.log('User deletion successful');
- resolve(true);
- } else {
- console.error('User deletion failed with status:', xhr.status);
- let errorMessage = 'Unknown error';
- try {
- const response = JSON.parse(xhr.responseText);
- errorMessage = response.message || response.error || 'Unknown error';
- } catch (e) {
- errorMessage = xhr.responseText || 'Unknown error';
- }
- console.error('Error message:', errorMessage);
- resolve(false); // Resolve with false instead of rejecting to handle the error in a controlled way
- }
- };
-
- xhr.onerror = function() {
- console.error('Network error during user deletion');
- reject(new Error('Network error during user deletion'));
- };
-
- xhr.ontimeout = function() {
- console.error('Request timeout during user deletion');
- reject(new Error('Request timeout during user deletion'));
- };
-
- // Send the request
- xhr.send();
- console.log('Delete request sent for user ID:', userId);
- });
-}
-
-/**
- * Find a user's numeric ID by their username
- * @param {string} username - The username to look up
- * @param {function} callback - Callback function that receives the numeric ID or null if not found
- */
-function findUserIdByUsername(username, callback) {
- console.log('=== FIND USER ID BY USERNAME STARTED ===');
- console.log('Looking up user ID for username:', username);
-
- // Get the token
- const token = localStorage.getItem('auth_token');
- if (!token) {
- console.error('Authentication token is missing');
- callback(null);
- return;
- }
-
- // Fetch the list of users
- fetch('/api/admin/users', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json',
- 'Accept': 'application/json'
- }
- })
- .then(response => {
- if (!response.ok) {
- console.error('Failed to fetch users list:', response.status);
- callback(null);
- return null;
- }
- return response.json();
- })
- .then(users => {
- if (!users) {
- callback(null);
- return;
- }
-
- console.log('Fetched users list:', users);
-
- // Find the user with the matching username
- const user = users.find(u => u.username === username);
-
- if (user) {
- console.log('Found user:', user);
- callback(user.id);
- } else {
- console.error('User not found with username:', username);
- callback(null);
- }
- })
- .catch(error => {
- console.error('Error fetching users:', error);
- callback(null);
- });
-
- console.log('=== FIND USER ID BY USERNAME COMPLETED ===');
-}
-
-/**
- * Check admin permissions
- */
-function checkAdminPermissions() {
- console.log('=== CHECK ADMIN PERMISSIONS STARTED ===');
-
- // Get the token
- const token = localStorage.getItem('auth_token');
- if (!token) {
- alert('Error: Authentication token is missing');
- return;
- }
-
- // Get the current user info
- const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
- console.log('Current user info:', userInfo);
-
- // Check if the user is an admin
- if (userInfo.is_admin) {
- console.log('User is an admin');
- alert('You are an admin user');
- } else {
- console.log('User is not an admin');
- alert('You are not an admin user');
- }
-
- // Make a request to the admin endpoint to verify permissions
- fetch('/api/admin/users', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- })
- .then(response => {
- console.log('Admin check response status:', response.status);
-
- if (response.ok) {
- console.log('Admin endpoint access successful');
- alert('You have access to the admin endpoint');
- } else {
- console.error('Admin endpoint access failed');
- alert('You do not have access to the admin endpoint');
- }
-
- return response.text().catch(() => '');
- })
- .then(text => {
- console.log('Admin check response text:', text);
- })
- .catch(error => {
- console.error('Admin check error:', error);
- alert('Error checking admin permissions: ' + error.message);
- });
-
- console.log('=== CHECK ADMIN PERMISSIONS COMPLETED ===');
-}
-
-/**
- * Show a list of users in the system
- */
-function showUsersList() {
- console.log('=== SHOW USERS LIST STARTED ===');
-
- // Get the token
- const token = localStorage.getItem('auth_token');
- if (!token) {
- alert('Error: Authentication token is missing');
- return;
- }
-
- // Fetch the list of users
- fetch('/api/admin/users', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- })
- .then(response => {
- if (!response.ok) {
- console.error('Failed to fetch users list:', response.status);
- alert('Failed to fetch users list. Status: ' + response.status);
- return null;
- }
- return response.json();
- })
- .then(users => {
- if (!users) return;
-
- console.log('Fetched users list:', users);
-
- // Check if dark mode is enabled
- const isDarkMode = document.body.classList.contains('dark-mode');
-
- // Set colors based on theme
- const backgroundColor = isDarkMode ? '#333' : 'white';
- const textColor = isDarkMode ? '#fff' : '#000';
- const borderColor = isDarkMode ? '#555' : '#ddd';
-
- // Create a modal to display the users
- const modal = document.createElement('div');
- modal.style.position = 'fixed';
- modal.style.top = '0';
- modal.style.left = '0';
- modal.style.width = '100%';
- modal.style.height = '100%';
- modal.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
- modal.style.display = 'flex';
- modal.style.justifyContent = 'center';
- modal.style.alignItems = 'center';
- modal.style.zIndex = '10000';
-
- // Create the modal content
- const modalContent = document.createElement('div');
- modalContent.style.backgroundColor = backgroundColor;
- modalContent.style.color = textColor;
- modalContent.style.padding = '20px';
- modalContent.style.borderRadius = '5px';
- modalContent.style.maxWidth = '80%';
- modalContent.style.maxHeight = '80%';
- modalContent.style.overflow = 'auto';
-
- // Create the modal header
- const modalHeader = document.createElement('div');
- modalHeader.style.display = 'flex';
- modalHeader.style.justifyContent = 'space-between';
- modalHeader.style.alignItems = 'center';
- modalHeader.style.marginBottom = '20px';
-
- // Create the modal title
- const modalTitle = document.createElement('h3');
- modalTitle.textContent = 'Users List';
- modalTitle.style.color = textColor;
-
- // Create the close button
- const closeButton = document.createElement('button');
- closeButton.textContent = '×';
- closeButton.style.backgroundColor = 'transparent';
- closeButton.style.border = 'none';
- closeButton.style.fontSize = '24px';
- closeButton.style.cursor = 'pointer';
- closeButton.style.color = textColor;
- closeButton.addEventListener('click', function() {
- document.body.removeChild(modal);
- });
-
- // Add the title and close button to the header
- modalHeader.appendChild(modalTitle);
- modalHeader.appendChild(closeButton);
-
- // Create the table
- const table = document.createElement('table');
- table.style.width = '100%';
- table.style.borderCollapse = 'collapse';
-
- // Create the table header
- const thead = document.createElement('thead');
- const headerRow = document.createElement('tr');
-
- // Create the header cells
- const headers = ['ID', 'Username', 'Email', 'Name', 'Admin', 'Active', 'Actions'];
- headers.forEach(headerText => {
- const th = document.createElement('th');
- th.textContent = headerText;
- th.style.padding = '10px';
- th.style.textAlign = 'left';
- th.style.borderBottom = `1px solid ${borderColor}`;
- th.style.color = textColor;
- headerRow.appendChild(th);
- });
-
- thead.appendChild(headerRow);
- table.appendChild(thead);
-
- // Create the table body
- const tbody = document.createElement('tbody');
-
- // Add a row for each user
- users.forEach(user => {
- const row = document.createElement('tr');
-
- // Create cells for each property
- const idCell = document.createElement('td');
- idCell.textContent = user.id;
- idCell.style.padding = '10px';
- idCell.style.borderBottom = `1px solid ${borderColor}`;
- idCell.style.color = textColor;
-
- const usernameCell = document.createElement('td');
- usernameCell.textContent = user.username;
- usernameCell.style.padding = '10px';
- usernameCell.style.borderBottom = `1px solid ${borderColor}`;
- usernameCell.style.color = textColor;
-
- const emailCell = document.createElement('td');
- emailCell.textContent = user.email;
- emailCell.style.padding = '10px';
- emailCell.style.borderBottom = `1px solid ${borderColor}`;
- emailCell.style.color = textColor;
-
- const nameCell = document.createElement('td');
- nameCell.textContent = `${user.first_name || ''} ${user.last_name || ''}`.trim() || '-';
- nameCell.style.padding = '10px';
- nameCell.style.borderBottom = `1px solid ${borderColor}`;
- nameCell.style.color = textColor;
-
- const adminCell = document.createElement('td');
- adminCell.textContent = user.is_admin ? 'Yes' : 'No';
- adminCell.style.padding = '10px';
- adminCell.style.borderBottom = `1px solid ${borderColor}`;
- adminCell.style.color = textColor;
-
- const activeCell = document.createElement('td');
- activeCell.textContent = user.is_active ? 'Yes' : 'No';
- activeCell.style.padding = '10px';
- activeCell.style.borderBottom = `1px solid ${borderColor}`;
- activeCell.style.color = textColor;
-
- const actionsCell = document.createElement('td');
- actionsCell.style.padding = '10px';
- actionsCell.style.borderBottom = `1px solid ${borderColor}`;
-
- // Create a delete button
- const deleteButton = document.createElement('button');
- deleteButton.textContent = 'Delete';
- deleteButton.style.backgroundColor = '#dc3545';
- deleteButton.style.color = 'white';
- deleteButton.style.border = 'none';
- deleteButton.style.padding = '5px 10px';
- deleteButton.style.borderRadius = '3px';
- deleteButton.style.cursor = 'pointer';
-
- // Don't allow deleting the current user
- const currentUser = JSON.parse(localStorage.getItem('user_info') || '{}');
- if (user.id === currentUser.id) {
- deleteButton.disabled = true;
- deleteButton.style.opacity = '0.5';
- deleteButton.style.cursor = 'not-allowed';
- deleteButton.title = 'Cannot delete yourself';
- } else {
- deleteButton.addEventListener('click', function() {
- if (confirm(`Are you sure you want to delete user ${user.username} (ID: ${user.id})?`)) {
- document.body.removeChild(modal);
-
- // First check if the user still exists
- const checkingToast = showToast(`Checking if user ${user.username} still exists...`, 'info', 0);
-
- checkUserExists(user.id)
- .then(existingUser => {
- checkingToast.remove();
-
- if (!existingUser) {
- showToast(`User ${user.username} no longer exists`, 'warning');
- showUsersList(); // Refresh the list
- return;
- }
-
- // User exists, proceed with deletion
- testUserDeletion(user.id);
- })
- .catch(error => {
- checkingToast.remove();
- console.error('Error checking if user exists:', error);
- showToast(window.t('messages.error_checking_if_user_exists', { error: error.message }), 'error');
-
- // Ask if they want to try deletion anyway
- if (confirm(`Error checking if user ${user.username} exists. Try deletion anyway?`)) {
- testUserDeletion(user.id);
- } else {
- showUsersList(); // Refresh the list
- }
- });
- }
- });
- }
-
- actionsCell.appendChild(deleteButton);
-
- // Add all cells to the row
- row.appendChild(idCell);
- row.appendChild(usernameCell);
- row.appendChild(emailCell);
- row.appendChild(nameCell);
- row.appendChild(adminCell);
- row.appendChild(activeCell);
- row.appendChild(actionsCell);
-
- // Add the row to the table body
- tbody.appendChild(row);
- });
-
- table.appendChild(tbody);
-
- // Add the header and table to the modal content
- modalContent.appendChild(modalHeader);
- modalContent.appendChild(table);
-
- // Add the modal content to the modal
- modal.appendChild(modalContent);
-
- // Add the modal to the page
- document.body.appendChild(modal);
-
- console.log('Users list displayed');
- })
- .catch(error => {
- console.error('Error fetching users:', error);
- alert('Error fetching users: ' + error.message);
- });
-
- console.log('=== SHOW USERS LIST COMPLETED ===');
-}
-
-/**
- * Promise-based version of findUserIdByUsername
- * @param {string} username - The username to look up
- * @returns {Promise<number|null>} - Promise that resolves to the user ID or null if not found
- */
-function findUserIdByUsernameAsync(username) {
- return new Promise((resolve, reject) => {
- findUserIdByUsername(username, (err, userId) => {
- if (err) reject(err);
- else resolve(userId);
- });
- });
-}
-
-/**
- * Check if a user exists by ID or username
- * @param {string|number} userIdOrUsername - The user ID or username to check
- * @returns {Promise<Object|null>} - Promise that resolves to the user object if found, null otherwise
- */
-function checkUserExists(userIdOrUsername) {
- console.log('=== CHECK USER EXISTS STARTED ===');
- console.log('Checking if user exists:', userIdOrUsername);
-
- return new Promise((resolve, reject) => {
- // Get the token
- const token = localStorage.getItem('auth_token');
- if (!token) {
- console.error('Authentication token is missing');
- reject(new Error('Authentication token is missing'));
- return;
- }
-
- // Fetch the list of users
- fetch('/api/admin/users', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json',
- 'Accept': 'application/json'
- }
- })
- .then(response => {
- if (!response.ok) {
- console.error('Failed to fetch users list:', response.status);
- reject(new Error(`Failed to fetch users list: ${response.status}`));
- return null;
- }
- return response.json();
- })
- .then(users => {
- if (!users) {
- resolve(null);
- return;
- }
-
- console.log('Fetched users list for checking existence');
-
- // Check if the input is a numeric ID
- if (!isNaN(userIdOrUsername)) {
- // Convert to number for comparison
- const userId = Number(userIdOrUsername);
- const user = users.find(u => u.id === userId);
-
- if (user) {
- console.log('Found user by ID:', user);
- resolve(user);
- } else {
- console.log('User not found with ID:', userId);
- resolve(null);
- }
- } else {
- // Assume it's a username
- const user = users.find(u => u.username === userIdOrUsername);
-
- if (user) {
- console.log('Found user by username:', user);
- resolve(user);
- } else {
- console.log('User not found with username:', userIdOrUsername);
- resolve(null);
- }
- }
- })
- .catch(error => {
- console.error('Error checking if user exists:', error);
- reject(error);
- });
- });
-}
-
-/**
- * Test user deletion functionality
- * @param {string|number} userId - The user ID or username to delete
- */
-function testUserDeletion(userId) {
- console.log('=== TEST USER DELETION STARTED ===');
- console.log('Attempting to delete user:', userId);
-
- // Check if we have a valid user ID
- if (!userId) {
- console.error('No user ID provided');
- alert('Error: No user ID provided');
- return;
- }
-
- // Show a loading indicator
- const loadingToast = showToast('Checking user...', 'info', 0); // 0 means no auto-hide
-
- // First check if the user exists
- checkUserExists(userId)
- .then(user => {
- if (!user) {
- loadingToast.remove();
- showToast(`User with ID/username "${userId}" not found`, 'error');
- return;
- }
-
- // Update the loading toast
- loadingToast.remove();
- const deletingToast = showToast(`Deleting user ${user.username} (ID: ${user.id})...`, 'info', 0);
-
- // Use our improved deletion function with the numeric ID
- return superEmergencyDelete(user.id)
- .then(success => {
- // Hide the loading toast
- if (deletingToast) {
- deletingToast.remove();
- }
-
- if (success) {
- console.log('User deletion successful');
- showToast(`User ${user.username} deleted successfully!`, 'success');
-
- // Refresh the users list if it's currently displayed
- const usersModal = document.querySelector('div[style*="z-index: 10000"]');
- if (usersModal) {
- document.body.removeChild(usersModal);
- setTimeout(() => {
- showUsersList();
- }, 500);
- }
- } else {
- console.error('User deletion failed');
- showToast(`Failed to delete user ${user.username}. Check console for details.`, 'error');
-
- // Offer to try direct API call
- if (confirm(`Would you like to try a direct API call to delete user ${user.username}?`)) {
- const directToast = showToast(`Trying direct API call for user ${user.username}...`, 'info', 0);
-
- directDeleteUserAPI(user.id)
- .then(directSuccess => {
- directToast.remove();
-
- if (directSuccess) {
- showToast(`User ${user.username} deleted successfully with direct API call!`, 'success');
-
- // Refresh the users list if it's currently displayed
- const usersModal = document.querySelector('div[style*="z-index: 10000"]');
- if (usersModal) {
- document.body.removeChild(usersModal);
- setTimeout(() => {
- showUsersList();
- }, 500);
- }
- } else {
- showToast(window.t('messages.failed_to_delete_user_with_direct_api_call', { username: user.username }), 'error');
- }
- })
- .catch(error => {
- directToast.remove();
- console.error('Error with direct API call:', error);
- showToast('Error with direct API call: ' + error.message, 'error');
- });
- }
- }
- })
- .catch(error => {
- // Hide the loading toast
- if (deletingToast) {
- deletingToast.remove();
- }
-
- console.error('Error during user deletion:', error);
- showToast('Error during user deletion: ' + error.message, 'error');
- });
- })
- .catch(error => {
- loadingToast.remove();
- console.error('Error checking if user exists:', error);
- showToast('Error checking if user exists: ' + error.message, 'error');
- });
-
- console.log('=== TEST USER DELETION COMPLETED ===');
-}
-
-/**
- * Close all modals
- */
-function closeAllModals() {
- console.log('Closing all modals');
-
- // Get all modals
- const modals = document.querySelectorAll('.modal-backdrop');
-
- // Close each modal
- modals.forEach(modal => {
- console.log('Closing modal:', modal.id);
- modal.style.display = 'none';
- });
-
- // Also reset any form fields
- if (deleteConfirmInput) {
- deleteConfirmInput.value = '';
- if (confirmDeleteAccountBtn) {
- confirmDeleteAccountBtn.disabled = true;
- }
- }
-
- // Reset password form
- resetPasswordForm();
-
- console.log('All modals closed');
-}
-
-/**
- * Load site settings
- */
-async function loadSiteSettings() {
- console.log('Loading site settings...');
-
- // Enhanced debugging for element availability
- console.log('[SiteSettings Debug] DOM readiness check:');
- console.log(' - document.readyState:', document.readyState);
- console.log(' - adminSection exists:', !!document.getElementById('adminSection'));
- console.log(' - registrationEnabled exists:', !!document.getElementById('registrationEnabled'));
- console.log(' - oidcEnabled exists:', !!document.getElementById('oidcEnabled'));
- console.log(' - oidcProviderName exists:', !!document.getElementById('oidcProviderName'));
- console.log(' - oidcClientId exists:', !!document.getElementById('oidcClientId'));
-
- // Query elements locally within this function scope for population
- const registrationToggleElem = document.getElementById('registrationEnabled');
- const emailBaseUrlFieldElem = document.getElementById('emailBaseUrl');
- const globalViewToggleElem = document.getElementById('globalViewEnabled');
- const globalViewAdminOnlyToggleElem = document.getElementById('globalViewAdminOnly');
- const oidcEnabledToggleElem = document.getElementById('oidcEnabled');
- const oidcOnlyModeToggleElem = document.getElementById('oidcOnlyMode');
- const oidcProviderNameInputElem = document.getElementById('oidcProviderName');
- const oidcClientIdInputElem = document.getElementById('oidcClientId');
- const oidcClientSecretInputElem = document.getElementById('oidcClientSecret');
- const oidcIssuerUrlInputElem = document.getElementById('oidcIssuerUrl');
- const oidcScopeInputElem = document.getElementById('oidcScope');
- const oidcAdminGroupInputElem = document.getElementById('oidcAdminGroup');
-
- try {
- showLoading();
-
- const response = await fetch('/api/admin/settings', {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- });
-
- if (response.status === 403) {
- // User is not admin, hide admin settings sections
- console.log('User is not admin, hiding admin settings sections');
- const adminSection = document.getElementById('adminSection');
- if (adminSection) {
- adminSection.style.display = 'none';
- }
- return;
- }
-
- if (!response.ok) {
- throw new Error(`Failed to load site settings: ${response.status} ${response.statusText}`);
- }
-
- const settings = await response.json();
- console.log('[SiteSettings] Raw settings received from API:', settings);
-
- if (registrationToggleElem) {
- registrationToggleElem.checked = settings.registration_enabled === 'true';
- } else {
- console.error('[SiteSettings] registrationEnabled element NOT FOUND locally.');
- }
-
- if (emailBaseUrlFieldElem) {
- emailBaseUrlFieldElem.value = settings.email_base_url || 'http://localhost:8080';
- } else {
- console.error('[SiteSettings] emailBaseUrl element NOT FOUND locally.');
- }
-
- if (globalViewToggleElem) {
- globalViewToggleElem.checked = settings.global_view_enabled === 'true';
- } else {
- console.error('[SiteSettings] globalViewEnabled element NOT FOUND locally.');
- }
-
- if (globalViewAdminOnlyToggleElem) {
- globalViewAdminOnlyToggleElem.checked = settings.global_view_admin_only === 'true';
- } else {
- console.error('[SiteSettings] globalViewAdminOnly element NOT FOUND locally.');
- }
-
- // Populate OIDC settings using locally-scoped element variables
- if (oidcEnabledToggleElem) {
- console.log('[OIDC Settings] Found oidcEnabledToggleElem. Setting checked to:', settings.oidc_enabled === 'true');
- oidcEnabledToggleElem.checked = settings.oidc_enabled === 'true';
- } else {
- console.error('[OIDC Settings] oidcEnabledToggleElem element NOT FOUND locally.');
- }
-
- if (oidcOnlyModeToggleElem) {
- console.log('[OIDC Settings] Found oidcOnlyModeToggleElem. Setting checked to:', settings.oidc_only_mode === 'true');
- oidcOnlyModeToggleElem.checked = settings.oidc_only_mode === 'true';
- } else {
- console.error('[OIDC Settings] oidcOnlyModeToggleElem element NOT FOUND locally.');
- }
-
- if (oidcProviderNameInputElem) {
- console.log('[OIDC Settings] Found oidcProviderNameInputElem. Setting value to:', settings.oidc_provider_name || 'oidc');
- oidcProviderNameInputElem.value = settings.oidc_provider_name || 'oidc';
- } else {
- console.error('[OIDC Settings] oidcProviderNameInputElem element NOT FOUND locally.');
- }
-
- if (oidcClientIdInputElem) {
- console.log('[OIDC Settings] Found oidcClientIdInputElem. Setting value to:', settings.oidc_client_id || '');
- oidcClientIdInputElem.value = settings.oidc_client_id || '';
- } else {
- console.error('[OIDC Settings] oidcClientIdInputElem element NOT FOUND locally.');
- }
-
- if (oidcClientSecretInputElem) {
- console.log('[OIDC Settings] Found oidcClientSecretInputElem. Setting placeholder based on oidc_client_secret_set:', settings.oidc_client_secret_set);
- oidcClientSecretInputElem.value = ''; // Always clear on load
- oidcClientSecretInputElem.placeholder = settings.oidc_client_secret_set ? '******** (Set - Enter new to change)' : 'Enter OIDC Client Secret';
- } else {
- console.error('[OIDC Settings] oidcClientSecretInputElem element NOT FOUND locally.');
- }
-
- if (oidcIssuerUrlInputElem) {
- console.log('[OIDC Settings] Found oidcIssuerUrlInputElem. Setting value to:', settings.oidc_issuer_url || '');
- oidcIssuerUrlInputElem.value = settings.oidc_issuer_url || '';
- } else {
- console.error('[OIDC Settings] oidcIssuerUrlInputElem element NOT FOUND locally.');
- }
-
- if (oidcScopeInputElem) {
- console.log('[OIDC Settings] Found oidcScopeInputElem. Setting value to:', settings.oidc_scope || 'openid email profile');
- oidcScopeInputElem.value = settings.oidc_scope || 'openid email profile';
- } else {
- console.error('[OIDC Settings] oidcScopeInputElem element NOT FOUND locally.');
- }
-
- if (oidcAdminGroupInputElem) {
- console.log('[OIDC Settings] Found oidcAdminGroupInputElem. Setting value to:', settings.oidc_admin_group || '');
- oidcAdminGroupInputElem.value = settings.oidc_admin_group || '';
- } else {
- console.error('[OIDC Settings] oidcAdminGroupInputElem element NOT FOUND locally.');
- }
-
- console.log('Site and OIDC settings loaded and population attempted using locally queried elements.');
-
- } catch (error) {
- console.error('Error loading or populating site settings:', error);
- showToast('Failed to load site settings. Please try again.', 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Save site settings (non-OIDC part)
- */
-async function saveSiteSettings() {
- console.log('Saving site settings (non-OIDC)...');
- const registrationToggle = document.getElementById('registrationEnabled');
- const emailBaseUrlField = document.getElementById('emailBaseUrl');
- const globalViewToggle = document.getElementById('globalViewEnabled');
- const globalViewAdminOnlyToggle = document.getElementById('globalViewAdminOnly');
-
- const settingsToSave = {};
-
- if (registrationToggle) {
- settingsToSave.registration_enabled = registrationToggle.checked;
- }
-
- if (globalViewToggle) {
- settingsToSave.global_view_enabled = globalViewToggle.checked;
- }
-
- if (globalViewAdminOnlyToggle) {
- settingsToSave.global_view_admin_only = globalViewAdminOnlyToggle.checked;
- }
-
- if (emailBaseUrlField) {
- let baseUrl = emailBaseUrlField.value.trim();
- if (baseUrl && (baseUrl.startsWith('http://') || baseUrl.startsWith('https://'))) {
- if (baseUrl.endsWith('/')) {
- baseUrl = baseUrl.slice(0, -1);
- }
- settingsToSave.email_base_url = baseUrl;
- } else if (baseUrl) {
- showToast('Invalid Email Base URL format. It should start with http:// or https://', 'error');
- return;
- } else {
- settingsToSave.email_base_url = 'http://localhost:8080';
- emailBaseUrlField.value = settingsToSave.email_base_url;
- }
- }
-
- if (Object.keys(settingsToSave).length === 0) {
- showToast('No site settings to save.', 'info');
- return;
- }
-
- try {
- showLoading();
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
- console.log('Saving site settings with token:', token ? 'present' : 'missing');
-
- const response = await fetch('/api/admin/settings', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(settingsToSave)
- });
-
- const result = await response.json();
- if (response.ok) {
- showToast(result.message || 'Site settings saved successfully', 'success');
- } else {
- showToast(result.message || window.t('messages.failed_to_save_site_settings'), 'error');
- }
- } catch (error) {
- console.error('Error saving site settings:', error);
- showToast('Failed to save site settings. Please try again.', 'error');
- } finally {
- hideLoading();
- }
-}
-
-
-/**
- * Save OIDC settings
- */
-async function saveOidcSettings() {
- console.log('Saving OIDC settings...');
- const oidcSettingsPayload = {
- oidc_enabled: oidcEnabledToggle ? oidcEnabledToggle.checked : false,
- oidc_only_mode: oidcOnlyModeToggle ? oidcOnlyModeToggle.checked : false,
- oidc_provider_name: oidcProviderNameInput ? oidcProviderNameInput.value.trim() : 'oidc',
- oidc_client_id: oidcClientIdInput ? oidcClientIdInput.value.trim() : '',
- oidc_issuer_url: oidcIssuerUrlInput ? oidcIssuerUrlInput.value.trim() : '',
- oidc_scope: oidcScopeInput ? oidcScopeInput.value.trim() : 'openid email profile',
- oidc_admin_group: oidcAdminGroupInput ? oidcAdminGroupInput.value.trim() : ''
- };
-
- // Only include client_secret if a new value is entered
- if (oidcClientSecretInput && oidcClientSecretInput.value) {
- oidcSettingsPayload.oidc_client_secret = oidcClientSecretInput.value;
- }
-
- try {
- showLoading();
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
- console.log('Saving OIDC settings with token:', token ? 'present' : 'missing');
-
- const response = await fetch('/api/admin/settings', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(oidcSettingsPayload)
- });
-
- const result = await response.json();
- if (response.ok) {
- showToast(result.message || 'OIDC settings saved successfully.', 'success');
- if (result.message && result.message.includes("restart is required")) {
- if(oidcRestartMessage) oidcRestartMessage.style.display = 'block';
- } else {
- if(oidcRestartMessage) oidcRestartMessage.style.display = 'none';
- }
- // Clear the secret field after attempting to save
- if (oidcClientSecretInput) oidcClientSecretInput.value = '';
- // Reload settings to get the oidc_client_secret_set flag updated
- loadSiteSettings();
- } else {
- showToast(result.message || 'Failed to save OIDC settings.', 'error');
- }
- } catch (error) {
- console.error('Error saving OIDC settings:', error);
- showToast('Failed to save OIDC settings. Please try again.', 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Set up the delete button for user deletion
- */
-function setupDeleteButton() {
- console.log('=== SETUP DELETE BUTTON STARTED ===');
-
- // Get the confirm delete button
- const confirmDeleteUserBtn = document.getElementById('confirmDeleteUserBtn');
- if (!confirmDeleteUserBtn) {
- console.error('confirmDeleteUserBtn not found in setupDeleteButton');
- return;
- }
-
- try {
- // Get the user ID from various possible sources
- let userId = window.currentDeleteUserId || null;
-
- if (!userId && document.getElementById('deleteUserId')) {
- userId = document.getElementById('deleteUserId').value;
- }
-
- if (!userId && document.getElementById('editUserId')) {
- userId = document.getElementById('editUserId').value;
- }
-
- if (!userId && document.getElementById('displayUserId')) {
- userId = document.getElementById('displayUserId').textContent;
- }
-
- console.log('Setting up delete button for user ID:', userId);
-
- // Remove existing event listeners by cloning
- const newBtn = confirmDeleteUserBtn.cloneNode(true);
- confirmDeleteUserBtn.parentNode.replaceChild(newBtn, confirmDeleteUserBtn);
-
- // Add new event listener
- newBtn.addEventListener('click', function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Delete button clicked in setupDeleteButton');
- deleteUser();
- return false;
- });
-
- // Also set onclick for redundancy
- newBtn.onclick = function(e) {
- e.preventDefault();
- e.stopPropagation();
- console.log('Delete button clicked via onclick in setupDeleteButton');
- deleteUser();
- return false;
- };
-
- console.log('Delete button set up successfully');
- } catch (error) {
- console.error('Error setting up delete button:', error);
- }
-
- console.log('=== SETUP DELETE BUTTON COMPLETED ===');
-}
-
-/**
- * Direct API call for user deletion
- * @param {string|number} userId - The user ID or username to delete
- * @returns {Promise<boolean>} - Promise that resolves to true if deletion was successful, false otherwise
- */
-function directDeleteUserAPI(userId) {
- console.log('=== DIRECT DELETE API CALL STARTED ===');
- console.log('Function caller:', arguments.callee.caller ? arguments.callee.caller.name : 'unknown');
-
- return new Promise((resolve, reject) => {
- // Try to get the user ID from multiple sources if not provided
- if (!userId) {
- const deleteUserIdField = document.getElementById('deleteUserId');
- const editUserIdField = document.getElementById('editUserId');
- const displayUserIdField = document.getElementById('displayUserId');
-
- userId = window.currentDeleteUserId;
-
- if (!userId && deleteUserIdField && deleteUserIdField.value) {
- userId = deleteUserIdField.value;
- } else if (!userId && editUserIdField && editUserIdField.value) {
- userId = editUserIdField.value;
- } else if (!userId && displayUserIdField && displayUserIdField.textContent) {
- userId = displayUserIdField.textContent;
- }
- }
-
- console.log('User ID to delete:', userId);
-
- if (!userId) {
- console.error('Direct delete API call failed: User ID is missing');
- reject(new Error('User ID is missing'));
- return;
- }
-
- // Check if the input is a username rather than a numeric ID
- if (isNaN(userId)) {
- console.log('Input appears to be a username, not a numeric ID');
- // Try to find the user ID by username
- findUserIdByUsernameAsync(userId)
- .then(numericId => {
- if (numericId) {
- console.log(`Found numeric ID ${numericId} for username ${userId}`);
- // Call this function again with the numeric ID
- return directDeleteUserAPI(numericId);
- } else {
- throw new Error(`Could not find a user with username "${userId}"`);
- }
- })
- .then(resolve)
- .catch(reject);
- return;
- }
-
- console.log('Proceeding with numeric user ID:', userId);
-
- // Get the token with detailed logging
- const token = localStorage.getItem('auth_token');
- console.log('Token exists:', !!token);
- console.log('Token length:', token ? token.length : 0);
-
- if (!token) {
- console.error('Authentication token is missing');
- reject(new Error('Authentication token is missing'));
- return;
- }
-
- // Log the API endpoint
- const apiEndpoint = `/api/admin/users/${userId}`;
- console.log('Direct API endpoint:', apiEndpoint);
-
- // Create headers with detailed logging
- const headers = {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json',
- 'Accept': 'application/json'
- };
- console.log('Direct API request headers:', Object.keys(headers));
-
- // Make the fetch request with detailed logging
- console.log('Direct API fetch request configuration:', {
- method: 'DELETE',
- headers: Object.keys(headers),
- credentials: 'same-origin'
- });
-
- // Make a fetch API call
- fetch(apiEndpoint, {
- method: 'DELETE',
- headers: headers,
- credentials: 'same-origin' // Include cookies
- })
- .then(response => {
- console.log('Direct API response received');
- console.log('Direct API response status:', response.status);
- console.log('Direct API response status text:', response.statusText);
- console.log('Direct API response headers:', [...response.headers.entries()]);
- console.log('Direct API response type:', response.type);
- console.log('Direct API response URL:', response.url);
-
- // Get the raw text first
- return response.text().then(text => {
- console.log('Direct API raw response text:', text);
- try {
- const data = text ? JSON.parse(text) : {};
- return {
- status: response.status,
- data: data
- };
- } catch (err) {
- console.log('Error parsing Direct API JSON response:', err);
- return {
- status: response.status,
- data: { message: text || 'No response data or invalid JSON' }
- };
- }
- });
- })
- .then(result => {
- console.log('Direct API response data:', result);
-
- if (result.status >= 200 && result.status < 300) {
- console.log('Direct API call successful');
- resolve(true);
- } else {
- const errorMessage = result.data && result.data.message ? result.data.message : 'Failed to delete user';
- console.error('Direct API call failed:', errorMessage);
- resolve(false); // Resolve with false instead of rejecting
- }
- })
- .catch(error => {
- console.error('Direct API call error:', error);
- console.error('Direct API call error details:', error.message, error.stack);
- reject(error);
- });
- });
-}
-
-/**
- * Check if the API endpoint is accessible
- */
-function checkApiEndpoint() {
- console.log('Checking API endpoint accessibility...');
-
- // Try to access a simple API endpoint
- fetch('/api/auth/validate-token', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
- }
- })
- .then(response => {
- console.log('API endpoint check response status:', response.status);
- if (response.ok) {
- console.log('API endpoint is accessible');
- showToast('API endpoint is accessible', 'success');
- } else {
- console.error('API endpoint is not accessible');
- showToast('API endpoint is not accessible. Status: ' + response.status, 'error');
- }
- return response.json().catch(() => ({}));
- })
- .then(data => {
- console.log('API endpoint check response data:', data);
- })
- .catch(error => {
- console.error('Error checking API endpoint:', error);
- showToast('Error checking API endpoint: ' + error.message, 'error');
- });
-}
-
-/**
- * Trigger warranty expiration notifications (admin only)
- */
-async function triggerWarrantyNotifications() {
- console.log('Trigger warranty notifications requested');
-
- // Check if admin
- try {
- const response = await fetch('/api/auth/user', {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- throw new Error('Failed to check user status');
- }
-
- const userData = await response.json();
-
- if (!userData.is_admin) {
- showToast('Only administrators can send warranty notifications', 'error');
- return;
- }
-
- // Show confirmation dialog
- if (!confirm('Are you sure you want to send warranty expiration notifications to all eligible users? This will immediately email users with warranties expiring soon.')) {
- return;
- }
-
- showLoading();
-
- // Call the API endpoint to trigger notifications
- const notificationResponse = await fetch('/api/admin/send-notifications', {
- method: 'POST',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- });
-
- if (!notificationResponse.ok) {
- const errorData = await notificationResponse.json();
- throw new Error(errorData.message || 'Failed to send notifications');
- }
-
- const result = await notificationResponse.json();
- showToast(result.message || 'Notifications triggered successfully', 'success');
-
- } catch (error) {
- console.error('Error triggering notifications:', error);
- showToast('Error: ' + error.message, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Check scheduler status (admin only)
- */
-async function checkSchedulerStatus() {
- console.log('Checking scheduler status...');
-
- try {
- showLoading();
-
- const response = await fetch('/api/admin/scheduler-status', {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({ message: 'Unknown error occurred' }));
- throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
- }
-
- const status = await response.json();
- console.log('Scheduler status:', status);
-
- // Format the status information for display
- let message = '📊 Scheduler Status Report\n\n';
- message += `🚀 Initialized: ${status.scheduler_initialized ? '✅ Yes' : '❌ No'}\n`;
- message += `🔄 Running: ${status.scheduler_running ? '✅ Yes' : '❌ No'}\n`;
- message += `📋 Active Jobs: ${status.scheduler_jobs.length}\n`;
-
- if (status.scheduler_jobs.length > 0) {
- message += '\n📅 Scheduled Jobs:\n';
- status.scheduler_jobs.forEach(job => {
- const nextRun = job.next_run_time ?
- new Date(job.next_run_time).toLocaleString() :
- 'Not scheduled';
- message += `• ${job.id}: ${nextRun}\n`;
- message += ` Trigger: ${job.trigger}\n`;
- });
- }
-
- message += `\n🔧 Worker Information:\n`;
- message += `• Worker ID: ${status.worker_info.worker_id}\n`;
- message += `• Worker Name: ${status.worker_info.worker_name}\n`;
- message += `• Worker Class: ${status.worker_info.worker_class}\n`;
- message += `• Should Run Scheduler: ${status.worker_info.should_run_scheduler ? '✅ Yes' : '❌ No'}\n`;
-
- if (status.environment_vars && Object.keys(status.environment_vars).length > 0) {
- message += `\n🌍 Environment Variables:\n`;
- Object.entries(status.environment_vars).forEach(([key, value]) => {
- message += `• ${key}: ${value}\n`;
- });
- }
-
- // Show in alert dialog
- alert(message);
-
- // Also show a toast with a summary
- const summary = status.scheduler_running ?
- '✅ Scheduler is running normally' :
- '⚠️ Scheduler is not running - notifications may not be sent automatically';
- showToast(summary, status.scheduler_running ? 'success' : 'warning', 8000);
-
- } catch (error) {
- console.error('Error checking scheduler status:', error);
- showToast(`Error checking scheduler status: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Load available timezones from the API
- * @returns {Promise} A promise that resolves when timezones are loaded
- */
-function loadTimezones() {
- return loadTimezonesIntoSelect(timezoneSelect);
-}
-
-function loadTimezonesIntoSelect(selectElement) {
- if (!selectElement) {
- return Promise.reject('Select element not provided to loadTimezonesIntoSelect');
- }
- console.log(`Loading timezones into ${selectElement.id}...`);
- return new Promise((resolve, reject) => {
- fetch('/api/timezones', {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- })
- .then(response => {
- if (!response.ok) {
- throw new Error('Failed to load timezones');
- }
- return response.json();
- })
- .then(timezoneGroups => {
- // Clear loading option
- selectElement.innerHTML = '';
-
- // Add timezone groups and their options
- timezoneGroups.forEach(group => {
- const optgroup = document.createElement('optgroup');
- optgroup.label = group.region;
-
- group.timezones.forEach(timezone => {
- const option = document.createElement('option');
- option.value = timezone.value;
- option.textContent = timezone.label;
- optgroup.appendChild(option);
- });
-
- selectElement.appendChild(optgroup);
- });
-
- // Set the current timezone from preferences
- // Get the appropriate key prefix based on user type
- const prefix = getPreferenceKeyPrefix();
- const savedPreferences = JSON.parse(localStorage.getItem(`${prefix}preferences`) || '{}');
-
- console.log('Loading timezone preference from localStorage', {
- prefix: prefix,
- preferenceKey: `${prefix}preferences`,
- savedTimezone: savedPreferences.timezone
- });
-
- if (savedPreferences.timezone) {
- selectElement.value = savedPreferences.timezone;
- console.log(`Set ${selectElement.id} to:`, savedPreferences.timezone, 'Current value:', selectElement.value);
- resolve();
- } else {
- // If no timezone preference found in localStorage, load from API as backup
- console.log('No timezone found in localStorage, fetching from API');
- fetch('/api/auth/preferences', {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- })
- .then(response => response.json())
- .then(data => {
- // API returns preferences directly, not nested
- if (data && data.timezone) {
- console.log('Received timezone from API:', data.timezone);
- selectElement.value = data.timezone;
- console.log(`Set ${selectElement.id} to:`, data.timezone, 'Current value:', selectElement.value);
- }
- resolve();
- })
- .catch(error => {
- console.error('Error loading preferences from API:', error);
- resolve(); // Still resolve to continue the chain
- });
- }
- })
- .catch(error => {
- console.error('Error loading timezones:', error);
- selectElement.innerHTML = '<option value="UTC">UTC (Coordinated Universal Time)</option>';
- reject(error);
- });
- });
-}
-
-/**
- * Save email settings
- */
-function toggleNotificationSettings(channel) {
- if (emailSettingsContainer) {
- emailSettingsContainer.style.display = (channel === 'email' || channel === 'both') ? 'block' : 'none';
- }
- if (userAppriseSettingsContainer) {
- userAppriseSettingsContainer.style.display = (channel === 'apprise' || channel === 'both') ? 'block' : 'none';
- }
-}
-
-async function saveNotificationSettings() {
- showLoading();
-
- try {
- const preferences = {
- notification_channel: notificationChannel.value,
- notification_frequency: notificationFrequencySelect.value,
- notification_time: notificationTimeInput.value,
- apprise_notification_time: userAppriseNotificationTimeInput ? userAppriseNotificationTimeInput.value : '09:00',
- apprise_notification_frequency: userAppriseNotificationFrequency ? userAppriseNotificationFrequency.value : 'daily',
- timezone: timezoneSelect.value,
- apprise_timezone: userAppriseTimezoneSelect ? userAppriseTimezoneSelect.value : 'UTC'
- };
-
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
- console.log('Saving notification settings with token:', token ? 'present' : 'missing');
-
- const response = await fetch('/api/auth/preferences', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(preferences)
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.message || 'Failed to save notification settings');
- }
-
- showToast('Notification settings saved successfully', 'success');
- } catch (error) {
- console.error('Error saving notification settings:', error);
- showToast(`Error saving notification settings: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-// --- Add Storage Event Listener for Real-time Sync ---
-window.addEventListener('storage', (event) => {
- console.log(`[Settings Storage Listener] Event received: key=${event.key}, newValue=${event.newValue}`); // Log all events
-
- const prefix = getPreferenceKeyPrefix();
- const targetKey = `${prefix}defaultView`;
-
- // Only react to changes in the specific default view key for the current user type
- if (event.key === targetKey) { // Check key match first
- console.log(`[Settings Storage Listener] Matched key: ${targetKey}`);
- console.log(`[Settings Storage Listener] defaultViewSelect exists: ${!!defaultViewSelect}`);
- if (defaultViewSelect) {
- console.log(`[Settings Storage Listener] Current dropdown value: ${defaultViewSelect.value}`);
- }
- console.log(`[Settings Storage Listener] Event newValue: ${event.newValue}`);
-
- if (event.newValue && defaultViewSelect && defaultViewSelect.value !== event.newValue) {
- console.log(`[Settings Storage Listener] Value changed and dropdown exists. Checking options...`);
- const optionExists = [...defaultViewSelect.options].some(option => option.value === event.newValue);
- console.log(`[Settings Storage Listener] Option ${event.newValue} exists: ${optionExists}`);
- if (optionExists) {
- defaultViewSelect.value = event.newValue;
- console.log(`[Settings Storage Listener] SUCCESS: Updated settings default view dropdown via storage event to ${event.newValue}.`);
- } else {
- console.warn(`[Settings Storage Listener] Storage event value (${event.newValue}) not found in dropdown options.`);
- }
- } else if (!event.newValue) {
- console.log(`[Settings Storage Listener] Ignoring event for ${targetKey} because newValue is null/empty.`);
- } else if (!defaultViewSelect) {
- console.log(`[Settings Storage Listener] Ignoring event for ${targetKey} because defaultViewSelect element not found.`);
- } else {
- console.log(`[Settings Storage Listener] Ignoring event for ${targetKey} because value hasn't changed (${defaultViewSelect.value} === ${event.newValue}).`);
- }
- }
-
- // Add similar checks for other preferences if needed, e.g., dateFormat, currencySymbol
- if (event.key === 'dateFormat') { // Simplified log for other keys
- console.log(`[Settings Storage Listener] dateFormat changed to ${event.newValue}`);
- if (event.newValue && dateFormatSelect && dateFormatSelect.value !== event.newValue) {
- const optionExists = [...dateFormatSelect.options].some(option => option.value === event.newValue);
- if (optionExists) {
- dateFormatSelect.value = event.newValue;
- console.log('[Settings Storage Listener] Updated settings date format dropdown via storage event.');
- }
- }
- }
-
- if (event.key === `${prefix}currencySymbol`) { // Simplified log for other keys
- console.log(`[Settings Storage Listener] ${prefix}currencySymbol changed to ${event.newValue}`);
- if (event.newValue && currencySymbolSelect && currencySymbolSelect.value !== event.newValue) {
- // Handle standard vs custom symbol update
- const standardOption = Array.from(currencySymbolSelect.options).find(opt => opt.value === event.newValue);
- if (standardOption) {
- currencySymbolSelect.value = event.newValue;
- if (currencySymbolCustom) currencySymbolCustom.style.display = 'none';
- console.log('[Settings Storage Listener] Updated settings currency dropdown via storage event.');
- } else if (currencySymbolSelect.value !== 'other' || (currencySymbolCustom && currencySymbolCustom.value !== event.newValue)) {
- currencySymbolSelect.value = 'other';
- if (currencySymbolCustom) {
- currencySymbolCustom.value = event.newValue;
- currencySymbolCustom.style.display = 'inline-block';
- }
- console.log('[Settings Storage Listener] Updated settings currency dropdown to custom via storage event.');
- }
- }
- }
-
- // Add check for expiringSoonDays
- if (event.key === `${prefix}expiringSoonDays`) { // Simplified log for other keys
- console.log(`[Settings Storage Listener] ${prefix}expiringSoonDays changed to ${event.newValue}`);
- if (event.newValue && expiringSoonDaysInput && expiringSoonDaysInput.value !== event.newValue) {
- expiringSoonDaysInput.value = event.newValue;
- console.log('[Settings Storage Listener] Updated settings expiring soon days input via storage event.');
- }
- }
-
- // Add check for currencyPosition
- if (event.key === `${prefix}currencyPosition`) {
- console.log(`[Settings Storage Listener] ${prefix}currencyPosition changed to ${event.newValue}`);
- if (event.newValue && currencyPositionSelect && currencyPositionSelect.value !== event.newValue) {
- currencyPositionSelect.value = event.newValue;
- console.log('[Settings Storage Listener] Updated settings currency position dropdown via storage event.');
- }
- }
-
-});
-// --- End Storage Event Listener ---
-
-// Add event listener for dropdown to show/hide custom input
-if (currencySymbolSelect && currencySymbolCustom) {
- currencySymbolSelect.addEventListener('change', function() {
- if (this.value === 'other') {
- currencySymbolCustom.style.display = '';
- currencySymbolCustom.focus();
- } else {
- currencySymbolCustom.style.display = 'none';
- currencySymbolCustom.value = '';
- }
- });
-}
-
-// =====================
-// APPRISE NOTIFICATIONS FUNCTIONALITY
-// =====================
-
-/**
- * Load Apprise settings and status
- */
-async function loadAppriseSettings() {
- try {
- // Get current Apprise status
- const statusResponse = await fetch('/api/admin/apprise/status', {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- });
-
- if (statusResponse.status === 403) {
- // User is not admin, hide Apprise section
- const appriseCard = document.querySelector('.card:has(#appriseStatusBadge)');
- if (appriseCard) {
- appriseCard.style.display = 'none';
- }
- return;
- }
-
- if (statusResponse.status === 503) {
- // Apprise not available
- if (appriseNotAvailable) appriseNotAvailable.style.display = 'block';
- if (appriseStatusBadge) appriseStatusBadge.textContent = 'Not Available';
- if (appriseStatusBadge) appriseStatusBadge.className = 'badge badge-danger';
- return;
- }
-
- const statusData = await statusResponse.json();
-
- // Update status badge
- if (appriseStatusBadge) {
- if (statusData.available && statusData.enabled) {
- appriseStatusBadge.textContent = 'Active';
- appriseStatusBadge.className = 'badge badge-success';
- } else if (statusData.available) {
- appriseStatusBadge.textContent = 'Disabled';
- appriseStatusBadge.className = 'badge badge-warning';
- } else {
- appriseStatusBadge.textContent = 'Not Available';
- appriseStatusBadge.className = 'badge badge-danger';
- }
- }
-
- // Update status display
- if (appriseUrlsCount) appriseUrlsCount.textContent = statusData.urls_configured || 0;
- if (currentAppriseExpirationDays) currentAppriseExpirationDays.textContent = statusData.expiration_days ? statusData.expiration_days.join(', ') : '-';
-
- // Load settings from site settings
- await loadAppriseSiteSettings();
-
- } catch (error) {
- console.error('Error loading Apprise settings:', error);
- if (appriseStatusBadge) {
- appriseStatusBadge.textContent = 'Error';
- appriseStatusBadge.className = 'badge badge-danger';
- }
- }
-}
-
-/**
- * Load Apprise site settings
- */
-async function loadAppriseSiteSettings() {
- try {
- console.log('📥 Loading Apprise site settings...');
- const response = await fetch('/api/admin/settings', {
- method: 'GET',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- });
-
- console.log('📥 Load response status:', response.status);
-
- if (!response.ok) {
- console.warn('⚠️ Load response not OK, skipping settings load');
- return;
- }
-
- const data = await response.json();
- console.log('📥 Loaded settings data:', data);
-
- // Check if Apprise settings exist in the data
- const appriseKeys = Object.keys(data).filter(key => key.startsWith('apprise_'));
- console.log('📥 Found Apprise keys:', appriseKeys);
-
- // Update form fields
- if (appriseEnabledToggle && data.apprise_enabled !== undefined) {
- appriseEnabledToggle.checked = data.apprise_enabled === 'true';
- console.log('✅ Set appriseEnabled:', data.apprise_enabled);
-
- // Show/hide settings container based on enabled state
- const settingsContainer = document.getElementById('appriseSettingsContainer');
- if (settingsContainer) {
- settingsContainer.style.display = data.apprise_enabled === 'true' ? 'block' : 'none';
- }
- } else {
- console.log('⚠️ appriseEnabled element not found or apprise_enabled data missing');
- }
-
- if (appriseUrlsTextarea && data.apprise_urls) {
- appriseUrlsTextarea.value = data.apprise_urls.replace(/,/g, '\n');
- console.log('✅ Set appriseUrls:', data.apprise_urls);
- } else {
- console.log('⚠️ appriseUrlsTextarea element not found or apprise_urls data missing');
- }
-
- if (appriseExpirationDaysInput && data.apprise_expiration_days) {
- appriseExpirationDaysInput.value = data.apprise_expiration_days;
- console.log('✅ Set appriseExpirationDays:', data.apprise_expiration_days);
- } else {
- console.log('⚠️ appriseExpirationDaysInput element not found or data missing');
- }
-
-
-
- if (appriseTitlePrefixInput && data.apprise_title_prefix) {
- appriseTitlePrefixInput.value = data.apprise_title_prefix;
- console.log('✅ Set appriseTitlePrefix:', data.apprise_title_prefix);
- } else {
- console.log('⚠️ appriseTitlePrefixInput element not found or data missing');
- }
-
- if (appriseNotificationModeSelect && data.apprise_notification_mode) {
- appriseNotificationModeSelect.value = data.apprise_notification_mode;
- updateAppriseModeDescription(data.apprise_notification_mode);
- console.log('✅ Set appriseNotificationMode:', data.apprise_notification_mode);
- } else {
- console.log('⚠️ appriseNotificationModeSelect element not found or data missing');
- // Set default mode if not found
- if (appriseNotificationModeSelect) {
- appriseNotificationModeSelect.value = 'global';
- updateAppriseModeDescription('global');
- }
- }
-
- if (appriseWarrantyScopeSelect && data.apprise_warranty_scope) {
- appriseWarrantyScopeSelect.value = data.apprise_warranty_scope;
- updateAppriseScopeDescription(data.apprise_warranty_scope);
- console.log('✅ Set appriseWarrantyScope:', data.apprise_warranty_scope);
- } else {
- console.log('⚠️ appriseWarrantyScopeSelect element not found or data missing');
- // Set default scope if not found
- if (appriseWarrantyScopeSelect) {
- appriseWarrantyScopeSelect.value = 'all';
- updateAppriseScopeDescription('all');
- }
- }
-
- } catch (error) {
- console.error('❌ Error loading Apprise site settings:', error);
- }
-}
-
-/**
- * Save Apprise settings
- */
-async function saveAppriseSettings() {
- try {
- console.log('🔍 Starting saveAppriseSettings...');
- showLoading();
-
- // Process URLs - convert newlines to commas and clean up
- const urlsText = appriseUrlsTextarea ? appriseUrlsTextarea.value : '';
- const urls = urlsText.split(/[\n,]/)
- .map(url => url.trim())
- .filter(url => url.length > 0)
- .join(',');
-
- const settings = {
- apprise_enabled: appriseEnabledToggle ? appriseEnabledToggle.checked.toString() : 'false',
- apprise_notification_mode: appriseNotificationModeSelect ? appriseNotificationModeSelect.value : 'global',
- apprise_warranty_scope: appriseWarrantyScopeSelect ? appriseWarrantyScopeSelect.value : 'all',
- apprise_urls: urls,
- apprise_expiration_days: appriseExpirationDaysInput ? appriseExpirationDaysInput.value : '7,30',
- apprise_title_prefix: appriseTitlePrefixInput ? appriseTitlePrefixInput.value : '[Warracker]'
- };
-
- console.log('📋 Settings to save:', settings);
-
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
- console.log('📡 Saving Apprise settings with token:', token ? 'present' : 'missing');
-
- const response = await fetch('/api/admin/settings', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(settings)
- });
-
- console.log('📡 Response status:', response.status);
-
- if (!response.ok) {
- const errorData = await response.json();
- console.error('❌ Response error:', errorData);
- throw new Error(errorData.message || 'Failed to save Apprise settings');
- }
-
- const responseData = await response.json();
- console.log('✅ Save response:', responseData);
-
- // Reload configuration
- console.log('🔄 Reloading Apprise configuration...');
- const reloadResponse = await fetch('/api/admin/apprise/reload-config', {
- method: 'POST',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- });
-
- console.log('🔄 Reload response status:', reloadResponse.status);
-
- showToast('Apprise settings saved successfully', 'success');
-
- // Reload status
- console.log('📱 Reloading Apprise settings...');
- await loadAppriseSettings();
-
- } catch (error) {
- console.error('❌ Error saving Apprise settings:', error);
- showToast(`Error saving Apprise settings: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Send test Apprise notification
- */
-async function sendTestAppriseNotification() {
- try {
- showLoading();
-
- const testUrl = appriseTestUrlInput ? appriseTestUrlInput.value.trim() : null;
-
- const payload = testUrl ? { test_url: testUrl } : {};
-
- const response = await fetch('/api/admin/apprise/test', {
- method: 'POST',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(payload)
- });
-
- const data = await response.json();
-
- if (data.success) {
- showToast('Test notification sent successfully', 'success');
- } else {
- showToast(`Failed to send test notification: ${data.message}`, 'error');
- }
-
- } catch (error) {
- console.error('Error sending test notification:', error);
- showToast(`Error sending test notification: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Validate Apprise URLs
- */
-async function validateAppriseUrls() {
- try {
- showLoading();
-
- const urlsText = appriseUrlsTextarea ? appriseUrlsTextarea.value : '';
- const urls = urlsText.split(/[\n,]/)
- .map(url => url.trim())
- .filter(url => url.length > 0);
-
- if (urls.length === 0) {
- showToast('No URLs to validate', 'warning');
- hideLoading();
- return;
- }
-
- let validCount = 0;
- let invalidUrls = [];
-
- for (const url of urls) {
- try {
- const response = await fetch('/api/admin/apprise/validate-url', {
- method: 'POST',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({ url: url })
- });
-
- const data = await response.json();
-
- if (data.valid) {
- validCount++;
- } else {
- invalidUrls.push(url);
- }
- } catch (error) {
- invalidUrls.push(url);
- }
- }
-
- let message = `Validation complete: ${validCount}/${urls.length} URLs are valid`;
- if (invalidUrls.length > 0) {
- message += `\nInvalid URLs: ${invalidUrls.join(', ')}`;
- showToast(message, 'warning');
- } else {
- showToast(message, 'success');
- }
-
- } catch (error) {
- console.error('Error validating URLs:', error);
- showToast(`Error validating URLs: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Trigger Apprise expiration notifications
- */
-async function triggerAppriseExpirationNotifications() {
- try {
- showLoading();
-
- const response = await fetch('/api/admin/apprise/send-expiration', {
- method: 'POST',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- });
-
- const data = await response.json();
-
- if (data.success) {
- showToast(data.message, 'success');
- } else {
- showToast(`Failed to trigger notifications: ${data.message}`, 'error');
- }
-
- } catch (error) {
- console.error('Error triggering Apprise notifications:', error);
- showToast(`Error triggering notifications: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * View supported services
- */
-function viewSupportedAppriseServices() {
- window.open('https://github.com/caronc/apprise/wiki', '_blank', 'noopener,noreferrer');
-}
-
-/**
- * Save just the Apprise enabled/disabled state
- */
-async function saveAppriseEnabledState(enabled) {
- try {
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
-
- const response = await fetch('/api/admin/settings', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- apprise_enabled: enabled.toString()
- })
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.message || 'Failed to save Apprise enabled state');
- }
-
- // Reload configuration
- const reloadResponse = await fetch('/api/admin/apprise/reload-config', {
- method: 'POST',
- headers: {
- 'Authorization': 'Bearer ' + localStorage.getItem('auth_token'),
- 'Content-Type': 'application/json'
- }
- });
-
- console.log('✅ Apprise enabled state saved:', enabled);
-
- // Update status badge
- await loadAppriseSettings();
-
- } catch (error) {
- console.error('❌ Error saving Apprise enabled state:', error);
- showToast(`Error updating Apprise setting: ${error.message}`, 'error');
-
- // Revert the toggle if save failed
- if (appriseEnabledToggle) {
- appriseEnabledToggle.checked = !enabled;
- }
- }
-}
-
-/**
- * Update Apprise mode description text
- */
-function updateAppriseModeDescription(mode) {
- if (!appriseModeDescription) return;
-
- if (mode === 'global') {
- appriseModeDescription.textContent = 'A single, consolidated notification will be sent to the global Apprise channels defined below.';
- } else if (mode === 'individual') {
- appriseModeDescription.textContent = 'A separate notification will be sent for each user with expiring warranties. (Note: This currently uses the global channels. Per-user channels can be a future enhancement.)';
- }
-}
-
-/**
- * Update Apprise warranty scope description text
- */
-function updateAppriseScopeDescription(scope) {
- if (!appriseScopeDescription) return;
-
- if (scope === 'all') {
- appriseScopeDescription.textContent = 'Notifications will include expiring warranties from all users in the system.';
- } else if (scope === 'admin') {
- appriseScopeDescription.textContent = 'Notifications will only include expiring warranties belonging to the admin/owner user.';
- }
-}
-
-/**
- * Setup Apprise event listeners
- */
-function setupAppriseEventListeners() {
- // Enable/disable toggle
- if (appriseEnabledToggle) {
- appriseEnabledToggle.addEventListener('change', async function() {
- const settingsContainer = document.getElementById('appriseSettingsContainer');
- if (settingsContainer) {
- settingsContainer.style.display = this.checked ? 'block' : 'none';
- }
-
- // Auto-save the enabled state
- await saveAppriseEnabledState(this.checked);
- });
- }
-
- // Notification mode change
- if (appriseNotificationModeSelect) {
- appriseNotificationModeSelect.addEventListener('change', (e) => {
- updateAppriseModeDescription(e.target.value);
- });
- }
-
- // Warranty scope change
- if (appriseWarrantyScopeSelect) {
- appriseWarrantyScopeSelect.addEventListener('change', (e) => {
- updateAppriseScopeDescription(e.target.value);
- });
- }
-
- // Save settings
- if (saveAppriseSettingsBtn) {
- saveAppriseSettingsBtn.addEventListener('click', saveAppriseSettings);
- }
-
- // Test notification
- if (testAppriseBtn) {
- testAppriseBtn.addEventListener('click', sendTestAppriseNotification);
- }
-
- // Validate URLs
- if (validateAppriseUrlBtn) {
- validateAppriseUrlBtn.addEventListener('click', validateAppriseUrls);
- }
-
- // Trigger expiration notifications
- if (triggerAppriseNotificationsBtn) {
- triggerAppriseNotificationsBtn.addEventListener('click', triggerAppriseExpirationNotifications);
- }
-
- // View supported services
- if (viewSupportedServicesBtn) {
- viewSupportedServicesBtn.addEventListener('click', viewSupportedAppriseServices);
- }
-}
-
-// Initialize Apprise functionality
-document.addEventListener('DOMContentLoaded', function() {
- setupAppriseEventListeners();
-
- // Load Apprise settings after auth is ready (admin only)
- setTimeout(() => {
- if (window.auth && window.auth.isAuthenticated && window.auth.isAuthenticated()) {
- const currentUser = window.auth.getCurrentUser();
- if (currentUser && currentUser.is_admin) {
- loadAppriseSettings();
- loadPaperlessSettings(); // Also load Paperless-ngx settings for admin
- } else {
- console.log('User is not admin, skipping Apprise settings load in deferred initialization');
- }
- }
- }, 1000);
-});
-
-// ============================================================================
-// Paperless-ngx Integration Functions
-// ============================================================================
-
-/**
- * Toggle the visibility of Paperless-ngx settings based on enabled state
- * @param {boolean} enabled - Whether Paperless-ngx is enabled
- */
-function togglePaperlessSettings(enabled) {
- if (paperlessSettingsContainer) {
- paperlessSettingsContainer.style.display = enabled ? 'block' : 'none';
- }
-}
-
-/**
- * Load Paperless-ngx settings from the server
- */
-async function loadPaperlessSettings() {
- try {
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
-
- const response = await fetch('/api/admin/settings', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- if (!response.ok) {
- throw new Error('Failed to load settings');
- }
-
- const settings = await response.json();
-
- // Update Paperless-ngx settings UI
- if (paperlessEnabledToggle) {
- const isEnabled = settings.paperless_enabled === 'true';
- paperlessEnabledToggle.checked = isEnabled;
- togglePaperlessSettings(isEnabled);
- }
-
- if (paperlessUrlInput && settings.paperless_url) {
- paperlessUrlInput.value = settings.paperless_url;
- }
-
- // Update API token field placeholder to indicate if token is saved
- if (paperlessApiTokenInput) {
- if (settings.paperless_api_token_set === 'true') {
- paperlessApiTokenInput.placeholder = 'API token saved (hidden for security) - Leave blank to keep existing';
- } else {
- paperlessApiTokenInput.placeholder = 'Enter API token';
- }
- }
-
- console.log('✅ Paperless-ngx settings loaded successfully');
-
- } catch (error) {
- console.error('❌ Error loading Paperless-ngx settings:', error);
- showToast(`Error loading Paperless-ngx settings: ${error.message}`, 'error');
- }
-}
-
-/**
- * Save Paperless-ngx settings to the server
- */
-async function savePaperlessSettings() {
- try {
- showLoading();
-
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
-
- // Validate URL format
- const url = paperlessUrlInput.value.trim();
- if (url && !isValidUrl(url)) {
- showToast('Please enter a valid URL (e.g., https://paperless.yourdomain.com)', 'error');
- return;
- }
-
- // Prepare settings data
- const settingsData = {
- paperless_enabled: paperlessEnabledToggle.checked.toString(),
- paperless_url: url
- };
-
- // Only include API token if it's provided (not empty)
- const apiToken = paperlessApiTokenInput.value.trim();
- if (apiToken) {
- settingsData.paperless_api_token = apiToken;
- }
-
- // Save admin settings first
- const response = await fetch('/api/admin/settings', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(settingsData)
- });
-
- if (!response.ok) {
- const errorData = await response.json();
- throw new Error(errorData.message || 'Failed to save Paperless-ngx settings');
- }
-
- // Also save the user preference for viewing documents in app
- const paperlessViewInApp = paperlessViewInAppToggle ? paperlessViewInAppToggle.checked : false;
- const preferencesData = {
- paperless_view_in_app: paperlessViewInApp
- };
-
- const preferencesResponse = await fetch('/api/auth/preferences', {
- method: 'PUT',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify(preferencesData)
- });
-
- if (!preferencesResponse.ok) {
- console.warn('Failed to save paperless view preference, but admin settings were saved');
- }
-
- // Update localStorage for the preference
- const prefix = getPreferenceKeyPrefix();
- localStorage.setItem(`${prefix}paperlessViewInApp`, paperlessViewInApp);
-
- showToast('Paperless-ngx settings saved successfully!', 'success');
-
- // Clear the API token input for security
- if (paperlessApiTokenInput) {
- paperlessApiTokenInput.value = '';
- paperlessApiTokenInput.placeholder = 'API token saved (hidden for security) - Leave blank to keep existing';
- }
-
- console.log('✅ Paperless-ngx settings saved successfully');
-
- } catch (error) {
- console.error('❌ Error saving Paperless-ngx settings:', error);
- showToast(`Error saving Paperless-ngx settings: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Test connection to Paperless-ngx instance
- */
-async function testPaperlessConnection() {
- try {
- showLoading();
-
- // Clear previous status
- if (paperlessConnectionStatus) {
- paperlessConnectionStatus.innerHTML = '';
- paperlessConnectionStatus.className = 'paperless-status-message';
- }
-
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
-
- // Get current values from the form
- const url = paperlessUrlInput.value.trim();
- const apiToken = paperlessApiTokenInput.value.trim();
-
- if (!url) {
- showToast('Please enter a Paperless-ngx URL first', 'warning');
- return;
- }
-
- // Check if API token is provided in form, otherwise use stored settings
- if (!apiToken && paperlessApiTokenInput.placeholder.includes('saved')) {
- // API token is already saved, test with stored settings
- const response = await fetch('/api/paperless/test', {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- const result = await response.json();
-
- if (paperlessConnectionStatus) {
- paperlessConnectionStatus.classList.add('show');
- if (result.success) {
- paperlessConnectionStatus.className = 'paperless-status-message show success';
- paperlessConnectionStatus.innerHTML = `
- <strong>✅ Connection Successful!</strong><br>
- ${result.message}
- ${result.server_info ? `<br><small>Server: ${result.server_info}</small>` : ''}
- `;
- showToast('Paperless-ngx connection test successful!', 'success');
- } else {
- paperlessConnectionStatus.className = 'paperless-status-message show error';
- paperlessConnectionStatus.innerHTML = `
- <strong>❌ Connection Failed!</strong><br>
- ${result.message}
- `;
- showToast('Paperless-ngx connection test failed', 'error');
- }
- }
-
- return;
- }
-
- if (!apiToken) {
- showToast('Please enter an API token to test the connection', 'warning');
- return;
- }
-
- const response = await fetch('/api/paperless/test', {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- url: url,
- api_token: apiToken
- })
- });
-
- const result = await response.json();
-
- if (paperlessConnectionStatus) {
- if (result.success) {
- paperlessConnectionStatus.classList.add('show');
- paperlessConnectionStatus.className = 'paperless-status-message show success';
- paperlessConnectionStatus.innerHTML = `
- <strong>✅ Connection Successful!</strong><br>
- ${result.message}
- ${result.server_info ? `<br><small>Server: ${result.server_info}</small>` : ''}
- `;
- showToast('Paperless-ngx connection test successful!', 'success');
- } else {
- paperlessConnectionStatus.classList.add('show');
- paperlessConnectionStatus.className = 'paperless-status-message show error';
- paperlessConnectionStatus.innerHTML = `
- <strong>❌ Connection Failed!</strong><br>
- ${result.message}
- `;
- showToast('Paperless-ngx connection test failed', 'error');
- }
- }
-
- } catch (error) {
- console.error('❌ Error testing Paperless-ngx connection:', error);
-
- if (paperlessConnectionStatus) {
- paperlessConnectionStatus.classList.add('show');
- paperlessConnectionStatus.className = 'paperless-status-message show error';
- paperlessConnectionStatus.innerHTML = `
- <strong>❌ Connection Error!</strong><br>
- ${error.message}
- `;
- }
-
- showToast(`Error testing connection: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Debug Paperless-ngx configuration
- */
-async function debugPaperlessConfiguration() {
- try {
- showLoading();
-
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
-
- const response = await fetch('/api/paperless/debug', {
- method: 'GET',
- headers: {
- 'Authorization': `Bearer ${token}`,
- 'Content-Type': 'application/json'
- }
- });
-
- const result = await response.json();
-
- // Display debug information
- console.log('🔍 Paperless-ngx Debug Information:', result);
-
- let debugHtml = '<h5>📋 Paperless-ngx Debug Information</h5>';
- debugHtml += `<strong>Enabled:</strong> ${result.paperless_enabled}<br>`;
- debugHtml += `<strong>URL:</strong> ${result.paperless_url || 'Not set'}<br>`;
- debugHtml += `<strong>API Token Set:</strong> ${result.paperless_api_token_set}<br>`;
- debugHtml += `<strong>Handler Available:</strong> ${result.paperless_handler_available}<br>`;
-
- if (result.test_connection_result) {
- debugHtml += `<strong>Connection Test:</strong> ${result.test_connection_result.success ? '✅ Success' : '❌ Failed'}<br>`;
- debugHtml += `<strong>Message:</strong> ${result.test_connection_result.message || result.test_connection_result.error}<br>`;
- }
-
- if (result.paperless_handler_error) {
- debugHtml += `<strong>Handler Error:</strong> ${result.paperless_handler_error}<br>`;
- }
-
- // Show in connection status area or create a temporary area
- if (paperlessConnectionStatus) {
- paperlessConnectionStatus.classList.add('show');
- paperlessConnectionStatus.className = 'paperless-status-message show info';
- paperlessConnectionStatus.innerHTML = debugHtml;
- } else {
- // Create temporary debug display
- const debugArea = document.createElement('div');
- debugArea.innerHTML = debugHtml;
- document.body.appendChild(debugArea);
- setTimeout(() => debugArea.remove(), 10000); // Remove after 10 seconds
- }
-
- showToast('Debug information logged to console', 'info');
-
- } catch (error) {
- console.error('❌ Error running Paperless debug:', error);
- showToast(`Debug error: ${error.message}`, 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Test basic file upload mechanism
- */
-async function testFileUpload() {
- try {
- showLoading();
-
- // Create a simple test file
- const testContent = 'This is a test file for Paperless-ngx upload debugging';
- const testFile = new File([testContent], 'test.txt', { type: 'text/plain' });
-
- const token = window.auth ? window.auth.getToken() : localStorage.getItem('auth_token');
-
- const formData = new FormData();
- formData.append('file', testFile);
- formData.append('document_type', 'test');
-
- const response = await fetch('/api/paperless/test-upload', {
- method: 'POST',
- headers: {
- 'Authorization': `Bearer ${token}`
- },
- body: formData
- });
-
- const result = await response.json();
-
- console.log('🧪 File Upload Test Result:', result);
-
- if (result.success) {
- showToast('File upload test successful!', 'success');
- if (paperlessConnectionStatus) {
- paperlessConnectionStatus.classList.add('show');
- paperlessConnectionStatus.className = 'paperless-status-message show success';
- paperlessConnectionStatus.innerHTML = `
- <strong>✅ File Upload Test Successful!</strong><br>
- ${result.message}<br>
- <small>File: ${result.file_info.filename} (${result.file_info.size} bytes)</small>
- `;
- }
- } else {
- showToast('File upload test failed', 'error');
- if (paperlessConnectionStatus) {
- paperlessConnectionStatus.classList.add('show');
- paperlessConnectionStatus.className = 'paperless-status-message show error';
- paperlessConnectionStatus.innerHTML = `
- <strong>❌ File Upload Test Failed!</strong><br>
- ${result.error}
- `;
- }
- }
-
- } catch (error) {
- console.error('❌ Error testing file upload:', error);
- showToast(window.t('messages.file_upload_test_error', { error: error.message }), 'error');
- } finally {
- hideLoading();
- }
-}
-
-/**
- * Validate if a string is a valid URL
- * @param {string} string - The string to validate
- * @returns {boolean} - Whether the string is a valid URL
- */
-function isValidUrl(string) {
- try {
- const url = new URL(string);
- return url.protocol === 'http:' || url.protocol === 'https:';
- } catch (_) {
- return false;
- }
-}
diff --git a/frontend/src/sw.js b/frontend/src/sw.js
deleted file mode 100644
index 97b932f..0000000
--- a/frontend/src/sw.js
+++ /dev/null
@@ -1,114 +0,0 @@
-const CACHE_NAME = 'warracker-cache-v20251030001';
-const urlsToCache = [
- // HTML pages
- './',
- './index.html',
- './status.html',
- './settings-new.html',
- './about.html',
- './login.html',
- './register.html',
- './reset-password.html',
- './reset-password-request.html',
- './auth-redirect.html',
- './debug-export.html',
-
- // Stylesheets (versioned)
- './style.css?v=20250119004',
- './styles.css?v=20250119001',
- './settings-styles.css?v=20250119001',
- './header-fix.css?v=20250119001',
- './mobile-header.css?v=20250119002',
-
- // JavaScript (versioned)
- './script.js?v=20250119002',
- './auth.js?v=20250119001',
- './settings-new.js?v=20250119001',
- './status.js?v=20250119001',
- './theme-loader.js?v=20250119001',
- './footer-fix.js?v=20251024001',
- './footer-content.js?v=20250119001',
- './include-auth-new.js?v=20250119001',
- './file-utils.js?v=20250119001',
- './fix-auth-buttons-loader.js?v=20250119001',
- './auth-redirect.js?v=20250119001',
- './mobile-menu.js?v=20250119002',
- './version-checker.js?v=20250119001',
-
- // i18n libraries and config (versioned)
- './js/i18n.js?v=20250119001',
- './js/lib/i18next.min.js?v=20250119001',
- './js/lib/i18nextHttpBackend.min.js?v=20250119001',
- './js/lib/i18nextBrowserLanguageDetector.min.js?v=20250119001',
-
- // Charts
- './chart.js?v=20250119001',
-
- // App manifest and icons
- './manifest.json',
- './favicon.ico',
- './img/favicon-16x16.png?v=2',
- './img/favicon-32x32.png?v=2',
- './img/favicon-512x512.png'
-];
-
-self.addEventListener('install', event => {
- event.waitUntil(
- caches.open(CACHE_NAME)
- .then(cache => {
- console.log('Opened cache');
- return cache.addAll(urlsToCache);
- })
- );
- // Activate the new service worker immediately after installation
- self.skipWaiting();
-});
-
-self.addEventListener('fetch', event => {
- if (event.request.method !== 'GET') {
- return;
- }
-
- const requestUrl = new URL(event.request.url);
-
- event.respondWith(
- caches.match(event.request).then(cachedResponse => {
- const fetchPromise = fetch(event.request)
- .then(networkResponse => {
- const isSameOrigin = requestUrl.origin === self.location.origin;
- const okToCache = isSameOrigin && networkResponse && networkResponse.status === 200 &&
- ['document', 'script', 'style', 'image', 'font'].includes(event.request.destination);
-
- if (okToCache) {
- const responseToCache = networkResponse.clone();
- caches.open(CACHE_NAME).then(cache => cache.put(event.request, responseToCache));
- }
- return networkResponse;
- })
- .catch(() => {
- if (cachedResponse) return cachedResponse;
- if (event.request.mode === 'navigate') {
- return caches.match('./index.html');
- }
- return Promise.reject(new Error('Network error and no cache.'));
- });
-
- return cachedResponse || fetchPromise;
- })
- );
-});
-
-self.addEventListener('activate', event => {
- const cacheWhitelist = [CACHE_NAME];
- event.waitUntil(
- caches.keys().then(cacheNames => {
- return Promise.all(
- cacheNames.map(cacheName => {
- if (cacheWhitelist.indexOf(cacheName) === -1) {
- return caches.delete(cacheName);
- }
- })
- );
- }).then(() => self.clients.claim())
- );
-});
\ No newline at end of file
diff --git a/frontend/src/theme-loader.js b/frontend/src/theme-loader.js
deleted file mode 100644
index 8f6d8dc..0000000
--- a/frontend/src/theme-loader.js
+++ /dev/null
@@ -1,48 +0,0 @@
-// theme-loader.js
-(function() {
- try {
- // Function to apply the theme directly to the root element
- function applyTheme(isDark) {
- const theme = isDark ? 'dark' : 'light';
- document.documentElement.setAttribute('data-theme', theme);
- // No need for console log in production loader script
- // console.log(`Theme applied on load: ${theme}`);
- }
-
- function getCookie(name) {
- const value = `; ${document.cookie}`;
- const parts = value.split(`; ${name}=`);
- if (parts.length === 2) return parts.pop().split(';').shift();
- return null;
- }
-
- // Default to light theme initially
- let isDarkMode = false;
-
- // Priority: cookie 'theme' -> localStorage 'darkMode' -> system preference
- const themeCookie = getCookie('theme');
- const savedTheme = localStorage.getItem('darkMode');
-
- if (themeCookie === 'dark' || themeCookie === 'light') {
- isDarkMode = themeCookie === 'dark';
- } else if (savedTheme !== null) {
- // Use the saved theme preference
- isDarkMode = savedTheme === 'true';
- } else {
- // Fallback to system preference if no theme saved in localStorage
- const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
- // console.log(`No saved theme found, falling back to system preference: ${prefersDarkMode ? 'dark' : 'light'}`);
- isDarkMode = prefersDarkMode;
- // Optionally, save the detected system preference as the initial setting for future loads
- // localStorage.setItem('darkMode', isDarkMode); // Consider if this is desired behavior
- }
-
- // Apply the determined theme
- applyTheme(isDarkMode);
-
- } catch (e) {
- console.error("Error applying theme from theme-loader.js:", e);
- // Fallback to light theme in case of error
- document.documentElement.setAttribute('data-theme', 'light');
- }
-})();
diff --git a/frontend/src/version-checker.js b/frontend/src/version-checker.js
deleted file mode 100644
index b1e5b78..0000000
--- a/frontend/src/version-checker.js
+++ /dev/null
@@ -1,82 +0,0 @@
-// Version checker for Warracker
-document.addEventListener('DOMContentLoaded', () => {
- const currentVersion = '1.0.3'; // Current version of the application
- const updateStatus = document.getElementById('updateStatus');
- const updateLink = document.getElementById('updateLink');
- const versionDisplay = document.getElementById('versionDisplay');
-
- // Function to compare versions
- function compareVersions(v1, v2) {
- const v1Parts = v1.split('.').map(Number);
- const v2Parts = v2.split('.').map(Number);
-
- for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
- const v1Part = v1Parts[i] || 0;
- const v2Part = v2Parts[i] || 0;
-
- if (v1Part > v2Part) return 1;
- if (v1Part < v2Part) return -1;
- }
- return 0;
- }
-
- // Function to check for updates
- async function checkForUpdates() {
- try {
- const response = await fetch('https://api.github.com/repos/sassanix/Warracker/releases/latest');
- if (!response.ok) throw new Error('Failed to fetch release information');
-
- const data = await response.json();
- const latestVersion = data.tag_name.replace('v', ''); // Remove 'v' prefix if present
-
- const comparison = compareVersions(latestVersion, currentVersion);
-
- if (comparison > 0) {
- // New version available
- if (window.i18next && window.i18next.t) {
- updateStatus.textContent = window.i18next.t('about.new_version_available', { version: data.tag_name });
- } else {
- updateStatus.textContent = `New version ${data.tag_name} available!`;
- }
- updateStatus.style.color = 'var(--success-color)';
- updateLink.href = data.html_url;
- updateLink.style.display = 'inline-block';
- } else {
- // Up to date
- if (window.i18next && window.i18next.t) {
- updateStatus.textContent = window.i18next.t('about.latest_version');
- } else {
- updateStatus.textContent = 'You are using the latest version';
- }
- updateStatus.style.color = 'var(--success-color)';
- }
- } catch (error) {
- console.error('Error checking for updates:', error);
- if (window.i18next && window.i18next.t) {
- updateStatus.textContent = window.i18next.t('about.update_check_failed');
- } else {
- updateStatus.textContent = 'Failed to check for updates';
- }
- updateStatus.style.color = 'var(--error-color)';
- }
- }
-
- // Update version display if element exists
- if (versionDisplay) {
- // Wait for i18next to be ready
- const updateVersionDisplay = () => {
- if (window.i18next && window.i18next.t) {
- versionDisplay.textContent = window.i18next.t('about.version') + ' v' + currentVersion;
- } else {
- versionDisplay.textContent = 'Version v' + currentVersion;
- }
- };
-
- // Try immediately and also after a delay for i18next
- updateVersionDisplay();
- setTimeout(updateVersionDisplay, 500);
- }
-
- // Check for updates when the page loads
- checkForUpdates();
-});
\ No newline at end of file