@ssgc/alert-console 2.2.7 → 2.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.es.js +1668 -1526
- package/dist/index.es.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),h=require("react"),c=require("antd"),Me=require("@ant-design/icons"),re=require("react-toastify");function ws(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const le=ws(h),Ns="#FF3B30",js="#FF9500",Cs="#FFCC00",Ts="#34C759",Le={critical:Ns,high:js,medium:Cs,low:Ts},wt={Critical:Le.critical,High:Le.high,Medium:Le.medium,Low:Le.low};function Is(e){return wt[e]||wt.Low}function Nt(e){if(!e||typeof e!="string")return 0;const t=e.trim().split(":");if(t.length!==3)return 0;const[s,r,i]=t,a=Number.parseInt(s,10),o=Number.parseInt(r,10),l=Number.parseFloat(i||"0"),f=Number.isFinite(a)?a:0,d=Number.isFinite(o)?o:0,u=Number.isFinite(l)?l:0;return f*3600+d*60+u}function Xe(e){const t=e.thirdPartyIds??e.ThirdPartyIds??e.thirdPartyId??e.ThirdPartyId??"",s=Array.isArray(t)?t.join(","):String(t??"");if(!s||!s.trim())return[];const r=s.split(",").map(o=>parseInt(String(o).trim(),10)).filter(o=>Number.isFinite(o)),i=new Set,a=[];return r.forEach(o=>{i.has(o)||(i.add(o),a.push(o))}),a}const Gt="",Rs=Gt,ks="",Os="",jt={snl:{alerts:Gt,rules:Rs},schools:{alerts:ks,rules:Os}};function ye(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Es(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function $e(e,t){if(!t)return e;const s=new URL(e);return Object.entries(t).forEach(([r,i])=>{i!=null&&String(i).length>0&&s.searchParams.set(r,String(i))}),s.toString()}async function ge(e,t){const s={...t.headers,...Es()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function Ps(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=ye(e.baseUrl,"/api/Alert"),r=await ge(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertStatusList(){const s=ye(e.baseUrl,"/api/Alert/AlertStatusList"),r=await ge(s,{method:"GET",headers:t});return Array.isArray(r)?r:r&&typeof r=="object"&&Array.isArray(r.data)?r.data:[]},async getAlertsReport(s){const r=ye(e.baseUrl,"/Alerts/GetAlertsReport"),i=$e(r,s),a=await ge(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=ye(e.baseUrl,"/api/Alert/status");return ge(r,{method:"PUT",headers:t,body:JSON.stringify(s??{})})},async getAdminSettings(){const s=ye(e.baseUrl,"/api/Alert/GetAdminSettings"),r=await ge(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("userId"in r)return r}return null},async setAdminSettings(s){const r=ye(e.baseUrl,"/api/Alert/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??"",groupBy:s?.groupBy??null};return ge(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=ye(e.baseUrl,"/api/Alert/GetPreferenceSettings"),r=await ge(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("anomalyIds"in r)return r}return null},async setPreferenceSettings(s){const r=ye(e.baseUrl,"/api/Alert/SetPreferenceSettings"),i=await ge(r,{method:"POST",headers:t,body:JSON.stringify(s??{})}),a=i?.responseStatus??!0,o=i?.data??i?.message??"Preferences updated successfully.";return{responseStatus:a,errorMessage:a?"":i?.errorMessage??i?.message??"",statusCode:200,data:o}},async getAlertNotifications(s){const r=ye(e.baseUrl,"/api/Alert/GetNotifications"),i=$e(r,{alertId:s}),a=await ge(i,{method:"GET",headers:t});return Array.isArray(a)?a:a&&typeof a=="object"&&Array.isArray(a.data)?a.data:[]},async notifyFamilyMembers(s){const r=ye(e.baseUrl,"/api/Alert/NotificationToFamilyMembers"),i=$e(r,{alertId:s});return ge(i,{method:"POST",headers:t})},async sendSMSorEmailNotifications(s,r,i){const a=ye(e.baseUrl,"/api/Alert/SendSMSorEmailNotifications"),o=$e(a,{alertId:s,isEmail:r,isSMS:i});return ge(o,{method:"POST",headers:t})}}}function Ct(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Ms(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Be(e,t){const s={...t.headers,...Ms()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function Ds(e){const t={"Content-Type":"application/json",...e.headers||{}},s=Ct(e.baseUrl,"/api/Rules"),r=Ct(e.baseUrl,"/api/Rules/lookups");return{async getRules(){const i=await Be(s,{method:"GET",headers:t});return Array.isArray(i)?i:[]},async setEscalationSettings(i){return Be(s,{method:"POST",headers:t,body:JSON.stringify(i??{})})},async getLookups(){return Be(r,{method:"GET",headers:t})},async updateRule(i,a){const o=`${s}/${i}`;return Be(o,{method:"PUT",headers:t,body:JSON.stringify(a??{})})}}}function Fs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var _e={exports:{}},Us=_e.exports,Tt;function Ls(){return Tt||(Tt=1,(function(e,t){(function(s,r){e.exports=r()})(Us,(function(){var s=1e3,r=6e4,i=36e5,a="millisecond",o="second",l="minute",f="hour",d="day",u="week",A="month",m="quarter",T="year",w="date",g="Invalid Date",S=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,L=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,D={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(R){var x=["th","st","nd","rd"],p=R%100;return"["+R+(x[(p-20)%10]||x[p]||x[0])+"]"}},$=function(R,x,p){var N=String(R);return!N||N.length>=x?R:""+Array(x+1-N.length).join(p)+R},F={s:$,z:function(R){var x=-R.utcOffset(),p=Math.abs(x),N=Math.floor(p/60),y=p%60;return(x<=0?"+":"-")+$(N,2,"0")+":"+$(y,2,"0")},m:function R(x,p){if(x.date()<p.date())return-R(p,x);var N=12*(p.year()-x.year())+(p.month()-x.month()),y=x.clone().add(N,A),v=p-y<0,b=x.clone().add(N+(v?-1:1),A);return+(-(N+(p-y)/(v?y-b:b-y))||0)},a:function(R){return R<0?Math.ceil(R)||0:Math.floor(R)},p:function(R){return{M:A,y:T,w:u,d,D:w,h:f,m:l,s:o,ms:a,Q:m}[R]||String(R||"").toLowerCase().replace(/s$/,"")},u:function(R){return R===void 0}},z="en",Y={};Y[z]=D;var G="$isDayjsObject",W=function(R){return R instanceof X||!(!R||!R[G])},C=function R(x,p,N){var y;if(!x)return z;if(typeof x=="string"){var v=x.toLowerCase();Y[v]&&(y=v),p&&(Y[v]=p,y=v);var b=x.split("-");if(!y&&b.length>1)return R(b[0])}else{var k=x.name;Y[k]=x,y=k}return!N&&y&&(z=y),y||!N&&z},j=function(R,x){if(W(R))return R.clone();var p=typeof x=="object"?x:{};return p.date=R,p.args=arguments,new X(p)},I=F;I.l=C,I.i=W,I.w=function(R,x){return j(R,{locale:x.$L,utc:x.$u,x:x.$x,$offset:x.$offset})};var X=(function(){function R(p){this.$L=C(p.locale,null,!0),this.parse(p),this.$x=this.$x||p.x||{},this[G]=!0}var x=R.prototype;return x.parse=function(p){this.$d=(function(N){var y=N.date,v=N.utc;if(y===null)return new Date(NaN);if(I.u(y))return new Date;if(y instanceof Date)return new Date(y);if(typeof y=="string"&&!/Z$/i.test(y)){var b=y.match(S);if(b){var k=b[2]-1||0,U=(b[7]||"0").substring(0,3);return v?new Date(Date.UTC(b[1],k,b[3]||1,b[4]||0,b[5]||0,b[6]||0,U)):new Date(b[1],k,b[3]||1,b[4]||0,b[5]||0,b[6]||0,U)}}return new Date(y)})(p),this.init()},x.init=function(){var p=this.$d;this.$y=p.getFullYear(),this.$M=p.getMonth(),this.$D=p.getDate(),this.$W=p.getDay(),this.$H=p.getHours(),this.$m=p.getMinutes(),this.$s=p.getSeconds(),this.$ms=p.getMilliseconds()},x.$utils=function(){return I},x.isValid=function(){return this.$d.toString()!==g},x.isSame=function(p,N){var y=j(p);return this.startOf(N)<=y&&y<=this.endOf(N)},x.isAfter=function(p,N){return j(p)<this.startOf(N)},x.isBefore=function(p,N){return this.endOf(N)<j(p)},x.$g=function(p,N,y){return I.u(p)?this[N]:this.set(y,p)},x.unix=function(){return Math.floor(this.valueOf()/1e3)},x.valueOf=function(){return this.$d.getTime()},x.startOf=function(p,N){var y=this,v=!!I.u(N)||N,b=I.p(p),k=function(ce,se){var ie=I.w(y.$u?Date.UTC(y.$y,se,ce):new Date(y.$y,se,ce),y);return v?ie:ie.endOf(d)},U=function(ce,se){return I.w(y.toDate()[ce].apply(y.toDate("s"),(v?[0,0,0,0]:[23,59,59,999]).slice(se)),y)},P=this.$W,B=this.$M,q=this.$D,K="set"+(this.$u?"UTC":"");switch(b){case T:return v?k(1,0):k(31,11);case A:return v?k(1,B):k(0,B+1);case u:var ne=this.$locale().weekStart||0,de=(P<ne?P+7:P)-ne;return k(v?q-de:q+(6-de),B);case d:case w:return U(K+"Hours",0);case f:return U(K+"Minutes",1);case l:return U(K+"Seconds",2);case o:return U(K+"Milliseconds",3);default:return this.clone()}},x.endOf=function(p){return this.startOf(p,!1)},x.$set=function(p,N){var y,v=I.p(p),b="set"+(this.$u?"UTC":""),k=(y={},y[d]=b+"Date",y[w]=b+"Date",y[A]=b+"Month",y[T]=b+"FullYear",y[f]=b+"Hours",y[l]=b+"Minutes",y[o]=b+"Seconds",y[a]=b+"Milliseconds",y)[v],U=v===d?this.$D+(N-this.$W):N;if(v===A||v===T){var P=this.clone().set(w,1);P.$d[k](U),P.init(),this.$d=P.set(w,Math.min(this.$D,P.daysInMonth())).$d}else k&&this.$d[k](U);return this.init(),this},x.set=function(p,N){return this.clone().$set(p,N)},x.get=function(p){return this[I.p(p)]()},x.add=function(p,N){var y,v=this;p=Number(p);var b=I.p(N),k=function(B){var q=j(v);return I.w(q.date(q.date()+Math.round(B*p)),v)};if(b===A)return this.set(A,this.$M+p);if(b===T)return this.set(T,this.$y+p);if(b===d)return k(1);if(b===u)return k(7);var U=(y={},y[l]=r,y[f]=i,y[o]=s,y)[b]||1,P=this.$d.getTime()+p*U;return I.w(P,this)},x.subtract=function(p,N){return this.add(-1*p,N)},x.format=function(p){var N=this,y=this.$locale();if(!this.isValid())return y.invalidDate||g;var v=p||"YYYY-MM-DDTHH:mm:ssZ",b=I.z(this),k=this.$H,U=this.$m,P=this.$M,B=y.weekdays,q=y.months,K=y.meridiem,ne=function(se,ie,me,pe){return se&&(se[ie]||se(N,v))||me[ie].slice(0,pe)},de=function(se){return I.s(k%12||12,se,"0")},ce=K||function(se,ie,me){var pe=se<12?"AM":"PM";return me?pe.toLowerCase():pe};return v.replace(L,(function(se,ie){return ie||(function(me){switch(me){case"YY":return String(N.$y).slice(-2);case"YYYY":return I.s(N.$y,4,"0");case"M":return P+1;case"MM":return I.s(P+1,2,"0");case"MMM":return ne(y.monthsShort,P,q,3);case"MMMM":return ne(q,P);case"D":return N.$D;case"DD":return I.s(N.$D,2,"0");case"d":return String(N.$W);case"dd":return ne(y.weekdaysMin,N.$W,B,2);case"ddd":return ne(y.weekdaysShort,N.$W,B,3);case"dddd":return B[N.$W];case"H":return String(k);case"HH":return I.s(k,2,"0");case"h":return de(1);case"hh":return de(2);case"a":return ce(k,U,!0);case"A":return ce(k,U,!1);case"m":return String(U);case"mm":return I.s(U,2,"0");case"s":return String(N.$s);case"ss":return I.s(N.$s,2,"0");case"SSS":return I.s(N.$ms,3,"0");case"Z":return b}return null})(se)||b.replace(":","")}))},x.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},x.diff=function(p,N,y){var v,b=this,k=I.p(N),U=j(p),P=(U.utcOffset()-this.utcOffset())*r,B=this-U,q=function(){return I.m(b,U)};switch(k){case T:v=q()/12;break;case A:v=q();break;case m:v=q()/3;break;case u:v=(B-P)/6048e5;break;case d:v=(B-P)/864e5;break;case f:v=B/i;break;case l:v=B/r;break;case o:v=B/s;break;default:v=B}return y?v:I.a(v)},x.daysInMonth=function(){return this.endOf(A).$D},x.$locale=function(){return Y[this.$L]},x.locale=function(p,N){if(!p)return this.$L;var y=this.clone(),v=C(p,N,!0);return v&&(y.$L=v),y},x.clone=function(){return I.w(this.$d,this)},x.toDate=function(){return new Date(this.valueOf())},x.toJSON=function(){return this.isValid()?this.toISOString():null},x.toISOString=function(){return this.$d.toISOString()},x.toString=function(){return this.$d.toUTCString()},R})(),Z=X.prototype;return j.prototype=Z,[["$ms",a],["$s",o],["$m",l],["$H",f],["$W",d],["$M",A],["$y",T],["$D",w]].forEach((function(R){Z[R[1]]=function(x){return this.$g(x,R[0],R[1])}})),j.extend=function(R,x){return R.$i||(R(x,X,j),R.$i=!0),j},j.locale=C,j.isDayjs=W,j.unix=function(R){return j(1e3*R)},j.en=Y[z],j.Ls=Y,j.p={},j}))})(_e)),_e.exports}var $s=Ls();const Wt=Fs($s);function Yt(e){if(!e)return"By Severity";const t=e.trim().toLowerCase();return t.includes("created")?"By Created Date":t.includes("updated")||t.includes("modified")?"By Updated Date":"By Severity"}function Kt(e){if(!e||typeof e!="string")return{hours:0,minutes:0,seconds:0};const t=e.split(":").map(a=>parseInt(a,10)),s=Number.isFinite(t[0])?t[0]:0,r=Number.isFinite(t[1])?t[1]:0,i=Number.isFinite(t[2])?t[2]:0;return{hours:s,minutes:r,seconds:i}}function It(e){const{hours:t,minutes:s,seconds:r}=Kt(e);return Wt().hour(t).minute(s).second(r).millisecond(0)}function Ae(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Bs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function Rt(e,t){if(!t)return e;const s=new URL(e);return Object.entries(t).forEach(([r,i])=>{i!=null&&String(i).length>0&&s.searchParams.set(r,String(i))}),s.toString()}async function we(e,t){const s={...t.headers,...Bs()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.Message||`HTTP ${r.status}`;throw new Error(o)}return a}const oe=(...e)=>e.find(t=>t!=null);function qs(e){return{id:String(oe(e?.AlertId,e?.alertId)??""),priority:oe(e?.Priority,e?.priority,"Low"),timestamp:oe(e?.Timestamp,e?.timestamp,""),statusType:oe(e?.Status,e?.statusType,""),description:oe(e?.Description,e?.description,""),eventName:oe(e?.EventName,e?.eventName),ruleName:oe(e?.RuleName,e?.ruleName),spaceName:oe(e?.SpaceName,e?.spaceName),assignTeam:oe(e?.AssignTeam,e?.assignTeam),cameraName:oe(e?.CameraName,e?.cameraName),type:oe(e?.Type,e?.type),mediaDetails:oe(e?.MediaDetails,e?.mediaDetails),additionalMedia:oe(e?.AdditionalMedia,e?.additionalMedia),timeElapsed:oe(e?.TimeElapsed,e?.timeElapsed),timeRemaining:oe(e?.TimeRemaining,e?.timeRemaining),anomalyName:oe(e?.AnomalyName,e?.anomalyName),alertDetails:oe(e?.AlertDetails,e?.alertDetails),statusHistory:oe(e?.StatusHistory,e?.statusHistory)}}function Qs(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=Ae(e.baseUrl,"/api/detectionpolicy/alerts?customerId=99e5c8b5-b9d4-4d35-8885-7f121c532664"),r=await we(s,{method:"GET",headers:t});return Array.isArray(r?.Items)?(r?.Items).map(qs):[]},async getAlertStatusList(){const s=Ae(e.baseUrl,"/api/detectionpolicy/alerts/StatusList"),r=await we(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertsReport(s){const r=Ae(e.baseUrl,"/api/detectionpolicy/alerts/GetAlertsReport"),i=Rt(r,s),a=await we(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=Ae(e.baseUrl,"/api/detectionpolicy/alerts/Log"),i={AlertId:s.alertId??s.alertUniqueId??s.AlertId,Status:s.status??s.Status??"",Notes:s.notes??s.Notes??""};return we(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getAdminSettings(){const s=Ae(e.baseUrl,"/api/detectionpolicy/alerts/GetAdminSettings"),r=await we(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("userId"in r)return r}return null},async setAdminSettings(s){const r=Ae(e.baseUrl,"/api/detectionpolicy/alerts/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??""};return we(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=Ae(e.baseUrl,"/api/detectionpolicy/alerts/GetPreferenceSettings"),r=await we(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("anomalyIds"in r)return r}return null},async setPreferenceSettings(s){const r=Ae(e.baseUrl,"/api/detectionpolicy/alerts/SetPreferenceSettings"),i=d=>{const{hours:u,minutes:A,seconds:m}=Kt(d);return(u*3600+A*60+m)*1e7},a={Settings:{UserId:0,AnomalyIds:Array.isArray(s?.anomalyIds)?s.anomalyIds.map(d=>String(d)):[],DoNotDisturbStart:{Ticks:i(s?.doNotDisturbStart)},DoNotDisturbEnd:{Ticks:i(s?.doNotDisturbEnd)},InApp:!!s?.inApp,SMS:!!s?.sms,Email:!!s?.email,SortBy:s?.sortBy??""}},o=await we(r,{method:"POST",headers:t,body:JSON.stringify(a)}),l=o?.responseStatus??!0,f=o?.data??o?.message??"Preferences updated successfully.";return{responseStatus:l,errorMessage:l?"":o?.errorMessage??o?.Message??o?.message??"",statusCode:200,data:f}},async getAlertNotifications(s){const r=Ae(e.baseUrl,"/api/detectionpolicy/alerts/GetNotifications"),i=Rt(r,{alertId:s}),a=await we(i,{method:"GET",headers:t});return Array.isArray(a)?a:a&&typeof a=="object"&&Array.isArray(a.data)?a.data:[]}}}function _s(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Ce(e,t){const s={...t.headers,..._s()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function Hs(e){const t={"Content-Type":"application/json",...e.headers||{}},s=new URL("/api/detectionpolicy/rules",e.baseUrl).toString();return{async getRules(){const r=await Ce(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async setEscalationSettings(r){return Ce(s,{method:"POST",headers:t,body:JSON.stringify(r??{})})},async getLookups(){const r=F=>new URL(F,e.baseUrl).toString(),i=[Ce(r("/api/detectionpolicy/lookups/actiontypes"),{method:"GET",headers:t}),Ce(r("/api/detectionpolicy/lookups/anomalies"),{method:"GET",headers:t}),Ce(r("/api/detectionpolicy/lookups/thirdparty"),{method:"GET",headers:t}),Ce(r("/api/detectionpolicy/lookups/severity"),{method:"GET",headers:t}),Ce(r("/api/detectionpolicy/lookups/scheduletypes"),{method:"GET",headers:t})],[a,o,l,f,d]=await Promise.allSettled(i),u=F=>F.status==="fulfilled"&&Array.isArray(F.value)?F.value:[],A=u(a),m=u(o),T=u(l),w=u(f),g=u(d),S=A.map(F=>({actionTypeId:Number(F?.ActionTypeId),name:F?.DisplayName??F?.Name??""})),L=m.map(F=>({recordId:F?.AnomalyId,anomalyName:F?.DisplayName??F?.Name??""})),D=T.map(F=>({thirdPartyId:Number(F?.ThirdPartyId),thirdPartyName:F?.ThirdPartyName??F?.Name??""})),$={actionTypes:S,anomalies:L,thirdParties:D};return w.length&&($.severities=w),g.length&&($.scheduleTypes=g),$},async updateRule(r,i){const a=`${s}/${r}`;return Ce(a,{method:"PUT",headers:t,body:JSON.stringify(i??{})})}}}const zt=h.createContext(null);function Vt({tenant:e="snl",override:t,children:s}){const r=h.useMemo(()=>{const a=t?.alertsBaseUrl?.trim()||jt[e]?.alerts||"";let o=t?.rulesBaseUrl?.trim()||jt[e]?.rules||"";e==="snl"&&(o=a);const l=t?.headers;return{tenant:e,alertsBaseUrl:a,rulesBaseUrl:o,headers:l}},[e,t?.alertsBaseUrl,t?.rulesBaseUrl,JSON.stringify(t?.headers||{})]),i=h.useMemo(()=>{const a=r.tenant==="schools"?Qs({baseUrl:r.alertsBaseUrl,headers:r.headers}):Ps({baseUrl:r.alertsBaseUrl,headers:r.headers}),o=r.tenant==="schools"?Hs({baseUrl:r.rulesBaseUrl,headers:r.headers}):Ds({baseUrl:r.alertsBaseUrl,headers:r.headers});return{config:r,alerts:a,rules:o}},[r]);return n.jsx(zt.Provider,{value:i,children:s})}function fe(){const e=h.useContext(zt);if(!e)throw new Error("useApi must be used inside ApiProvider");return e}const Gs={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Ws={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},lt=6,ct=7;function Ys(e,t,s){const r=e===lt,i=e===ct,a=t.isEmailSent,o=t.isSMSSent,l=r&&a||i&&o,f=r?"Send Email":i?"Send SMS":s,d=r&&a?"Email sent":i&&o?"SMS sent":f,u=r&&a?"Email sent":i&&o?"SMS sent":`Click to ${f}`;return{isDisabled:l,buttonText:d,tooltipTitle:u}}function Ks(e){const t=new Set;(e||[]).forEach(r=>{const i=r.anomalyName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All Types",value:"All"},...s]}function zs(e){const t=new Set;(e||[]).forEach(r=>{const i=r.spaceName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All",value:"All"},...s]}function kt(e,t){return`${e}-${t?"email":"sms"}`}function Ot(e){return e===lt||e===ct}function Ye({value:e,onChange:t,options:s,className:r,dropdownWidth:i}){return n.jsx(c.Select,{className:r,options:s,value:e,onChange:t,dropdownMatchSelectWidth:i??260})}const Vs=[{label:"All levels",value:"All"},{label:"Critical",value:"Critical"},{label:"High",value:"High"},{label:"Medium",value:"Medium"},{label:"Low",value:"Low"}];function Js({value:e,onChange:t,options:s}){return n.jsx(Ye,{className:"w-[140px]",value:e,onChange:t,options:s||Vs})}const Xs=[{label:"All Types",value:"All"},{label:"Weapon Detection",value:"Weapon"},{label:"Unauthorized Access",value:"Unauthorized"},{label:"Aggressive Behavior",value:"Aggressive"}];function Zs({value:e,onChange:t,options:s}){return n.jsx(Ye,{className:"w-[220px]",dropdownWidth:280,value:e,onChange:t,options:s||Xs})}function er({value:e,onChange:t,options:s}){return n.jsx(Ye,{className:"w-[100px]",value:e,onChange:t,options:s||[]})}const tr=[{label:"All",value:"All"},{label:"SOS",value:"SOS"},{label:"911",value:"911"},{label:"Aegix",value:"Aegix"},{label:"Eli",value:"Eli"},{label:"Skydio",value:"Skydio"}];function sr({value:e,onChange:t,options:s}){return n.jsx(Ye,{className:"w-[130px]",value:e,onChange:t,options:s||tr})}function Jt({columns:e,data:t,loading:s=!1,pageSize:r=10,rowKey:i="id",toolbar:a,tableProps:o}){return n.jsxs("div",{children:[a,n.jsx(c.Table,{rowKey:i,dataSource:t,columns:e,loading:s,pagination:{pageSize:r,showSizeChanger:!0,showTotal:l=>`Total: ${l}`},bordered:!0,...o})]})}function ut({data:e,loading:t=!1,pageSize:s=10,columns:r,severityOptions:i,spaceOptions:a,renderActions:o,onAlertIdClick:l,onRefetch:f,excludeCompleted:d=!0}){const[u,A]=h.useState("All"),[m,T]=h.useState("All"),[w,g]=h.useState("All"),[S,L]=h.useState("All"),[D,$]=h.useState(""),[F,z]=h.useState([{label:"All",value:"All"}]),[Y,G]=h.useState(new Set),{rules:W,alerts:C}=fe(),j={6:{title:"Email",kind:"icon",icon:n.jsx(Me.MailOutlined,{})},7:{title:"SMS",kind:"icon",icon:n.jsx(Me.MessageOutlined,{})}},I=h.useMemo(()=>Ks(e),[e]),X=h.useMemo(()=>zs(e),[e]);h.useEffect(()=>{let v=!0;return(async()=>{try{const b=await W.getLookups(),U=(Array.isArray(b.thirdParties)?b.thirdParties:[]).map(P=>({label:P.thirdPartyName,value:String(P.thirdPartyId)}));v&&z([{label:"All",value:"All"},...U])}catch(b){console.error("Error loading third party options",b)}})(),()=>{v=!1}},[W]);const Z=h.useMemo(()=>(e||[]).some(v=>Xe(v).length>0),[e]),R=h.useMemo(()=>(e||[]).filter(v=>{const b=u==="All"||v.priority===u,k=`${v.id} ${v.description} ${v.statusType}`.toLowerCase(),U=!D||k.includes(D.toLowerCase()),P=m==="All"||(v.anomalyName||"").toLowerCase()===m.toLowerCase(),B=w==="All"||(v.spaceName||"").toLowerCase()===w.toLowerCase(),q=!Z||S==="All"||Xe(v).includes(Number(S)),K=!d||!["completed","false positive"].includes(String(v.statusType||"").toLowerCase());return b&&U&&P&&B&&q&&K}),[e,u,D,m,w,S,Z,d]),x=I,p=a&&a.length?a:X,N=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:v=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${Ws[v]}`,backgroundColor:Gs[v]},children:v})},{title:"Tracker",key:"tracker",width:140,render:(v,b)=>n.jsx("a",{onClick:k=>{k.preventDefault(),l?.(b,{tab:"track",sourceTab:"active"})},className:"text-blue-600 hover:underline",children:"Tracker"})},{title:"Call to action/Human in the loop",key:"actions",width:320,render:(v,b)=>{if(o)return n.jsx(n.Fragment,{children:o(b)});const k=Xe(b);if(!k.length)return null;const U=async(P,B)=>{const q=kt(b.id,P);G(K=>new Set(K).add(q));try{const K=await C.sendSMSorEmailNotifications?.(b.id,P,B);K?.responseStatus?(re.toast.success(K.data||(P?"Email sent successfully":"SMS sent successfully")),f?.()):re.toast.error(K?.data||K?.errorMessage||"Failed to send notification")}catch(K){re.toast.error(K?.message||"Failed to send notification")}finally{G(K=>{const ne=new Set(K);return ne.delete(q),ne})}};return n.jsx(c.Space,{size:"middle",children:k.map(P=>{const B=j[P];if(!B)return null;const q=P===lt,K=P===ct,{isDisabled:ne,buttonText:de,tooltipTitle:ce}=Ys(P,b,B.title),se=kt(b.id,q),ie=Ot(P)&&Y.has(se),me=()=>{U(q,K)};return n.jsx(c.Tooltip,{title:ce,children:n.jsx(c.Button,{size:"small",disabled:ne,loading:ie,onClick:Ot(P)?me:void 0,icon:!ie&&(B.kind==="img"&&B.src?n.jsx("img",{src:B.src,alt:B.alt||B.title}):B.icon),className:"flex flex-col items-center justify-center gap-1",style:{height:"fit-content"},children:de})},P)})})}},{title:"Alert Timestamp",dataIndex:"timestamp",key:"timestamp",width:220,render:(v,b)=>{const k=b?.timeElapsed,U=b?.timeRemaining,P=k?Nt(k):0,B=U?Nt(U):0,q=Math.round(P/(P+B)*100);return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-[70px]",children:"Elapsed:"}),n.jsx("span",{className:"font-medium",children:k??"-"})]}),n.jsx(c.Progress,{percent:q,showInfo:!1,size:"small",strokeColor:Is(b.priority)}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-[70px]",children:"Remaining"}),n.jsx("span",{className:"font-medium",children:U??"-"})]})]})}},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(v,b)=>n.jsxs("div",{children:[n.jsx("a",{onClick:k=>{k.preventDefault(),l?.(b,{sourceTab:"active"})},className:"inline-block mb-1 text-blue-600",children:b.alertNumber}),n.jsx("div",{className:"text-black/65",children:v})]})}],y=r&&r.length?r:N;return n.jsx("div",{children:n.jsx(Jt,{rowKey:"id",data:R,columns:y,loading:t,pageSize:s,toolbar:n.jsxs(c.Row,{gutter:[12,12],className:"mb-3",align:"middle",children:[n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Severity"}),n.jsx(Js,{value:u,onChange:A,options:i})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Anomaly type"}),n.jsx(Zs,{value:m,onChange:T,options:x})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Space"}),n.jsx(er,{value:w,onChange:g,options:p})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Action Taken"}),n.jsx(sr,{value:S,onChange:L,options:F})]})}),n.jsx(c.Col,{flex:"auto"}),n.jsx(c.Col,{flex:"none",children:n.jsx(c.Input.Search,{allowClear:!0,placeholder:"Search",onSearch:$,onChange:v=>$(v.target.value),className:"w-[260px] ",enterButton:!0})})]})})})}var De=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},rr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nr=class{#e=rr;#t=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#t&&e!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:e}),this.#e=e,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},Re=new nr;function ir(e){setTimeout(e,0)}var ke=typeof window>"u"||"Deno"in globalThis;function ue(){}function ar(e,t){return typeof e=="function"?e(t):e}function et(e){return typeof e=="number"&&e>=0&&e!==1/0}function Xt(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Te(e,t){return typeof e=="function"?e(t):e}function he(e,t){return typeof e=="function"?e(t):e}function Et(e,t){const{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:l}=e;if(o){if(r){if(t.queryHash!==dt(o,t.options))return!1}else if(!Ue(t.queryKey,o))return!1}if(s!=="all"){const f=t.isActive();if(s==="active"&&!f||s==="inactive"&&f)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||i&&i!==t.state.fetchStatus||a&&!a(t))}function Pt(e,t){const{exact:s,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(s){if(Oe(t.options.mutationKey)!==Oe(a))return!1}else if(!Ue(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function dt(e,t){return(t?.queryKeyHashFn||Oe)(e)}function Oe(e){return JSON.stringify(e,(t,s)=>st(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}function Ue(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>Ue(e[s],t[s])):!1}var or=Object.prototype.hasOwnProperty;function tt(e,t,s=0){if(e===t)return e;if(s>500)return t;const r=Mt(e)&&Mt(t);if(!r&&!(st(e)&&st(t)))return t;const a=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),l=o.length,f=r?new Array(l):{};let d=0;for(let u=0;u<l;u++){const A=r?u:o[u],m=e[A],T=t[A];if(m===T){f[A]=m,(r?u<a:or.call(e,A))&&d++;continue}if(m===null||T===null||typeof m!="object"||typeof T!="object"){f[A]=T;continue}const w=tt(m,T,s+1);f[A]=w,w===m&&d++}return a===l&&d===a?e:f}function He(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function Mt(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function st(e){if(!Dt(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!Dt(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Dt(e){return Object.prototype.toString.call(e)==="[object Object]"}function lr(e){return new Promise(t=>{Re.setTimeout(t,e)})}function rt(e,t,s){if(typeof s.structuralSharing=="function")return s.structuralSharing(e,t);if(s.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return tt(e,t)}catch(r){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${s.queryHash}]: ${r}`),r}return tt(e,t)}return t}function cr(e,t,s=0){const r=[...e,t];return s&&r.length>s?r.slice(1):r}function ur(e,t,s=0){const r=[t,...e];return s&&r.length>s?r.slice(0,-1):r}var Ge=Symbol();function Zt(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===Ge&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ge?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ht(e,t){return typeof e=="function"?e(...t):!!e}function dr(e,t,s){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i)}),e}var hr=class extends De{#e;#t;#s;constructor(){super(),this.#s=e=>{if(!ke&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#s=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},ft=new hr;function nt(){let e,t;const s=new Promise((i,a)=>{e=i,t=a});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return s.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},s.reject=i=>{r({status:"rejected",reason:i}),t(i)},s}var fr=ir;function mr(){let e=[],t=0,s=l=>{l()},r=l=>{l()},i=fr;const a=l=>{t?e.push(l):i(()=>{s(l)})},o=()=>{const l=e;e=[],l.length&&i(()=>{r(()=>{l.forEach(f=>{s(f)})})})};return{batch:l=>{let f;t++;try{f=l()}finally{t--,t||o()}return f},batchCalls:l=>(...f)=>{a(()=>{l(...f)})},schedule:a,setNotifyFunction:l=>{s=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{i=l}}}var ae=mr(),pr=class extends De{#e=!0;#t;#s;constructor(){super(),this.#s=e=>{if(!ke&&window.addEventListener){const t=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#s=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(s=>{s(e)}))}isOnline(){return this.#e}},We=new pr;function yr(e){return Math.min(1e3*2**e,3e4)}function es(e){return(e??"online")==="online"?We.isOnline():!0}var it=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function ts(e){let t=!1,s=0,r;const i=nt(),a=()=>i.status!=="pending",o=g=>{if(!a()){const S=new it(g);m(S),e.onCancel?.(S)}},l=()=>{t=!0},f=()=>{t=!1},d=()=>ft.isFocused()&&(e.networkMode==="always"||We.isOnline())&&e.canRun(),u=()=>es(e.networkMode)&&e.canRun(),A=g=>{a()||(r?.(),i.resolve(g))},m=g=>{a()||(r?.(),i.reject(g))},T=()=>new Promise(g=>{r=S=>{(a()||d())&&g(S)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),w=()=>{if(a())return;let g;const S=s===0?e.initialPromise:void 0;try{g=S??e.fn()}catch(L){g=Promise.reject(L)}Promise.resolve(g).then(A).catch(L=>{if(a())return;const D=e.retry??(ke?0:3),$=e.retryDelay??yr,F=typeof $=="function"?$(s,L):$,z=D===!0||typeof D=="number"&&s<D||typeof D=="function"&&D(s,L);if(t||!z){m(L);return}s++,e.onFail?.(s,L),lr(F).then(()=>d()?void 0:T()).then(()=>{t?m(L):w()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:l,continueRetry:f,canStart:u,start:()=>(u()?w():T().then(w),i)}}var ss=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),et(this.gcTime)&&(this.#e=Re.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ke?1/0:300*1e3))}clearGcTimeout(){this.#e&&(Re.clearTimeout(this.#e),this.#e=void 0)}},gr=class extends ss{#e;#t;#s;#n;#r;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#n=e.client,this.#s=this.#n.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=Ut(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Ut(this.options);t.data!==void 0&&(this.setState(Ft(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const s=rt(this.state.data,e,this.options);return this.#i({data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(ue).catch(ue):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>he(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ge||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Te(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!Xt(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#o?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const l=this.observers.find(f=>f.options.queryFn);l&&this.setOptions(l.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const s=new AbortController,r=l=>{Object.defineProperty(l,"signal",{enumerable:!0,get:()=>(this.#o=!0,s.signal)})},i=()=>{const l=Zt(this.options,t),d=(()=>{const u={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(u),u})();return this.#o=!1,this.options.persister?this.options.persister(l,d,this):l(d)},o=(()=>{const l={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(l),l})();this.options.behavior?.onFetch(o,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#i({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=ts({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof it&&l.revert&&this.setState({...this.#t,fetchStatus:"idle"}),s.abort()},onFail:(l,f)=>{this.#i({type:"failed",failureCount:l,error:f})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0});try{const l=await this.#r.start();if(l===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(l),this.#s.config.onSuccess?.(l,this),this.#s.config.onSettled?.(l,this.state.error,this),l}catch(l){if(l instanceof it){if(l.silent)return this.#r.promise;if(l.revert){if(this.state.data===void 0)throw l;return this.state.data}}throw this.#i({type:"error",error:l}),this.#s.config.onError?.(l,this),this.#s.config.onSettled?.(this.state.data,l,this),l}finally{this.scheduleGc()}}#i(e){const t=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...rs(s.data,this.options),fetchMeta:e.meta??null};case"success":const r={...s,...Ft(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?r:void 0,r;case"error":const i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=t(this.state),ae.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function rs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:es(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Ft(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ut(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,r=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var vr=class extends De{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=nt(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#s=void 0;#n=void 0;#r;#a;#o;#i;#p;#h;#f;#c;#u;#l;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Lt(this.#t,this.options)?this.#d():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return at(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return at(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#b(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof he(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#A(),this.#t.setOptions(this.options),t._defaulted&&!He(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&$t(this.#t,s,this.options,t)&&this.#d(),this.updateResult(),r&&(this.#t!==s||he(this.options.enabled,this.#t)!==he(t.enabled,this.#t)||Te(this.options.staleTime,this.#t)!==Te(t.staleTime,this.#t))&&this.#y();const i=this.#g();r&&(this.#t!==s||he(this.options.enabled,this.#t)!==he(t.enabled,this.#t)||i!==this.#l)&&this.#v(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),s=this.createResult(t,e);return Sr(this,s)&&(this.#n=s,this.#a=this.options,this.#r=this.#t.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(s,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),s=this.#e.getQueryCache().build(this.#e,t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#d(e){this.#A();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(ue)),t}#y(){this.#S();const e=Te(this.options.staleTime,this.#t);if(ke||this.#n.isStale||!et(e))return;const s=Xt(this.#n.dataUpdatedAt,e)+1;this.#c=Re.setTimeout(()=>{this.#n.isStale||this.updateResult()},s)}#g(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#b(),this.#l=e,!(ke||he(this.options.enabled,this.#t)===!1||!et(this.#l)||this.#l===0)&&(this.#u=Re.setInterval(()=>{(this.options.refetchIntervalInBackground||ft.isFocused())&&this.#d()},this.#l))}#x(){this.#y(),this.#v(this.#g())}#S(){this.#c&&(Re.clearTimeout(this.#c),this.#c=void 0)}#b(){this.#u&&(Re.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const s=this.#t,r=this.options,i=this.#n,a=this.#r,o=this.#a,f=e!==s?e.state:this.#s,{state:d}=e;let u={...d},A=!1,m;if(t._optimisticResults){const W=this.hasListeners(),C=!W&&Lt(e,t),j=W&&$t(e,s,t,r);(C||j)&&(u={...u,...rs(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:T,errorUpdatedAt:w,status:g}=u;m=u.data;let S=!1;if(t.placeholderData!==void 0&&m===void 0&&g==="pending"){let W;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(W=i.data,S=!0):W=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,W!==void 0&&(g="success",m=rt(i?.data,W,t),A=!0)}if(t.select&&m!==void 0&&!S)if(i&&m===a?.data&&t.select===this.#p)m=this.#h;else try{this.#p=t.select,m=t.select(m),m=rt(i?.data,m,t),this.#h=m,this.#i=null}catch(W){this.#i=W}this.#i&&(T=this.#i,m=this.#h,w=Date.now(),g="error");const L=u.fetchStatus==="fetching",D=g==="pending",$=g==="error",F=D&&L,z=m!==void 0,G={status:g,fetchStatus:u.fetchStatus,isPending:D,isSuccess:g==="success",isError:$,isInitialLoading:F,isLoading:F,data:m,dataUpdatedAt:u.dataUpdatedAt,error:T,errorUpdatedAt:w,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:u.dataUpdateCount>0||u.errorUpdateCount>0,isFetchedAfterMount:u.dataUpdateCount>f.dataUpdateCount||u.errorUpdateCount>f.errorUpdateCount,isFetching:L,isRefetching:L&&!D,isLoadingError:$&&!z,isPaused:u.fetchStatus==="paused",isPlaceholderData:A,isRefetchError:$&&z,isStale:mt(e,t),refetch:this.refetch,promise:this.#o,isEnabled:he(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const W=G.data!==void 0,C=G.status==="error"&&!W,j=Z=>{C?Z.reject(G.error):W&&Z.resolve(G.data)},I=()=>{const Z=this.#o=G.promise=nt();j(Z)},X=this.#o;switch(X.status){case"pending":e.queryHash===s.queryHash&&j(X);break;case"fulfilled":(C||G.data!==X.value)&&I();break;case"rejected":(!C||G.error!==X.reason)&&I();break}}return G}updateResult(){const e=this.#n,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#a=this.options,this.#r.data!==void 0&&(this.#f=this.#t),He(t,e))return;this.#n=t;const s=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;const a=new Set(i??this.#m);return this.options.throwOnError&&a.add("error"),Object.keys(this.#n).some(o=>{const l=o;return this.#n[l]!==e[l]&&a.has(l)})};this.#w({listeners:s()})}#A(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#s=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#w(e){ae.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xr(e,t){return he(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Lt(e,t){return xr(e,t)||e.state.data!==void 0&&at(e,t,t.refetchOnMount)}function at(e,t,s){if(he(t.enabled,e)!==!1&&Te(t.staleTime,e)!=="static"){const r=typeof s=="function"?s(e):s;return r==="always"||r!==!1&&mt(e,t)}return!1}function $t(e,t,s,r){return(e!==t||he(r.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&mt(e,s)}function mt(e,t){return he(t.enabled,e)!==!1&&e.isStaleByTime(Te(t.staleTime,e))}function Sr(e,t){return!He(e.getCurrentResult(),t)}function Bt(e){return{onFetch:(t,s)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},f=0;const d=async()=>{let u=!1;const A=w=>{dr(w,()=>t.signal,()=>u=!0)},m=Zt(t.options,t.fetchOptions),T=async(w,g,S)=>{if(u)return Promise.reject();if(g==null&&w.pages.length)return Promise.resolve(w);const D=(()=>{const Y={client:t.client,queryKey:t.queryKey,pageParam:g,direction:S?"backward":"forward",meta:t.options.meta};return A(Y),Y})(),$=await m(D),{maxPages:F}=t.options,z=S?ur:cr;return{pages:z(w.pages,$,F),pageParams:z(w.pageParams,g,F)}};if(i&&a.length){const w=i==="backward",g=w?br:qt,S={pages:a,pageParams:o},L=g(r,S);l=await T(S,L,w)}else{const w=e??a.length;do{const g=f===0?o[0]??r.initialPageParam:qt(r,l);if(f>0&&g==null)break;l=await T(l,g),f++}while(f<w)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s):t.fetchFn=d}}}function qt(e,{pages:t,pageParams:s}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,s[r],s):void 0}function br(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}var Ar=class extends ss{#e;#t;#s;#n;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#s=e.mutationCache,this.#t=[],this.state=e.state||ns(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#r({type:"continue"})},s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#n=ts({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(a,o)=>{this.#r({type:"failed",failureCount:a,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#s.canRun(this)});const r=this.state.status==="pending",i=!this.#n.canStart();try{if(r)t();else{this.#r({type:"pending",variables:e,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(e,this,s);const o=await this.options.onMutate?.(e,s);o!==this.state.context&&this.#r({type:"pending",context:o,variables:e,isPaused:i})}const a=await this.#n.start();return await this.#s.config.onSuccess?.(a,e,this.state.context,this,s),await this.options.onSuccess?.(a,e,this.state.context,s),await this.#s.config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,e,this.state.context,s),this.#r({type:"success",data:a}),a}catch(a){try{await this.#s.config.onError?.(a,e,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,e,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,e,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#r({type:"error",error:a}),a}finally{this.#s.runNext(this)}}#r(e){const t=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),ae.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function ns(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var wr=class extends De{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(e,t,s){const r=new Ar({client:e,mutationCache:this,mutationId:++this.#s,options:e.defaultMutationOptions(t),state:s});return this.add(r),r}add(e){this.#e.add(e);const t=qe(e);if(typeof t=="string"){const s=this.#t.get(t);s?s.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=qe(e);if(typeof t=="string"){const s=this.#t.get(t);if(s)if(s.length>1){const r=s.indexOf(e);r!==-1&&s.splice(r,1)}else s[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=qe(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=qe(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){ae.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Pt(t,s))}findAll(e={}){return this.getAll().filter(t=>Pt(e,t))}notify(e){ae.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return ae.batch(()=>Promise.all(e.map(t=>t.continue().catch(ue))))}};function qe(e){return e.options.scope?.id}var Nr=class extends De{#e;#t=void 0;#s;#n;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#r()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#e.defaultMutationOptions(e),He(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&Oe(t.mutationKey)!==Oe(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(e){this.#r(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#r(),this.#a()}mutate(e,t){return this.#n=t,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(e)}#r(){const e=this.#s?.state??ns();this.#t={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#a(e){ae.batch(()=>{if(this.#n&&this.hasListeners()){const t=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#n.onSuccess?.(e.data,t,s,r)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(e.data,null,t,s,r)}catch(i){Promise.reject(i)}}else if(e?.type==="error"){try{this.#n.onError?.(e.error,t,s,r)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(void 0,e.error,t,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(t=>{t(this.#t)})})}},jr=class extends De{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,s){const r=t.queryKey,i=t.queryHash??dt(r,t);let a=this.get(i);return a||(a=new gr({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){ae.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Et(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Et(e,s)):t}notify(e){ae.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ae.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ae.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Cr=class{#e;#t;#s;#n;#r;#a;#o;#i;constructor(e={}){this.#e=e.queryCache||new jr,this.#t=e.mutationCache||new wr,this.#s=e.defaultOptions||{},this.#n=new Map,this.#r=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=ft.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=We.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),s=this.#e.build(this,t),r=s.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&s.isStaleByTime(Te(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:s})=>{const r=s.data;return[t,r]})}setQueryData(e,t,s){const r=this.defaultQueryOptions({queryKey:e}),a=this.#e.get(r.queryHash)?.state.data,o=ar(t,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return ae.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,s)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;ae.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#e;return ae.batch(()=>(s.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},r=ae.batch(()=>this.#e.findAll(e).map(i=>i.cancel(s)));return Promise.all(r).then(ue).catch(ue)}invalidateQueries(e,t={}){return ae.batch(()=>(this.#e.findAll(e).forEach(s=>{s.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const s={...t,cancelRefetch:t.cancelRefetch??!0},r=ae.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,s);return s.throwOnError||(a=a.catch(ue)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(ue)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#e.build(this,t);return s.isStaleByTime(Te(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(ue).catch(ue)}fetchInfiniteQuery(e){return e.behavior=Bt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(ue).catch(ue)}ensureInfiniteQueryData(e){return e.behavior=Bt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return We.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(e){this.#s=e}setQueryDefaults(e,t){this.#n.set(Oe(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(r=>{Ue(e,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(e,t){this.#r.set(Oe(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],s={};return t.forEach(r=>{Ue(e,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#s.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=dt(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ge&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#s.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},is=le.createContext(void 0),pt=e=>{const t=le.useContext(is);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Tr=({client:e,children:t})=>(le.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),n.jsx(is.Provider,{value:e,children:t})),as=le.createContext(!1),Ir=()=>le.useContext(as);as.Provider;function Rr(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var kr=le.createContext(Rr()),Or=()=>le.useContext(kr),Er=(e,t,s)=>{const r=s?.state.error&&typeof e.throwOnError=="function"?ht(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Pr=e=>{le.useEffect(()=>{e.clearReset()},[e])},Mr=({result:e,errorResetBoundary:t,throwOnError:s,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ht(s,[e.error,r])),Dr=e=>{if(e.suspense){const s=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Fr=(e,t)=>e.isLoading&&e.isFetching&&!t,Ur=(e,t)=>e?.suspense&&t.isPending,Qt=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function Lr(e,t,s){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=Ir(),i=Or(),a=pt(),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=a.getQueryCache().get(o.queryHash);process.env.NODE_ENV!=="production"&&(o.queryFn||console.error(`[${o.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),o._optimisticResults=r?"isRestoring":"optimistic",Dr(o),Er(o,i,l),Pr(i);const f=!a.getQueryCache().get(o.queryHash),[d]=le.useState(()=>new t(a,o)),u=d.getOptimisticResult(o),A=!r&&e.subscribed!==!1;if(le.useSyncExternalStore(le.useCallback(m=>{const T=A?d.subscribe(ae.batchCalls(m)):ue;return d.updateResult(),T},[d,A]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),le.useEffect(()=>{d.setOptions(o)},[o,d]),Ur(o,u))throw Qt(o,d,i);if(Mr({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw u.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!ke&&Fr(u,r)&&(f?Qt(o,d,i):l?.promise)?.catch(ue).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?u:d.trackResult(u)}function yt(e,t){return Lr(e,vr)}function $r(e,t){const s=pt(),[r]=le.useState(()=>new Nr(s,e));le.useEffect(()=>{r.setOptions(e)},[r,e]);const i=le.useSyncExternalStore(le.useCallback(o=>r.subscribe(ae.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=le.useCallback((o,l)=>{r.mutate(o,l).catch(ue)},[r]);if(i.error&&ht(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function gt(){const{alerts:e}=fe(),t=pt();return $r({mutationFn:s=>e.updateAlertStatus(s),onSuccess:()=>{t.invalidateQueries({queryKey:["alerts","list"]}),t.invalidateQueries({queryKey:["alerts","report"]})}})}function Br(e,t){return e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZone:t})}function qr(e,t){try{const i=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(e).find(o=>o.type==="timeZoneName")?.value;let a;try{const l=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"shortOffset"}).formatToParts(e).find(f=>f.type==="timeZoneName");l?.value&&l.value.startsWith("GMT")&&(a=l.value.replace("GMT",""))}catch{}return{abbr:i,offset:a}}catch{return{}}}function Qr(e){if(!e)return"-";try{const t=new Date(e),s=d=>String(d).padStart(2,"0"),r=s(t.getMonth()+1),i=s(t.getDate()),a=t.getFullYear(),o=s(t.getHours()),l=s(t.getMinutes()),f=s(t.getSeconds());return`${r}/${i}/${a} ${o}:${l}:${f}`}catch{return"-"}}function ot(e){if(!e)return"-";try{return new Date(e).toLocaleString("en-US",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return"-"}}const _r={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},Hr={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"};function os({alerts:e,loading:t=!1,pageSize:s=10,severityOptions:r,anomalyOptions:i,spaceOptions:a,onAlertIdClick:o}){const l=gt(),f=["completed","false positive"],d=async m=>{try{const T=await l.mutateAsync({alertUniqueId:m.alertId??m.id,alertId:m.id,status:"Reopen",notes:"Reopened",modifiedBy:0});if(T?.responseStatus){const w=T?.data||"Alert reopened successfully.";re.toast.success(w)}else{const w=T?.errorMessage||"Failed to reopen alert";re.toast.error(w)}}catch{re.toast.error("Failed to reopen alert. Please try again.")}},u=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:m=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${_r[m]}`,backgroundColor:Hr[String(m)]},children:m})},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:200,render:m=>Qr(m)},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(m,T)=>n.jsxs("div",{children:[n.jsx("a",{onClick:w=>{w.preventDefault(),o?.(T,{sourceTab:"archived"})},className:"inline-block mb-1 text-blue-600",children:T.alertNumber}),n.jsx("div",{className:"text-black/65",children:m})]})},{title:"",key:"menu",width:60,align:"right",render:(m,T)=>n.jsx(c.Dropdown,{trigger:["click"],menu:{items:[{key:"reopen",label:"Reopen"}],onClick:({key:w})=>{w==="reopen"&&d(T)}},children:n.jsx(c.Button,{type:"text",icon:n.jsx(Me.MoreOutlined,{})})})}],A=(e||[]).filter(m=>f.includes((m.statusType||"").toLowerCase()));return n.jsx(ut,{data:A,loading:t,pageSize:s,columns:u,severityOptions:r,anomalyOptions:i,spaceOptions:a,renderActions:void 0,onAlertIdClick:o,excludeCompleted:!1})}function Gr({size:e=120,time:t,timeZone:s="America/New_York"}){const{hours:r,minutes:i,seconds:a}=h.useMemo(()=>{const A=new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"numeric",second:"numeric",hour12:!1}).formatToParts(t);return{hours:parseInt(A.find(m=>m.type==="hour")?.value||"0",10),minutes:parseInt(A.find(m=>m.type==="minute")?.value||"0",10),seconds:parseInt(A.find(m=>m.type==="second")?.value||"0",10)}},[t,s]),o=a*6,l=i*6+a*.1,f=r%12*30+i*.5,d=e/2;return n.jsxs("div",{className:"relative rounded-full border border-gray-300 bg-white",style:{width:e,height:e},role:"img","aria-label":"Analog Clock",children:[[...Array(12)].map((u,A)=>{const m=A*30,T=6,w=d-4,g=w-T,S=(m-90)*(Math.PI/180),L=d+g*Math.cos(S),D=d+g*Math.sin(S),$=d+w*Math.cos(S),F=d+w*Math.sin(S);return n.jsx("svg",{className:"absolute inset-0",width:e,height:e,children:n.jsx("line",{x1:L,y1:D,x2:$,y2:F,stroke:"#9CA3AF",strokeWidth:A%3===0?2:1,strokeLinecap:"round"})},A)}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${f}deg)`},children:n.jsx("line",{x1:d,y1:d,x2:d,y2:d-e*.25,stroke:"#1F2937",strokeWidth:4,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${l}deg)`},children:n.jsx("line",{x1:d,y1:d,x2:d,y2:d-e*.35,stroke:"#374151",strokeWidth:3,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${o}deg)`},children:n.jsx("line",{x1:d,y1:d+e*.08,x2:d,y2:d-e*.38,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"})}),n.jsx("div",{className:"absolute bg-gray-900 rounded-full",style:{width:8,height:8,left:d-4,top:d-4}})]})}function ls({label:e="USA",timeZone:t="America/New_York",updateIntervalMs:s=1e3,className:r}){const[i,a]=h.useState(new Date);h.useEffect(()=>{const d=setInterval(()=>a(new Date),s);return()=>clearInterval(d)},[s]);const o=h.useMemo(()=>Br(i,t),[i,t]),{abbr:l,offset:f}=h.useMemo(()=>qr(i,t),[i,t]);return n.jsxs("div",{className:`flex items-center gap-3 ${r||""}`,children:[n.jsx(Gr,{time:i,timeZone:t,size:80}),n.jsxs("div",{className:"flex flex-col items-baseline gap-1",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[n.jsx("span",{className:"uppercase",children:e}),l&&n.jsx("span",{className:"px-1.5 py-0.5 rounded-md border text-[10px] leading-none text-gray-600 bg-gray-50",children:l}),f&&n.jsx("span",{className:"text-xs text-gray-500",children:f})]}),n.jsx("div",{className:"text-2xl font-semibold text-gray-700 tracking-wide",children:o})]})]})}const Wr=[{SeverityId:1,Code:"LOW",DisplayName:"Low",SortOrder:10,IsActive:!0},{SeverityId:2,Code:"MEDIUM",DisplayName:"Medium",SortOrder:20,IsActive:!0},{SeverityId:3,Code:"HIGH",DisplayName:"High",SortOrder:30,IsActive:!0},{SeverityId:4,Code:"CRITICAL",DisplayName:"Critical",SortOrder:40,IsActive:!0}],Yr=[{RuleId:"0938aa00-dfa7-4258-805a-67396366c776",RuleVersionId:"36d2d581-57c3-45c3-8705-8235935fdf96",Name:"License Plate Recognition",Description:"License Plate Recognition",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:3,AnomalyId:"915976ef-4eb6-4f7b-bbe6-e53862517fc9",Level:"global"},{RuleId:"2437286a-db6a-4d35-814e-9ac49f158dde",RuleVersionId:"00000000-0000-0000-0000-000000000000",Name:"Monitor And Track Onsite Vehicle timelog",Description:"Monitor And Track Onsite Vehicle timelog",VersionCount:0,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:3,AnomalyId:"9fd651ab-4312-4826-84b6-94d735894477",Level:"global"},{RuleId:"b99120ba-7a83-4ade-b5d9-a420550fe351",RuleVersionId:"d7b14dae-a7b1-474e-a357-199182c02ac3",Name:"Watchlist person detected",Description:"Watchlist person detected",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:4,AnomalyId:"bb3a3d3a-73a3-4f5a-8804-1baadbd0d412",Level:"global"},{RuleId:"ffc2c24f-adb7-4aba-ace7-f19c54e21530",RuleVersionId:"6ab3178f-bf77-4a1e-898d-1d5dbef749c5",Name:"Weapon Detection",Description:"Weapon Detection",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:4,AnomalyId:"ac82c3a2-72e6-4f9c-88fb-851a3ca3c4de",Level:"global"}],Kr=[{userRoleId:1,userRoleName:"Super Admin"},{userRoleId:2,userRoleName:"Security Officer"},{userRoleId:3,userRoleName:"Security Admin"},{userRoleId:4,userRoleName:"Regulatory Officer/First Responder"},{userRoleId:5,userRoleName:"User"}],Pe={severities:Wr,rules:Yr,userRoles:Kr},{Text:zr}=c.Typography;function Vr({sortBy:e,onChange:t,showActions:s,onSave:r,onClear:i,saving:a}){return n.jsxs(c.Row,{gutter:[16,16],align:"middle",children:[n.jsx(c.Col,{xs:24,md:8,lg:5,children:n.jsxs(c.Space,{className:"w-full items-center",direction:"horizontal",size:12,children:[n.jsx(zr,{className:"text-gray-600 whitespace-nowrap",children:"Sort By:"}),n.jsx(c.Select,{placeholder:"By Severity",value:e,onChange:o=>t({sortBy:o}),options:[{label:"By Severity",value:"By Severity"},{label:"By Created Date",value:"By Created Date"}],className:"w-full",style:{minWidth:"200px"}})]})}),n.jsx(c.Col,{xs:24,md:8,style:{alignSelf:"end"},children:s?n.jsxs(c.Space,{className:"w-full",direction:"horizontal",size:8,children:[n.jsx(c.Button,{onClick:i,disabled:a,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:r,loading:a,children:"Save"})]}):null})]})}const{Text:Ne}=c.Typography;function Jr(e){const{selectedRule:t,setSelectedRule:s,ruleOptions:r,minsOptions:i,roleOptions:a,l1mins:o,setL1mins:l,l1role:f,setL1role:d,l2mins:u,setL2mins:A,l2role:m,setL2role:T,l3mins:w,setL3mins:g,l3role:S,setL3role:L,actions:D,setActions:$,thirdPartyIds:F,setThirdPartyIds:z,humanLoop:Y,setHumanLoop:G,onClear:W,onSave:C,saving:j,onActionTypesLoaded:I}=e,{rules:X}=fe(),[Z,R]=h.useState([]),[x,p]=h.useState([]),[N,y]=h.useState(!1);h.useEffect(()=>{let k=!1;return(async()=>{try{y(!0);const U=await X.getLookups();if(k||!U||!Array.isArray(U.actionTypes))return;const P=U.actionTypes.map(q=>({label:q.name,value:String(q.actionTypeId)}));R(P),I&&I(U.actionTypes);const B=Array.isArray(U.thirdParties)?U.thirdParties.map(q=>({label:q.thirdPartyName,value:q.thirdPartyId})):[];p(B)}catch(U){console.error("Error loading lookups",U)}finally{k||y(!1)}})(),()=>{k=!0}},[]);const v=typeof o=="number"||typeof f=="number"||typeof u=="number"||typeof m=="number"||typeof w=="number"||typeof S=="number"||Array.isArray(D)&&D.length>0||Array.isArray(F)&&F.length>0||!!Y,b=!!t&&v&&!j;return n.jsxs(c.Spin,{spinning:!!j||N,children:[n.jsxs(c.Row,{gutter:[16,16],align:"bottom",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ne,{className:"text-gray-700 font-medium block mb-1",children:"Rules"}),n.jsx(c.Select,{placeholder:"Rules",value:t,onChange:s,options:r,className:"w-full"})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Ne,{className:"text-gray-700 font-medium block mb-1",children:"Level 1 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ne,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:o,onChange:l,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:f,onChange:d,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Ne,{className:"text-gray-700 font-medium block mb-1",children:"Level 2 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ne,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:u,onChange:A,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:m,onChange:T,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Ne,{className:"text-gray-700 font-medium block mb-1",children:"Level 3 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ne,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:w,onChange:g,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:S,onChange:L,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:5,children:n.jsxs("div",{children:[n.jsx(Ne,{className:"text-gray-700 font-medium block mb-1",children:"Pick Actions"}),n.jsx(c.Select,{mode:"multiple",placeholder:"Select response actions",className:"w-full",value:D,onChange:$,options:Z})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:3,children:n.jsx("div",{className:"flex items-end h-full",children:n.jsx(c.Checkbox,{checked:Y,onChange:k=>G(k.target.checked),children:"Human-In-The-Loop"})})})]}),n.jsxs(c.Row,{gutter:[16,16],align:"bottom",className:"mt-4",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:5,children:n.jsxs("div",{children:[n.jsx(Ne,{className:"text-gray-700 font-medium block mb-1",children:"Third Party App"}),n.jsx(c.Select,{mode:"multiple",placeholder:"Third Party app",className:"w-full",value:F,onChange:z,options:x})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(c.Button,{onClick:W,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:C,loading:!!j,disabled:!b,children:"Save"})]})})]})]})}function Xr({entries:e,userRoles:t,onEdit:s,loading:r}){const i=new Map(t.map(o=>[o.userRoleId,o.userRoleName])),a=o=>o.map(l=>i.get(l)||String(l)).join(", ");return n.jsx(c.Table,{rowKey:"id",dataSource:e,pagination:!1,loading:r,columns:[{title:"Rule",dataIndex:"ruleOrSeverityLabel",key:"rule"},{title:"Level 1",key:"l1",render:(o,l)=>n.jsxs("span",{children:[l.l1.minutes?`Action taken in (${l.l1.minutes} Mins)`:"No Action taken in 0 Min",l.l1.roles?.length?`, Escalate to (${a(l.l1.roles)})`:""]})},{title:"Level 2",key:"l2",render:(o,l)=>n.jsxs("span",{children:[l.l2.minutes?`Action taken in (${l.l2.minutes} Mins)`:"No Action taken in 0 Min",l.l2.roles?.length?`, Escalate to (${a(l.l2.roles)})`:""]})},{title:"Level 3",key:"l3",render:(o,l)=>n.jsxs("span",{children:[l.l3.minutes?`Action taken in (${l.l3.minutes} Mins)`:"No Action taken in 0 Min",l.l3.roles?.length?`, Escalate to (${a(l.l3.roles)})`:""]})},{title:"Pick Actions",key:"actionsCol",render:(o,l)=>l.actions&&l.actions.length?l.actions.join(", "):"-"},{title:"Notify",key:"notify",render:(o,l)=>l.notify&&l.notify.length?l.notify.join(", "):"-"},{title:"Human-In-The-Loop",key:"humanLoop",render:(o,l)=>l.humanLoop?"Yes":"No"},{title:"Actions",key:"ops",render:(o,l)=>n.jsx(c.Button,{type:"text",onClick:()=>s(l.id),children:n.jsx(Me.EditOutlined,{})})}]})}const{Title:Zr}=c.Typography;function cs({userRoles:e,rules:t,rawRules:s}){const{rules:r}=fe(),[i,a]=h.useState(!1),[o,l]=h.useState(s),[f,d]=h.useState({}),u=h.useMemo(()=>e.map(g=>({label:g.userRoleName,value:g.userRoleId})),[e]),A=h.useMemo(()=>(t||[]).map((g,S)=>({key:g.RuleId||g.Name||String(S),ruleName:g.Name||"-",ruleDesc:g.Description||""})),[t]);h.useEffect(()=>{let g=!1;return(async()=>{try{a(!0);const S=await r.getRules();g||(l(Array.isArray(S)?S:[]),d({}))}catch{!g&&Array.isArray(s)&&l(s)}finally{g||a(!1)}})(),()=>{g=!0}},[]),h.useEffect(()=>{!o&&Array.isArray(s)&&l(s)},[s]);const m=h.useMemo(()=>{if(!Array.isArray(o)||!o.length)return{};const g={};for(const S of A){const L=o.find($=>$?.ruleId===S.key||$?.ruleName===S.key||$?.RuleId===S.key||$?.ruleName===S.ruleName||$?.Name===S.ruleName),D=Array.isArray(L?.userRoleIds)?L.userRoleIds:[];D.length&&(g[S.key]=D)}return g},[o,A]),T=()=>{d({})},w=async()=>{try{if(!o||!Array.isArray(o)||Object.keys(f).length===0){re.toast.info("No changes to save");return}a(!0);const g=Object.entries(f).map(async([S,L])=>{const D=o.find(G=>G?.ruleId===S||G?.ruleName===S||G?.RuleId===S),$=typeof D?.recordId=="number"?D.recordId:void 0;if(!D||typeof $!="number")throw new Error(`Unable to find recordId for rule ${S}`);const F=Array.isArray(L)?L:[],z=F.map(G=>{const W=e.find(C=>C.userRoleId===G);return{id:G,name:W?.userRoleName??String(G)}}),Y={...D,ruleId:S,userRoleIds:F,userRoles:z,actions:[{actionTypeId:4,actionTypeUniqueId:"bc0973d4-9be0-4efb-8545-c9112ba06c1f",name:"Audible Warning",notificationType:"Alarm",category:"Hardware",description:"Test",isSystemDefined:!0,isActive:!0,displayOrder:0}]};return r.updateRule($,Y)});await Promise.all(g),re.toast.success("Alert assignment saved");try{const S=await r.getRules();l(Array.isArray(S)?S:[]),d({})}catch(S){console.error("Failed to refresh rules after save",S)}}catch(g){console.error("Failed to save alert assignment",g)}finally{a(!1)}};return n.jsxs("div",{className:"w-full",children:[n.jsx("div",{className:"flex items-center justify-between",children:n.jsx(Zr,{level:4,className:"!mb-4",children:"Alert Assignment"})}),n.jsx(c.Table,{rowKey:"key",dataSource:A,loading:i,pagination:!1,columns:[{title:"Rule Name",dataIndex:"ruleName",key:"ruleName"},{title:"Description",dataIndex:"ruleDesc",key:"ruleDesc"},{title:"Alert Notification To",key:"assign",render:(g,S)=>n.jsx(c.Select,{mode:"multiple",placeholder:"Dropdown with Multi select",className:"w-full",value:f[S.key]??m[S.key]??[],onChange:L=>d(D=>({...D,[S.key]:L})),options:u})}]}),n.jsxs(c.Space,{className:"mt-4",children:[n.jsx(c.Button,{onClick:T,disabled:i,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:w,loading:i,disabled:i||Object.keys(f).length===0,children:"Save"})]})]})}const{Title:_t}=c.Typography;function us({severities:e,rules:t,userRoles:s,rawRules:r,onSave:i}){const{rules:a,alerts:o}=fe(),[l,f]=h.useState("By Severity"),[d,u]=h.useState("By severity"),[A,m]=h.useState("By Severity"),[T,w]=h.useState(!1),[g,S]=h.useState(!1),[L,D]=h.useState(!1),[$,F]=h.useState(null),[z,Y]=h.useState("rules"),[G,W]=h.useState(),[C,j]=h.useState(),[I,X]=h.useState(),[Z,R]=h.useState(),[x,p]=h.useState(),[N,y]=h.useState(),[v,b]=h.useState(),[k,U]=h.useState(),[P,B]=h.useState([]),[q,K]=h.useState([]),[ne,de]=h.useState(!1),[ce,se]=h.useState({}),[ie,me]=h.useState({}),[pe,Ke]=h.useState(s||[]),[O,Q]=h.useState([]),[te,ve]=h.useState(!1),[Ee,Fe]=h.useState(!1),[xe,je]=h.useState(r||[]);h.useEffect(()=>{r&&r.length&&je(r)},[r]),h.useEffect(()=>{if(!xe||!xe.length)return;const E=Object.keys(ce).length>0||Object.keys(ie).length>0;if(O.length&&!E)return;const J=xe.map((_,M)=>{const V=t.find(be=>be.RuleId===(_.ruleId||_.ruleName))?.Name||_.ruleName||_.Name||"-",H=_.escalationSettings||{},ee=typeof H.level1UserRoleId=="number"&&H.level1UserRoleId>0?[H.level1UserRoleId]:[],Se=typeof H.level2UserRoleId=="number"&&H.level2UserRoleId>0?[H.level2UserRoleId]:[],Ve=typeof H.level3UserRoleId=="number"&&H.level3UserRoleId>0?[H.level3UserRoleId]:[],St=(Array.isArray(H.escalationSettingsActionTypeIds)?H.escalationSettingsActionTypeIds:[]).map(be=>ce[be]||String(be)),At=(Array.isArray(H.thirdPartyId)?H.thirdPartyId:[]).map(be=>ie[be]||String(be)),Je=typeof H.humanLoop=="boolean"?H.humanLoop:null;return{id:String(_.ruleId||_.ruleName||M),ruleOrSeverityLabel:V,l1:{minutes:H.level1PostAssistTime??void 0,roles:ee},l2:{minutes:H.level2PostAssistTime??void 0,roles:Se},l3:{minutes:H.level3PostAssistTime??void 0,roles:Ve},actions:St,notify:At,humanLoop:Je}});Q(J)},[xe,t,ce,ie]);const ze=h.useMemo(()=>e.map(E=>({label:E.DisplayName,value:E.SeverityId})),[e]),ps=h.useMemo(()=>t.map(E=>({label:E.Name,value:E.RuleId})),[t]),ys=h.useMemo(()=>pe.map(E=>({label:E.userRoleName,value:E.userRoleId})),[pe]),gs=h.useMemo(()=>[1,3,5,10,15,20,30,45,60].map(E=>({label:`${E}`,value:E})),[]);h.useEffect(()=>{let E=!1;async function J(){try{D(!0),F(null);const _=await o.getAdminSettings();if(!E&&_){const M=Yt(_.sortBy);f(M),m(M),w(!1)}}catch(_){if(!E){const M=_ instanceof Error?_.message:"Failed to load admin settings";F(M)}}finally{E||D(!1)}}return J(),()=>{E=!0}},[]),h.useEffect(()=>{if(!C)return;const E=V=>{const H=Number(V);return!isNaN(H)&&H>0?H:void 0},J=V=>{const H=Number(V);return!isNaN(H)&&H>0?H:void 0},M=(xe||[]).find(V=>V?.ruleId===C||V?.ruleName===C||V?.RuleId===C)?.escalationSettings;if(M&&typeof M=="object"){X(J(M.level1PostAssistTime)),R(E(M.level1UserRoleId)),p(J(M.level2PostAssistTime)),y(E(M.level2UserRoleId)),b(J(M.level3PostAssistTime)),U(E(M.level3UserRoleId));const V=Array.isArray(M.escalationSettingsActionTypeIds)?M.escalationSettingsActionTypeIds:[];B(V.map(H=>String(H))),K(Array.isArray(M.thirdPartyId)?M.thirdPartyId:[]),de(!!M.humanLoop)}},[z,C,xe]);const vs=async()=>{try{Fe(!0);const E=await a.getRules(),J=Array.isArray(E)?E:Array.isArray(E?.data)?E.data:[];je(J);const _=J.map((M,V)=>{const H=t.find(Ie=>Ie.RuleId===(M.ruleId||M.ruleName))?.Name||M.ruleName||M.Name||"-",ee=M.escalationSettings||{},Se=typeof ee.level1UserRoleId=="number"&&ee.level1UserRoleId>0?[ee.level1UserRoleId]:[],Ve=typeof ee.level2UserRoleId=="number"&&ee.level2UserRoleId>0?[ee.level2UserRoleId]:[],xt=typeof ee.level3UserRoleId=="number"&&ee.level3UserRoleId>0?[ee.level3UserRoleId]:[],bt=(Array.isArray(ee.escalationSettingsActionTypeIds)?ee.escalationSettingsActionTypeIds:[]).map(Ie=>ce[Ie]||String(Ie)),Je=(Array.isArray(ee.thirdPartyId)?ee.thirdPartyId:[]).map(Ie=>ie[Ie]||String(Ie)),be=typeof ee.humanLoop=="boolean"?ee.humanLoop:null;return{id:String(M.ruleId||M.ruleName||V),ruleOrSeverityLabel:H,l1:{minutes:ee.level1PostAssistTime??void 0,roles:Se},l2:{minutes:ee.level2PostAssistTime??void 0,roles:Ve},l3:{minutes:ee.level3PostAssistTime??void 0,roles:xt},actions:bt,notify:Je,humanLoop:be}});Q(_)}catch(E){console.error("Failed to refetch entries",E)}finally{Fe(!1)}};h.useEffect(()=>{let E=!1;return(async()=>{try{const J=await a.getLookups();if(E||!J)return;const _={};if(Array.isArray(J.thirdParties))for(const V of J.thirdParties)typeof V.thirdPartyId=="number"&&(_[V.thirdPartyId]=V.thirdPartyName);me(_);const M=Array.isArray(J.userRoles)?J.userRoles.map(V=>({userRoleId:V.userRoleId??V.id,userRoleName:V.userRoleName??V.name})):[];E||Ke(M.length?M:s||[])}catch(J){console.error("Error loading lookups",J)}})(),()=>{E=!0}},[]);const xs=async()=>{S(!0);try{const E=await o.setAdminSettings({sortBy:l,groupBy:"string"});E?.responseStatus&&E?.data&&re.toast.success(E.data),m(l),w(!1)}catch(E){console.error("Error saving admin settings",E)}finally{S(!1)}},Ss=()=>{f(A),w(!1)},bs=async()=>{ve(!0),i?.({ruleId:C,levels:[{minutes:I,role:Z},{minutes:x,role:N},{minutes:v,role:k}],actions:P,thirdPartyIds:q,humanLoop:ne});try{if(C){const _=Array.isArray(P)?P.map(Se=>Number(Se)):[],M=(xe||[]).find(Se=>Se?.ruleId===C||Se?.ruleName===C||Se?.RuleId===C),V=typeof M?.recordId=="number"?M.recordId:void 0;if(!M||typeof V!="number"){re.toast.error("Unable to find rule recordId for update");return}const H={...M,actions:[{actionTypeId:4,actionTypeUniqueId:"bc0973d4-9be0-4efb-8545-c9112ba06c1f",name:"Audible Warning",notificationType:"Alarm",category:"Hardware",description:"Test",isSystemDefined:!0,isActive:!0,displayOrder:0}],escalationSettings:{level1UserRoleId:Z??0,level1PostAssistTime:I??0,level2UserRoleId:N??0,level2PostAssistTime:x??0,level3UserRoleId:k??0,level3PostAssistTime:v??0,escalationSettingsActionTypeIds:_,thirdPartyId:Array.isArray(q)?q:[],humanLoop:ne}},ee=await a.updateRule(V,H);if(ee?.responseStatus||ee?.ok||ee){re.toast.success("Escalation settings saved"),await vs(),j(void 0),X(void 0),R(void 0),p(void 0),y(void 0),b(void 0),U(void 0),B([]),K([]),de(!1);return}}}catch(_){console.error("Error saving escalation settings",_)}finally{ve(!1)}const J=t.find(_=>_.RuleId===C)?.Name||"-";Q(_=>[..._,{id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ruleOrSeverityLabel:J,l1:{minutes:I,roles:Z?[Z]:[]},l2:{minutes:x,roles:N?[N]:[]},l3:{minutes:v,roles:k?[k]:[]},actions:(Array.isArray(P)?P:[]).map(M=>{const V=Number(M);return ce[V]||String(M)}),notify:(Array.isArray(q)?q:[]).map(M=>ie[M]||String(M)),humanLoop:!!ne}])},As=()=>{f("By Severity"),u("By severity"),Y("rules"),W(void 0),j(void 0),X(void 0),R(void 0),p(void 0),y(void 0),b(void 0),U(void 0),B([]),K([]),de(!1)};return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"mb-6",children:[n.jsx(_t,{level:4,className:"!mb-2",children:"Admin Settings"}),n.jsxs(c.Spin,{spinning:L,children:[$?n.jsxs("div",{className:"text-sm text-red-600 mb-2",children:["Failed to load settings: ",$]}):null,n.jsx(Vr,{sortBy:l,groupBy:d,onChange:E=>{E.sortBy&&(f(E.sortBy),w(!0)),E.groupBy&&(u(E.groupBy),w(!0))},showActions:T,onSave:xs,onClear:Ss,saving:g})]})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsxs("div",{children:[n.jsx(_t,{level:4,className:"!mb-4",children:"Escalation Settings"}),n.jsx(Jr,{escBasis:z,setEscBasis:Y,selectedSeverity:G,setSelectedSeverity:W,selectedRule:C,setSelectedRule:j,severityOptions:ze,ruleOptions:ps,minsOptions:gs,roleOptions:ys,l1mins:I,setL1mins:X,l1role:Z,setL1role:R,l2mins:x,setL2mins:p,l2role:N,setL2role:y,l3mins:v,setL3mins:b,l3role:k,setL3role:U,actions:P,setActions:B,thirdPartyIds:q,setThirdPartyIds:K,humanLoop:ne,setHumanLoop:de,onClear:As,onSave:bs,saving:te,onActionTypesLoaded:E=>{const J={};for(const _ of E)typeof _.actionTypeId=="number"&&(J[_.actionTypeId]=_.name);se(J)}})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(Xr,{entries:O,userRoles:pe,loading:Ee,onEdit:E=>{Y("rules");const J=O.find(M=>M.id===E),_=t.find(M=>M.RuleId===E)||(J?t.find(M=>M.Name===J.ruleOrSeverityLabel):void 0);j(_?_.RuleId:E)}}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(cs,{userRoles:pe,rules:t,rawRules:r}),n.jsx(c.Divider,{})]})}const{Title:Ht,Text:Qe}=c.Typography;function ds({severities:e,rules:t,onSave:s,onCancel:r}){const{rules:i,alerts:a}=fe(),o=[{label:"By Severity",value:"By Severity"},{label:"By Created Date",value:"By Created Date"}],[l,f]=h.useState("By Severity"),[d,u]=h.useState(new Set),[A,m]=h.useState(null),[T,w]=h.useState(null),[g,S]=h.useState({inApp:!1,sms:!1,email:!1}),[L,D]=h.useState([]),[$,F]=h.useState(!0),[z,Y]=h.useState(!1);h.useEffect(()=>{let C=!1;return(async()=>{try{const j=await a.getPreferenceSettings();if(C||!j)return;S({inApp:!!j.inApp,sms:!!j.sms,email:!!j.email});const I=Yt(j.sortBy);f(I==="By Created Date"?"By Created Date":"By Severity"),m(It(j.doNotDisturbStart)),w(It(j.doNotDisturbEnd)),Array.isArray(j.anomalyIds)&&u(new Set(j.anomalyIds.map(X=>String(X))))}catch(j){console.error("Error in loading my preferences: ",j)}})(),()=>{C=!0}},[]),h.useEffect(()=>{let C=!1;return(async()=>{try{F(!0);const j=await i.getLookups();if(C||!j)return;const I=Array.isArray(j.anomalies)?j.anomalies:[];D(I)}catch(j){console.error("Failed to load anomalies lookups",j)}finally{C||F(!1)}})(),()=>{C=!0}},[]);const G=C=>{u(j=>{const I=new Set(j);return I.has(C)?I.delete(C):I.add(C),I})},W=async()=>{s?.({sortBy:l,subscribedRuleIds:Array.from(d),dnd:{from:A,to:T},channels:g});try{Y(!0);const C=A?A.format?.("HH:mm:ss")??"00:00:00":"00:00:00",j=T?T.format?.("HH:mm:ss")??"00:00:00":"00:00:00",I=Array.from(d).map(Z=>Number(Z)).filter(Z=>Number.isFinite(Z)),X=await a.setPreferenceSettings({anomalyIds:I,doNotDisturbStart:C,doNotDisturbEnd:j,inApp:!!g.inApp,sms:!!g.sms,email:!!g.email,sortBy:l});X?.responseStatus&&re.toast.success(X?.data||"Preferences updated successfully.")}catch(C){console.error("Error in saving my preferences: ",C)}finally{Y(!1)}};return n.jsxs("div",{className:"w-full",children:[n.jsx(c.Row,{gutter:[16,16],align:"middle",className:"mb-4",children:n.jsx(c.Col,{xs:24,md:8,children:n.jsxs(c.Space,{direction:"horizontal",size:12,className:"w-full items-center",children:[n.jsx(Qe,{className:"text-gray-600",children:"Sort By:"}),n.jsx(c.Select,{className:"w-[240px]",value:l,options:o,onChange:f})]})})}),n.jsxs("div",{className:"mb-4",children:[n.jsx(Ht,{level:5,className:"!mb-2",children:"Anomalies"}),$?n.jsx("div",{className:"py-4",children:n.jsx(c.Spin,{})}):n.jsx(c.Space,{direction:"vertical",size:10,className:"w-full",children:(Array.isArray(L)?L:[]).map(C=>{const j=String(C.recordId),I=C.anomalyName;return n.jsx(c.Checkbox,{checked:d.has(j),onChange:()=>G(j),children:I},j)})})]}),n.jsxs("div",{className:"mb-4",children:[n.jsx(Ht,{level:5,className:"!mb-2",children:"Notification Timing & Channels"}),n.jsx(c.Row,{gutter:[16,16],align:"middle",className:"mb-3",children:n.jsx(c.Col,{xs:24,md:12,children:n.jsxs(c.Space,{direction:"horizontal",size:12,className:"w-full items-center",children:[n.jsx(Qe,{children:"Do Not Disturb mode:"}),n.jsxs(c.Space,{size:12,className:"w-full",children:[n.jsxs(c.Space,{direction:"horizontal",size:8,className:"items-center",children:[n.jsx(Qe,{children:"From"}),n.jsx(c.TimePicker,{value:A,onChange:C=>m(C),format:"HH:mm"})]}),n.jsxs(c.Space,{direction:"horizontal",size:8,className:"items-center",children:[n.jsx(Qe,{children:"To"}),n.jsx(c.TimePicker,{value:T,onChange:C=>w(C),format:"HH:mm"})]})]})]})})}),n.jsxs(c.Row,{gutter:[24,12],children:[n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:g.inApp,onChange:C=>S({...g,inApp:C.target.checked}),children:"In-app"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:g.sms,onChange:C=>S({...g,sms:C.target.checked}),children:"SMS"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:g.email,onChange:C=>S({...g,email:C.target.checked}),children:"Email"})})]})]}),n.jsx(c.Divider,{}),n.jsxs(c.Space,{className:"gap-3",children:[n.jsx(c.Button,{onClick:r,disabled:z,children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:W,loading:z,children:"Save"})]})]})}function hs({severities:e,rules:t,userRoles:s,rawRules:r}){const[i,a]=h.useState("global");return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"inline-flex rounded-xl overflow-hidden border border-gray-200 mb-4",children:[n.jsx("button",{onClick:()=>a("global"),className:`px-5 py-2 text-base font-medium outline-none ${i==="global"?" bg-black text-white":" bg-white text-black"}`,style:{border:"0"},children:"Global Settings"}),n.jsx("button",{onClick:()=>a("prefs"),className:`px-5 py-2 text-base font-medium outline-none ${i==="prefs"?"bg-black text-white":"bg-white"}`,children:"My Preferences"})]}),i==="global"?n.jsx(us,{severities:e,rules:t,userRoles:s,rawRules:r}):n.jsx(ds,{severities:e,rules:t})]})}const en="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAIZSURBVHgBnZW/b9NAFMe/z3H6i1ZNJUBFQsL/QQkLCFBtRhhKF1ibhBmpXbtgFlYqsTG0gRGWwgAjMb8EYmjYGN0pCCrVVaX+SBxf37PiqHWcOu5Xsux79+6j77vz3RH66IbdsDTQPCFngmBwqMCPBwVXoe204Fd/2ZfrSWMpHrDshtGCvsY9FlKkFNYD+Es/7EtuX+itp1sLnLrScTWoPMYsfnty/lUPtAOs4syiUgQOoWHJpG9kdBiX11Z+UaZCk1YT+vOzACuzYxgf7hZbyBGvhTi9af+7SkQbyKi7M8N4ZJ5D+eU2dg9UN07KvyNOS8io6UkNFXMMj1/vnACKAuTmNXZpIqME+LF+iIbX7ukjkClODWTQw+ujuGYMYfXzXnICbxSBDrxAUvYDhkrZp6ggUC8+sDI7mpj9YmESb3/uJ5Z9TJ5A3eORvzsBpgs6lufGT2TKPNY3fbxh6Knis0FTSjnx+LP3u5DJicDi/t7MCFadPaRJQTl02/5vKcKnpITluYkwrWjksebs48Pvg3SoUkXtq32hxt+1pITI8Zc/zcGACN59ty/WdWnklV5ukZ+49wU8MUJIF3mBGlqUr3Dv1+wpl20v9UuP75pElyrgc3XK7UJFbLvK4DJiv9ggDmWcjO9G4imWvW00yV/hjvtpOFnpQOVLkcO+0EhyevGrROG1ol1hREFc8ZGxyddIje+v9c4i9+gI5z7MozLxclgAAAAASUVORK5CYII=",tn="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAKeSURBVHgBjVVdbtpAEJ5ZmygPfTBSaVWpUt0bwFuURgJOUG5QeoLACbw+QeAEwA3SGxgJokh9CDeI+xSpTRU/Imw8nbFZx6QQGAl5d2fm229+dkDYI2f6oaUAOwhWExBcPnL4FwFBSLCexpCMf+qPi12++PKgpR/cGOwRa1pwQIjgOoWkf6s/hOVzVd588R+/xWjf5YAY8Y0+ErQrZFfnXg3lK3uGm7A+RISOxfbit5NprqBxxgBoeEIVHehqtI9lSz+5McaaITaA2J17bycFaBayMOS8IaT+zHuv4Ui58P9oAvB4Ga0paUgqbFGswL5idIcIx3P9DCiXrQB7iJawcTiCkMMIUlj7Jo8zr6Yv/EfRXXIqRnzUxnP9u46Id8Q5Sslq3+pqWErHAPKqvxROC/ZMuJwKJ8bkPouUkrYUqgt5IgMDKAxfAYT8nAZnmR2A5J47YSjrFKyOYpZN2SiIJ8YjRqVfASyAFVg9s2F2gXwRsClMXdnYcFpq5PyiQ8KEilaywc79+aEow2i7fdCF46SIpuTvCGi2kWSXjCM4QqS4Zl3yjwQ0UySwrBfGRJNjQKW4ZrmEpL45CxUDTGWdgmoZgxOoDA6zxYgr7ZudhWk3x6Sp4kl0nZmgujQhcH5Cvqy/Hxi5hdL+dgsWxR2rma4FkLeDw+PMM243+t2YB0jDDI9nMBquyWqI3tjmLYguQfqDzxebty/DIcnePr9jfePVfDhSzv2/Hs8LAY3kMmFfTCl+rl3uu1GWF6Jx+X3vkpa+58jeeNyXvY3Pd8N+a0hvgK9ge3hMTmG5CPTnSICWcFpXaDfZUcAck99yOnZM/id3hcmAFV/hgEilU6p0TcH2gpZYS98xc/kXUJ8YImPFzfeLh0cgXbMp8n/yD3ySPZSK0MWKAAAAAElFTkSuQmCC";function sn(e){const t=(e.status||"").toLowerCase()==="completed"?n.jsx("img",{src:en,alt:"completed",style:{width:20,height:20}}):n.jsx("img",{src:tn,alt:"pending",style:{width:20,height:20}});return{title:n.jsxs("div",{className:"flex flex-col gap-0 min-w-0",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("span",{className:"block text-sm break-words mb-1 overflow-visible whitespace-normal",children:n.jsx("b",{children:e.title})}),e.description?n.jsx("span",{className:"text-gray-500 text-xs",children:e.description}):null]}),e.timestamp?n.jsx("span",{className:"text-gray-500 text-xs",children:e.timestamp}):null]}),icon:t,description:null}}function rn({data:e}){return n.jsx("div",{className:"w-full",children:n.jsx(c.Tabs,{type:"card",items:[{key:"action",label:"Action Taken",children:n.jsxs("div",{className:"w-full",children:[n.jsx(c.Card,{className:"mb-4 rounded-md p-4",bordered:!0,children:n.jsxs("div",{className:"grid grid-cols-4 gap-6 text-xs",children:[n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Alert ID"}),n.jsx("span",{className:"text-black",children:e.summary.alertNumber})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Incident ID"}),n.jsx("span",{className:"text-black",children:e.summary.incidentId})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Severity"}),n.jsx("span",{className:"text-black",children:e.summary.severity})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Location"}),n.jsx("span",{className:"text-black",children:e.summary.location})]})]})}),n.jsxs(c.Card,{className:"rounded-md p-4",bordered:!0,children:[n.jsx("div",{className:"flex items-center justify-between",children:n.jsx("h4",{className:"text-sm text-black font-medium",children:"Response Timeline/ Audit trail/log"})}),n.jsx("div",{className:"mt-2",children:n.jsx(c.Steps,{direction:"vertical",size:"small",current:1,items:(e.timeline||[]).map(sn)})})]})]})},{key:"notification",label:"Notification Sent",children:n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(e.notifications||[]).map((t,s)=>n.jsxs(c.Card,{className:"rounded-md p-4",bordered:!0,children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("h4",{className:"text-sm text-black font-medium",children:t.channelLabel}),n.jsx("span",{className:"text-xs text-gray-500 mt-1",children:Wt(t.sentAt)?.format("MM/DD/YYYY HH:mm:ss")})]}),n.jsxs("span",{className:"text-[11px] px-2 py-1 rounded-full bg-green-50 text-green-700 border border-green-200",children:[t.delivered,"/",t.total," Delivered"]})]}),n.jsxs("div",{className:"mt-4 text-xs",children:[n.jsxs("div",{className:"text-black",children:[" ",t.messageTitle]}),t.messageBody?n.jsx("div",{className:"text-gray-600",children:t.messageBody}):null]}),n.jsxs("div",{className:"mt-4",children:[n.jsxs("div",{className:"text-xs text-black font-medium",children:["Recipients (",t.total,")"]}),n.jsx("div",{className:"mt-2 flex flex-col gap-3 text-xs",children:(t.recipients||[]).map((r,i)=>{const a=String(r?.notificationReceipientType||"").toLowerCase()==="EscalationNotification".toLowerCase();return n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsxs("span",{className:"text-black",children:[r.name," - ",n.jsx("span",{style:{color:a?"#FF3B30":"#FFB86A"},children:a?"Escalation Notification":"Alert Notification"})]}),n.jsxs("span",{className:"text-gray-500",children:[r.role," . ",r.phone]})]}),n.jsx("span",{className:`text-[11px] px-3 py-[2px] rounded ${r.status==="Delivered"?"bg-green-50 text-green-700 border border-green-200":"bg-red-50 text-red-700 border border-red-200"}`,children:r.status})]},i)})})]})]},s)),e?.notifications?.length?null:n.jsx("span",{className:"text-gray-500 text-xs",children:"No notifications."})]})}]})})}const nn=({alertId:e,id:t,priority:s,spaceName:r,alertNumber:i,statusHistory:a,notifGroups:o})=>{const l={alertId:e??String(t??""),incidentId:"-",severity:s||"",location:r||"",alertNumber:i??""},f=a?.length?a.map(u=>{const A=(u?.status||u?.eventStatus||"").toLowerCase()==="completed"?"Completed":"Inprogress",m=u?.createdDate?ot(u.createdDate):u?.timestamp?ot(u.timestamp):"";return{status:A,title:u?.status||u?.eventStatus||"Status Update",description:u?.description||u?.actionNotes||"",timestamp:m}}):[],d={summary:l,timeline:f,notifications:o??[]};return n.jsx(rn,{data:d})};function an(e){if(!e||typeof e!="string")return!1;const t=e.split("?")[0].toLowerCase();return t.endsWith(".mp4")||t.endsWith(".webm")||t.endsWith(".ogg")||t.endsWith(".m3u8")}function on(e){const t=(e?.mediaType||e?.type||"").toString().toLowerCase();return t==="video"||t==="mp4"?!0:an(e?.mediaUrl||e)}function Ze(e){const t=e;return t?Array.isArray(t)?t:[t]:[]}const ln={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},cn={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},un=({isModalOpen:e,handleModalClose:t,selectedRow:s,fetchAlertLogs:r,alertStatusList:i=[],alertStatusLoading:a=!1,initialTab:o="details",sourceTab:l})=>{const[f,d]=h.useState(),[u,A]=h.useState(""),[m,T]=h.useState(!1),w=h.useRef(null),[g,S]=h.useState("details"),[L,D]=h.useState(void 0),[$,F]=h.useState(!1),z=gt(),{alerts:Y,config:G}=fe(),W=G?.tenant==="schools",C=s?.originalData||{},{eventName:j,alertId:I,timestamp:X,description:Z,spaceName:R,assignTeam:x,priority:p,statusType:N,id:y,alertDetails:v,statusHistory:b,mediaDetails:k,alertNumber:U}=C,P=!W&&typeof C?.anomalyName=="string"&&String(C?.anomalyName||"").toLowerCase().includes("elopement"),B=O=>{const Q=String(O||"").toLowerCase();return Q==="delivered"?"Delivered":Q==="failed"?"Failed":"Queued"},q=O=>({name:O?.receipientName||O?.recipientName||"-",role:O?.receipientRoleName||"",phone:O?.receipentPhoneNumber||O?.recipientPhoneNumber||O?.receipientEmail||O?.recipientEmail||"",status:B(O?.messageStatus),notificationReceipientType:O?.notificationReceipientType||""}),K=(O,Q)=>{const te=Q.map(q),ve=te.filter(je=>je.status==="Delivered").length,Ee=Q.map(je=>je?.sentAt).filter(Boolean).sort((je,ze)=>new Date(ze).getTime()-new Date(je).getTime())[0],Fe=Q[0]||{},xe=[Fe?.severityName,Fe?.anomalyName].filter(Boolean).join(" - ")||`${O} Notification`;return{channelLabel:`${O} Notification`,sentAt:Ee||"",messageTitle:xe,messageBody:"",total:te.length,delivered:ve,recipients:te}},ne=O=>{const Q=new Map;return(O||[]).forEach(te=>{const ve=String(te?.notificationType||"Unknown"),Ee=Q.get(ve)||[];Ee.push(te),Q.set(ve,Ee)}),Array.from(Q.entries()).map(([te,ve])=>K(te,ve))},de=async O=>{try{const Q=await Y.getAlertNotifications(O),te=ne(Q);D(te)}catch{D(void 0)}};h.useEffect(()=>{if(g!=="track"||!y)return;let O=!1;return de(y).then(()=>{O&&D(void 0)}),()=>{O=!0}},[g,y]),h.useEffect(()=>{e&&S(o)},[e,o]);const se=l==="archived"||["completed","false positive"].includes(String(N||"").toLowerCase()),ie=O=>{const Q=String(O?.value||"").toLowerCase(),te=String(O?.statusName||"").toLowerCase();return Q.includes("reopen")||te.includes("reopen")},me=(i||[]).filter(O=>{const Q=ie(O);return typeof l<"u"?l==="archived"?Q:!Q:se?Q:!Q}).map(O=>({value:O.value,label:O.statusName})),pe=async()=>{try{T(!0);const O={alertUniqueId:I,alertId:y,status:f?String(f):void 0,notes:u.trim(),modifiedBy:0},Q=await z.mutateAsync(O);if(Q?.responseStatus){const te=Q?.data||"Alert updated successfully.";re.toast.success(te,{autoClose:1500,onClose:()=>{r(),t()}}),d(void 0),A("")}else{const te=Q?.errorMessage||"Failed to update alert status";re.toast.error(te)}}catch(O){console.error("Error updating alert status:",O),re.toast.error("Failed to update alert status. Please try again.")}finally{T(!1)}},Ke=async()=>{try{if(!y){re.toast.error("Alert ID is missing.");return}F(!0);const O=y;if(!Y.notifyFamilyMembers){re.toast.error("Notify Family is not supported.");return}const Q=await Y.notifyFamilyMembers(O);if(Q?.responseStatus){const te=Q?.data||"Alert Notifications sent to Family Members.";re.toast.success(te)}else{const te=Q?.errorMessage||"Failed to send notifications.";re.toast.error(te)}}catch(O){console.error("Error notifying family members:",O),re.toast.error("Failed to send notifications. Please try again.")}finally{F(!1)}};return n.jsx(c.Modal,{open:e,onCancel:t,width:1e3,styles:{body:{maxHeight:"70vh",overflowY:"auto"}},footer:g==="details"?n.jsxs("div",{className:"flex flex-row gap-2 justify-start",children:[n.jsx(c.Button,{onClick:t,className:"bg-[#6C757D] text-white",children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:pe,loading:m,children:m?"Saving...":"Save Changes"})]}):null,children:s&&n.jsx(c.Tabs,{activeKey:g,onChange:O=>S(O),items:[{key:"details",label:"Alert Detail",children:n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("div",{className:"text-sm font-bold",children:j||"Alert Event"}),v?.firstName?n.jsxs("div",{className:"text-sm text-gray-500",children:["Resident ID/Name: ",v?.firstName," ",v?.lastName||""," ",v?.residentId||""]}):null,n.jsxs("div",{className:"text-sm text-gray-500",children:["Timestamp: ",ot(X)]}),n.jsxs("div",{className:"font-sm text-gray-500",children:[n.jsx("b",{className:"text-black text-sm/6",children:"Description:"})," ",Z||"No description available"]}),R&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Space: ",R]}),x&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Assigned to: ",x]}),n.jsxs("div",{className:"flex gap-2 justify-start mt-3",children:[n.jsxs(c.Tag,{className:"font-sm text-gray-500 rounded-[8px] py-2 px-3",style:{border:`2px solid ${ln[String(p)]||"#DFE4EA"}`,backgroundColor:cn[String(p)]},children:["Severity: ",p||"N/A"]}),n.jsxs(c.Tag,{className:"font-sm text-gray-500 rounded-[8px] py-2 px-3",style:String(N||"").toLowerCase()==="completed"?{background:"#E7F6EC",border:"0.68px solid var(--Green, #34C759)"}:{background:"#E0EDFF",border:"1px solid var(--Grays-Gray-4, #D1D1D6)"},children:["Status: ",N||"N/A"]})]}),n.jsx("div",{className:"w-full flex flex-col justify-start items-start mt-2 font-bold",children:n.jsxs("div",{className:"w-full mt-4",children:[n.jsx("div",{className:"flex flex-col gap-2",children:n.jsx(c.Select,{placeholder:"Change Status",className:"w-full text-gray-500",onChange:O=>d(O),value:f,options:me,loading:a})}),n.jsxs("div",{className:"flex flex-col gap-2 mt-3",children:[n.jsx("label",{htmlFor:"action-details-input",className:"text-xs text-gray-500 font-medium",children:"Action Taken (Comments)"}),n.jsx("textarea",{id:"action-details-input",placeholder:"Enter details...",className:"w-full text-gray-500 h-20 border border-grey-500 rounded-md p-2",value:u,onChange:O=>A(O.target.value)})]}),P&&n.jsxs("div",{className:"border border-[#DFE4EA] rounded-md px-4 py-2 flex flex-row justify-between items-center mt-4 mb-8",children:[n.jsx("label",{htmlFor:"notify-family-button",className:"text-xs font-medium",children:"Alert notification will be sent to all Family Members."}),n.jsx(c.Button,{loading:$,onClick:Ke,disabled:$,className:"bg-black text-white rounded-md px-4 py-2 text-xs disabled:opacity-60 disabled:cursor-not-allowed",children:"Notify Family"})]})]})})]}),n.jsx("div",{className:"flex flex-col gap-4",children:n.jsxs("div",{className:"w-full mt-1",children:[n.jsxs("div",{className:"w-full flex items-center justify-between",children:[n.jsx("h3",{className:"text-black font-bold text-sm",children:"Camera Footage"}),Ze(k).length?n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>w.current?.prev?.(),className:"w-6 h-6 flex items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 text-gray-600","aria-label":"Previous media",children:n.jsx(Me.LeftOutlined,{style:{fontSize:12}})}),n.jsx("button",{type:"button",onClick:()=>w.current?.next?.(),className:"w-6 h-6 flex items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 text-gray-600","aria-label":"Next media",children:n.jsx(Me.RightOutlined,{style:{fontSize:12}})})]}):null]}),Ze(k).length?n.jsx("div",{className:"w-full",children:n.jsx(c.Carousel,{ref:w,dots:!0,className:"w-full",children:Ze(k).map((O,Q)=>n.jsxs("div",{className:"flex justify-center items-center",children:[on(O)?n.jsxs("video",{width:"240",height:"200",controls:!0,className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg",children:[n.jsx("source",{src:O.mediaUrl||O}),"Your browser does not support the video tag."]}):n.jsx("img",{src:O.mediaUrl||O,alt:O.caption||`media-${Q}`,className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg"}),O.caption&&n.jsx("p",{className:"text-xs text-gray-500 mt-1",children:O.caption})]},Q))})}):null]})})]})},{key:"track",label:"Track Incident",children:n.jsx(nn,{alertId:I,id:y,priority:p,spaceName:R,alertNumber:U,statusHistory:b,notifGroups:L})}]})})};function fs(){const{alerts:e}=fe(),t=yt({queryKey:["alerts","statusList"],queryFn:()=>e.getAlertStatusList(),staleTime:5*6e4});return{list:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function vt({alerts:e,loading:t=!1,columns:s,onRefetch:r}){const[i,a]=h.useState(!1),[o,l]=h.useState(null),[f,d]=h.useState("details"),{list:u,loading:A}=fs();function m(L,D){l(L),d(D?.tab??"details"),g(D?.sourceTab??"active"),a(!0)}function T(){a(!1)}const[w,g]=h.useState("active"),S=o?{originalData:{...o,alertId:o.alertId??o.id,mediaDetails:o.mediaDetails}}:null;return n.jsxs("div",{className:"p-6 flex flex-col items-start justify-start min-h-screen w-full overflow-auto",children:[n.jsxs("div",{className:"w-1/2 flex items-center justify-between mb-4",children:[n.jsx("h1",{className:"text-xl font-bold text-black",children:"Alert Console"}),n.jsx(ls,{label:"USA",timeZone:"America/New_York"})]}),n.jsx(c.Tabs,{defaultActiveKey:"active",className:"w-full",tabBarStyle:{fontSize:"medium"},onChange:L=>{L==="active"&&r?.()},items:[{key:"active",label:"Active",children:n.jsx(ut,{data:e,loading:t,pageSize:10,columns:s||[],onAlertIdClick:m,onRefetch:r})},{key:"archived",label:"Archived",children:n.jsx(os,{alerts:e,loading:t,columns:s||[],onAlertIdClick:m})},{key:"settings",label:"Settings",children:n.jsx(dn,{})}]}),n.jsx(un,{isModalOpen:i,handleModalClose:T,selectedRow:S,fetchAlertLogs:()=>{},alertStatusList:u,alertStatusLoading:A,initialTab:f,sourceTab:w})]})}function dn(){const[e,t]=h.useState([]),[s,r]=h.useState([]),[i,a]=h.useState([]),{rules:o}=fe();return h.useEffect(()=>{let l=!0;return(async()=>{try{const f=await o.getRules();if(!l)return;a(Array.isArray(f)?f:[]);const d=(f||[]).map((u,A)=>({RuleId:u.ruleId||u.ruleName||String(A),Name:u.ruleName||u.Name||"-",Description:u.ruleDesc||u.Description||"",SeverityId:0}));t(d.length?d:Pe.rules);try{const u=await o.getLookups(),A=Array.isArray(u?.userRoles)?u.userRoles.map(m=>({userRoleId:m.userRoleId??m.id,userRoleName:m.userRoleName??m.name})):[];r(A.length?A:Pe.userRoles)}catch{r(Pe.userRoles)}}catch{t(Pe.rules),r(Pe.userRoles)}})(),()=>{l=!1}},[]),n.jsx(hs,{severities:Pe.severities,rules:e,userRoles:s,rawRules:i})}function ms(){const{alerts:e}=fe(),t=yt({queryKey:["alerts","list"],queryFn:()=>e.listAlerts(),staleTime:3e4});return{alerts:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function hn(e){const{alerts:t,loading:s,refetch:r}=ms();return n.jsx(vt,{alerts:t,loading:s,columns:e.columns,onRefetch:r})}function fn({tenant:e,apiDomain:t,rulesDomain:s,headers:r,alerts:i,loading:a,columns:o}){const[l]=h.useState(()=>new Cr),f=h.useMemo(()=>({alertsBaseUrl:t,rulesBaseUrl:s||t,headers:r||void 0}),[t,s,r]);return n.jsx(Tr,{client:l,children:n.jsx(Vt,{tenant:e,override:f,children:Array.isArray(i)?n.jsx(vt,{alerts:i,loading:!!a,columns:o}):n.jsx(hn,{columns:o})})})}function mn(e){const{alerts:t}=fe(),s=yt({queryKey:["alerts","report",e],queryFn:()=>t.getAlertsReport(e),staleTime:6e4});return{data:s.data??[],loading:s.isLoading,error:s.error,refetch:s.refetch}}const pn=[{title:"ID",dataIndex:"id",key:"id",width:120},{title:"Priority",dataIndex:"priority",key:"priority",width:120},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:220},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description"}];exports.AlertAssignment=cs;exports.AlertConsole=vt;exports.AlertConsoleWidget=fn;exports.AlertsTable=ut;exports.ApiProvider=Vt;exports.ArchivedTable=os;exports.Clock=ls;exports.DataTable=Jt;exports.MyPreferencesPanel=ds;exports.SettingsPanel=us;exports.SettingsTabs=hs;exports.exampleAlertColumns=pn;exports.useAlertStatusList=fs;exports.useAlerts=ms;exports.useAlertsReport=mn;exports.useApi=fe;exports.useUpdateAlertStatus=gt;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),u=require("react"),c=require("antd"),De=require("@ant-design/icons"),he=require("react-toastify");function Ts(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const ce=Ts(u),Is="#FF3B30",Rs="#FF9500",ks="#FFCC00",Es="#34C759",Be={critical:Is,high:Rs,medium:ks,low:Es},Ct={Critical:Be.critical,High:Be.high,Medium:Be.medium,Low:Be.low};function Os(e){return Ct[e]||Ct.Low}function Tt(e){if(!e||typeof e!="string")return 0;const t=e.trim().split(":");if(t.length!==3)return 0;const[s,r,i]=t,a=Number.parseInt(s,10),o=Number.parseInt(r,10),l=Number.parseFloat(i||"0"),f=Number.isFinite(a)?a:0,h=Number.isFinite(o)?o:0,d=Number.isFinite(l)?l:0;return f*3600+h*60+d}function tt(e){const t=e.thirdPartyIds??e.ThirdPartyIds??e.thirdPartyId??e.ThirdPartyId??"",s=Array.isArray(t)?t.join(","):String(t??"");if(!s||!s.trim())return[];const r=s.split(",").map(o=>parseInt(String(o).trim(),10)).filter(o=>Number.isFinite(o)),i=new Set,a=[];return r.forEach(o=>{i.has(o)||(i.add(o),a.push(o))}),a}const zt="",Ms=zt,Ps="",Ds="",It={snl:{alerts:zt,rules:Ms},schools:{alerts:Ps,rules:Ds}};function xe(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Fs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function qe(e,t){if(!t)return e;const s=new URL(e);return Object.entries(t).forEach(([r,i])=>{i!=null&&String(i).length>0&&s.searchParams.set(r,String(i))}),s.toString()}async function be(e,t){const s={...t.headers,...Fs()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function Us(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=xe(e.baseUrl,"/api/Alert"),r=await be(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertStatusList(){const s=xe(e.baseUrl,"/api/Alert/AlertStatusList"),r=await be(s,{method:"GET",headers:t});return Array.isArray(r)?r:r&&typeof r=="object"&&Array.isArray(r.data)?r.data:[]},async getAlertsReport(s){const r=xe(e.baseUrl,"/Alerts/GetAlertsReport"),i=qe(r,s),a=await be(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=xe(e.baseUrl,"/api/Alert/status");return be(r,{method:"PUT",headers:t,body:JSON.stringify(s??{})})},async getAdminSettings(){const s=xe(e.baseUrl,"/api/Alert/GetAdminSettings"),r=await be(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("userId"in r)return r}return null},async setAdminSettings(s){const r=xe(e.baseUrl,"/api/Alert/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??"",groupBy:s?.groupBy??null};return be(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=xe(e.baseUrl,"/api/Alert/GetPreferenceSettings"),r=await be(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("anomalyIds"in r)return r}return null},async setPreferenceSettings(s){const r=xe(e.baseUrl,"/api/Alert/SetPreferenceSettings"),i=await be(r,{method:"POST",headers:t,body:JSON.stringify(s??{})}),a=i?.responseStatus??!0,o=i?.data??i?.message??"Preferences updated successfully.";return{responseStatus:a,errorMessage:a?"":i?.errorMessage??i?.message??"",statusCode:200,data:o}},async getAlertNotifications(s){const r=xe(e.baseUrl,"/api/Alert/GetNotifications"),i=qe(r,{alertId:s}),a=await be(i,{method:"GET",headers:t});return Array.isArray(a)?a:a&&typeof a=="object"&&Array.isArray(a.data)?a.data:[]},async notifyFamilyMembers(s){const r=xe(e.baseUrl,"/api/Alert/NotificationToFamilyMembers"),i=qe(r,{alertId:s});return be(i,{method:"POST",headers:t})},async sendSMSorEmailNotifications(s,r,i){const a=xe(e.baseUrl,"/api/Alert/SendSMSorEmailNotifications"),o=qe(a,{alertId:s,isEmail:r,isSMS:i});return be(o,{method:"POST",headers:t})}}}function Rt(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Ls(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function _e(e,t){const s={...t.headers,...Ls()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function $s(e){const t={"Content-Type":"application/json",...e.headers||{}},s=Rt(e.baseUrl,"/api/Rules"),r=Rt(e.baseUrl,"/api/Rules/lookups");return{async getRules(){const i=await _e(s,{method:"GET",headers:t});return Array.isArray(i)?i:[]},async setEscalationSettings(i){return _e(s,{method:"POST",headers:t,body:JSON.stringify(i??{})})},async getLookups(){return _e(r,{method:"GET",headers:t})},async updateRule(i,a){const o=`${s}/${i}`;return _e(o,{method:"PUT",headers:t,body:JSON.stringify(a??{})})}}}function Bs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ge={exports:{}},qs=Ge.exports,kt;function _s(){return kt||(kt=1,(function(e,t){(function(s,r){e.exports=r()})(qs,(function(){var s=1e3,r=6e4,i=36e5,a="millisecond",o="second",l="minute",f="hour",h="day",d="week",A="month",m="quarter",I="year",w="date",p="Invalid Date",S=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,L=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,F={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(E){var v=["th","st","nd","rd"],y=E%100;return"["+E+(v[(y-20)%10]||v[y]||v[0])+"]"}},$=function(E,v,y){var j=String(E);return!j||j.length>=v?E:""+Array(v+1-j.length).join(y)+E},U={s:$,z:function(E){var v=-E.utcOffset(),y=Math.abs(v),j=Math.floor(y/60),g=y%60;return(v<=0?"+":"-")+$(j,2,"0")+":"+$(g,2,"0")},m:function E(v,y){if(v.date()<y.date())return-E(y,v);var j=12*(y.year()-v.year())+(y.month()-v.month()),g=v.clone().add(j,A),x=y-g<0,b=v.clone().add(j+(x?-1:1),A);return+(-(j+(y-g)/(x?g-b:b-g))||0)},a:function(E){return E<0?Math.ceil(E)||0:Math.floor(E)},p:function(E){return{M:A,y:I,w:d,d:h,D:w,h:f,m:l,s:o,ms:a,Q:m}[E]||String(E||"").toLowerCase().replace(/s$/,"")},u:function(E){return E===void 0}},V="en",Y={};Y[V]=F;var G="$isDayjsObject",W=function(E){return E instanceof K||!(!E||!E[G])},T=function E(v,y,j){var g;if(!v)return V;if(typeof v=="string"){var x=v.toLowerCase();Y[x]&&(g=x),y&&(Y[x]=y,g=x);var b=v.split("-");if(!g&&b.length>1)return E(b[0])}else{var k=v.name;Y[k]=v,g=k}return!j&&g&&(V=g),g||!j&&V},C=function(E,v){if(W(E))return E.clone();var y=typeof v=="object"?v:{};return y.date=E,y.args=arguments,new K(y)},R=U;R.l=T,R.i=W,R.w=function(E,v){return C(E,{locale:v.$L,utc:v.$u,x:v.$x,$offset:v.$offset})};var K=(function(){function E(y){this.$L=T(y.locale,null,!0),this.parse(y),this.$x=this.$x||y.x||{},this[G]=!0}var v=E.prototype;return v.parse=function(y){this.$d=(function(j){var g=j.date,x=j.utc;if(g===null)return new Date(NaN);if(R.u(g))return new Date;if(g instanceof Date)return new Date(g);if(typeof g=="string"&&!/Z$/i.test(g)){var b=g.match(S);if(b){var k=b[2]-1||0,M=(b[7]||"0").substring(0,3);return x?new Date(Date.UTC(b[1],k,b[3]||1,b[4]||0,b[5]||0,b[6]||0,M)):new Date(b[1],k,b[3]||1,b[4]||0,b[5]||0,b[6]||0,M)}}return new Date(g)})(y),this.init()},v.init=function(){var y=this.$d;this.$y=y.getFullYear(),this.$M=y.getMonth(),this.$D=y.getDate(),this.$W=y.getDay(),this.$H=y.getHours(),this.$m=y.getMinutes(),this.$s=y.getSeconds(),this.$ms=y.getMilliseconds()},v.$utils=function(){return R},v.isValid=function(){return this.$d.toString()!==p},v.isSame=function(y,j){var g=C(y);return this.startOf(j)<=g&&g<=this.endOf(j)},v.isAfter=function(y,j){return C(y)<this.startOf(j)},v.isBefore=function(y,j){return this.endOf(j)<C(y)},v.$g=function(y,j,g){return R.u(y)?this[j]:this.set(g,y)},v.unix=function(){return Math.floor(this.valueOf()/1e3)},v.valueOf=function(){return this.$d.getTime()},v.startOf=function(y,j){var g=this,x=!!R.u(j)||j,b=R.p(y),k=function(le,re){var ie=R.w(g.$u?Date.UTC(g.$y,re,le):new Date(g.$y,re,le),g);return x?ie:ie.endOf(h)},M=function(le,re){return R.w(g.toDate()[le].apply(g.toDate("s"),(x?[0,0,0,0]:[23,59,59,999]).slice(re)),g)},O=this.$W,B=this.$M,q=this.$D,z="set"+(this.$u?"UTC":"");switch(b){case I:return x?k(1,0):k(31,11);case A:return x?k(1,B):k(0,B+1);case d:var ne=this.$locale().weekStart||0,fe=(O<ne?O+7:O)-ne;return k(x?q-fe:q+(6-fe),B);case h:case w:return M(z+"Hours",0);case f:return M(z+"Minutes",1);case l:return M(z+"Seconds",2);case o:return M(z+"Milliseconds",3);default:return this.clone()}},v.endOf=function(y){return this.startOf(y,!1)},v.$set=function(y,j){var g,x=R.p(y),b="set"+(this.$u?"UTC":""),k=(g={},g[h]=b+"Date",g[w]=b+"Date",g[A]=b+"Month",g[I]=b+"FullYear",g[f]=b+"Hours",g[l]=b+"Minutes",g[o]=b+"Seconds",g[a]=b+"Milliseconds",g)[x],M=x===h?this.$D+(j-this.$W):j;if(x===A||x===I){var O=this.clone().set(w,1);O.$d[k](M),O.init(),this.$d=O.set(w,Math.min(this.$D,O.daysInMonth())).$d}else k&&this.$d[k](M);return this.init(),this},v.set=function(y,j){return this.clone().$set(y,j)},v.get=function(y){return this[R.p(y)]()},v.add=function(y,j){var g,x=this;y=Number(y);var b=R.p(j),k=function(B){var q=C(x);return R.w(q.date(q.date()+Math.round(B*y)),x)};if(b===A)return this.set(A,this.$M+y);if(b===I)return this.set(I,this.$y+y);if(b===h)return k(1);if(b===d)return k(7);var M=(g={},g[l]=r,g[f]=i,g[o]=s,g)[b]||1,O=this.$d.getTime()+y*M;return R.w(O,this)},v.subtract=function(y,j){return this.add(-1*y,j)},v.format=function(y){var j=this,g=this.$locale();if(!this.isValid())return g.invalidDate||p;var x=y||"YYYY-MM-DDTHH:mm:ssZ",b=R.z(this),k=this.$H,M=this.$m,O=this.$M,B=g.weekdays,q=g.months,z=g.meridiem,ne=function(re,ie,Se,ge){return re&&(re[ie]||re(j,x))||Se[ie].slice(0,ge)},fe=function(re){return R.s(k%12||12,re,"0")},le=z||function(re,ie,Se){var ge=re<12?"AM":"PM";return Se?ge.toLowerCase():ge};return x.replace(L,(function(re,ie){return ie||(function(Se){switch(Se){case"YY":return String(j.$y).slice(-2);case"YYYY":return R.s(j.$y,4,"0");case"M":return O+1;case"MM":return R.s(O+1,2,"0");case"MMM":return ne(g.monthsShort,O,q,3);case"MMMM":return ne(q,O);case"D":return j.$D;case"DD":return R.s(j.$D,2,"0");case"d":return String(j.$W);case"dd":return ne(g.weekdaysMin,j.$W,B,2);case"ddd":return ne(g.weekdaysShort,j.$W,B,3);case"dddd":return B[j.$W];case"H":return String(k);case"HH":return R.s(k,2,"0");case"h":return fe(1);case"hh":return fe(2);case"a":return le(k,M,!0);case"A":return le(k,M,!1);case"m":return String(M);case"mm":return R.s(M,2,"0");case"s":return String(j.$s);case"ss":return R.s(j.$s,2,"0");case"SSS":return R.s(j.$ms,3,"0");case"Z":return b}return null})(re)||b.replace(":","")}))},v.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},v.diff=function(y,j,g){var x,b=this,k=R.p(j),M=C(y),O=(M.utcOffset()-this.utcOffset())*r,B=this-M,q=function(){return R.m(b,M)};switch(k){case I:x=q()/12;break;case A:x=q();break;case m:x=q()/3;break;case d:x=(B-O)/6048e5;break;case h:x=(B-O)/864e5;break;case f:x=B/i;break;case l:x=B/r;break;case o:x=B/s;break;default:x=B}return g?x:R.a(x)},v.daysInMonth=function(){return this.endOf(A).$D},v.$locale=function(){return Y[this.$L]},v.locale=function(y,j){if(!y)return this.$L;var g=this.clone(),x=T(y,j,!0);return x&&(g.$L=x),g},v.clone=function(){return R.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},E})(),ee=K.prototype;return C.prototype=ee,[["$ms",a],["$s",o],["$m",l],["$H",f],["$W",h],["$M",A],["$y",I],["$D",w]].forEach((function(E){ee[E[1]]=function(v){return this.$g(v,E[0],E[1])}})),C.extend=function(E,v){return E.$i||(E(v,K,C),E.$i=!0),C},C.locale=T,C.isDayjs=W,C.unix=function(E){return C(1e3*E)},C.en=Y[V],C.Ls=Y,C.p={},C}))})(Ge)),Ge.exports}var Qs=_s();const Vt=Bs(Qs);function Jt(e){if(!e)return"By Severity";const t=e.trim().toLowerCase();return t.includes("created")?"By Created Date":t.includes("updated")||t.includes("modified")?"By Updated Date":"By Severity"}function Zt(e){if(!e||typeof e!="string")return{hours:0,minutes:0,seconds:0};const t=e.split(":").map(a=>parseInt(a,10)),s=Number.isFinite(t[0])?t[0]:0,r=Number.isFinite(t[1])?t[1]:0,i=Number.isFinite(t[2])?t[2]:0;return{hours:s,minutes:r,seconds:i}}function Et(e){const{hours:t,minutes:s,seconds:r}=Zt(e);return Vt().hour(t).minute(s).second(r).millisecond(0)}function Ne(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Hs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function Ot(e,t){if(!t)return e;const s=new URL(e);return Object.entries(t).forEach(([r,i])=>{i!=null&&String(i).length>0&&s.searchParams.set(r,String(i))}),s.toString()}async function Ce(e,t){const s={...t.headers,...Hs()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.Message||`HTTP ${r.status}`;throw new Error(o)}return a}const oe=(...e)=>e.find(t=>t!=null);function Gs(e){return{id:String(oe(e?.AlertId,e?.alertId)??""),priority:oe(e?.Priority,e?.priority,"Low"),timestamp:oe(e?.Timestamp,e?.timestamp,""),statusType:oe(e?.Status,e?.statusType,""),description:oe(e?.Description,e?.description,""),eventName:oe(e?.EventName,e?.eventName),ruleName:oe(e?.RuleName,e?.ruleName),spaceName:oe(e?.SpaceName,e?.spaceName),assignTeam:oe(e?.AssignTeam,e?.assignTeam),cameraName:oe(e?.CameraName,e?.cameraName),type:oe(e?.Type,e?.type),mediaDetails:oe(e?.MediaDetails,e?.mediaDetails),additionalMedia:oe(e?.AdditionalMedia,e?.additionalMedia),timeElapsed:oe(e?.TimeElapsed,e?.timeElapsed),timeRemaining:oe(e?.TimeRemaining,e?.timeRemaining),anomalyName:oe(e?.AnomalyName,e?.anomalyName),alertDetails:oe(e?.AlertDetails,e?.alertDetails),statusHistory:oe(e?.StatusHistory,e?.statusHistory)}}function Ws(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=Ne(e.baseUrl,"/api/detectionpolicy/alerts?customerId=99e5c8b5-b9d4-4d35-8885-7f121c532664"),r=await Ce(s,{method:"GET",headers:t});return Array.isArray(r?.Items)?(r?.Items).map(Gs):[]},async getAlertStatusList(){const s=Ne(e.baseUrl,"/api/detectionpolicy/alerts/StatusList"),r=await Ce(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertsReport(s){const r=Ne(e.baseUrl,"/api/detectionpolicy/alerts/GetAlertsReport"),i=Ot(r,s),a=await Ce(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=Ne(e.baseUrl,"/api/detectionpolicy/alerts/Log"),i={AlertId:s.alertId??s.alertUniqueId??s.AlertId,Status:s.status??s.Status??"",Notes:s.notes??s.Notes??""};return Ce(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getAdminSettings(){const s=Ne(e.baseUrl,"/api/detectionpolicy/alerts/GetAdminSettings"),r=await Ce(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("userId"in r)return r}return null},async setAdminSettings(s){const r=Ne(e.baseUrl,"/api/detectionpolicy/alerts/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??""};return Ce(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=Ne(e.baseUrl,"/api/detectionpolicy/alerts/GetPreferenceSettings"),r=await Ce(s,{method:"GET",headers:t});if(r&&typeof r=="object"){if("data"in r)return r.data;if("anomalyIds"in r)return r}return null},async setPreferenceSettings(s){const r=Ne(e.baseUrl,"/api/detectionpolicy/alerts/SetPreferenceSettings"),i=h=>{const{hours:d,minutes:A,seconds:m}=Zt(h);return(d*3600+A*60+m)*1e7},a={Settings:{UserId:0,AnomalyIds:Array.isArray(s?.anomalyIds)?s.anomalyIds.map(h=>String(h)):[],DoNotDisturbStart:{Ticks:i(s?.doNotDisturbStart)},DoNotDisturbEnd:{Ticks:i(s?.doNotDisturbEnd)},InApp:!!s?.inApp,SMS:!!s?.sms,Email:!!s?.email,SortBy:s?.sortBy??""}},o=await Ce(r,{method:"POST",headers:t,body:JSON.stringify(a)}),l=o?.responseStatus??!0,f=o?.data??o?.message??"Preferences updated successfully.";return{responseStatus:l,errorMessage:l?"":o?.errorMessage??o?.Message??o?.message??"",statusCode:200,data:f}},async getAlertNotifications(s){const r=Ne(e.baseUrl,"/api/detectionpolicy/alerts/GetNotifications"),i=Ot(r,{alertId:s}),a=await Ce(i,{method:"GET",headers:t});return Array.isArray(a)?a:a&&typeof a=="object"&&Array.isArray(a.data)?a.data:[]}}}function Ks(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Ie(e,t){const s={...t.headers,...Ks()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function Ys(e){const t={"Content-Type":"application/json",...e.headers||{}},s=new URL("/api/detectionpolicy/rules",e.baseUrl).toString();return{async getRules(){const r=await Ie(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async setEscalationSettings(r){return Ie(s,{method:"POST",headers:t,body:JSON.stringify(r??{})})},async getLookups(){const r=U=>new URL(U,e.baseUrl).toString(),i=[Ie(r("/api/detectionpolicy/lookups/actiontypes"),{method:"GET",headers:t}),Ie(r("/api/detectionpolicy/lookups/anomalies"),{method:"GET",headers:t}),Ie(r("/api/detectionpolicy/lookups/thirdparty"),{method:"GET",headers:t}),Ie(r("/api/detectionpolicy/lookups/severity"),{method:"GET",headers:t}),Ie(r("/api/detectionpolicy/lookups/scheduletypes"),{method:"GET",headers:t})],[a,o,l,f,h]=await Promise.allSettled(i),d=U=>U.status==="fulfilled"&&Array.isArray(U.value)?U.value:[],A=d(a),m=d(o),I=d(l),w=d(f),p=d(h),S=A.map(U=>({actionTypeId:Number(U?.ActionTypeId),name:U?.DisplayName??U?.Name??""})),L=m.map(U=>({recordId:U?.AnomalyId,anomalyName:U?.DisplayName??U?.Name??""})),F=I.map(U=>({thirdPartyId:Number(U?.ThirdPartyId),thirdPartyName:U?.ThirdPartyName??U?.Name??""})),$={actionTypes:S,anomalies:L,thirdParties:F};return w.length&&($.severities=w),p.length&&($.scheduleTypes=p),$},async updateRule(r,i){const a=`${s}/${r}`;return Ie(a,{method:"PUT",headers:t,body:JSON.stringify(i??{})})}}}const Xt=u.createContext(null);function es({tenant:e="snl",override:t,children:s}){const r=u.useMemo(()=>{const a=t?.alertsBaseUrl?.trim()||It[e]?.alerts||"";let o=t?.rulesBaseUrl?.trim()||It[e]?.rules||"";e==="snl"&&(o=a);const l=t?.headers;return{tenant:e,alertsBaseUrl:a,rulesBaseUrl:o,headers:l}},[e,t?.alertsBaseUrl,t?.rulesBaseUrl,JSON.stringify(t?.headers||{})]),i=u.useMemo(()=>{const a=r.tenant==="schools"?Ws({baseUrl:r.alertsBaseUrl,headers:r.headers}):Us({baseUrl:r.alertsBaseUrl,headers:r.headers}),o=r.tenant==="schools"?Ys({baseUrl:r.rulesBaseUrl,headers:r.headers}):$s({baseUrl:r.alertsBaseUrl,headers:r.headers});return{config:r,alerts:a,rules:o}},[r]);return n.jsx(Xt.Provider,{value:i,children:s})}function ye(){const e=u.useContext(Xt);if(!e)throw new Error("useApi must be used inside ApiProvider");return e}const zs={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Vs={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},dt=6,ht=7;function Js(e,t,s){const r=e===dt,i=e===ht,a=t.isEmailSent,o=t.isSMSSent,l=r&&a||i&&o,f=r?"Send Email":i?"Send SMS":s,h=r&&a?"Email sent":i&&o?"SMS sent":f,d=r&&a?"Email sent":i&&o?"SMS sent":`Click to ${f}`;return{isDisabled:l,buttonText:h,tooltipTitle:d}}function Zs(e){const t=new Set;(e||[]).forEach(r=>{const i=r.anomalyName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All Types",value:"All"},...s]}function Xs(e){const t=new Set;(e||[]).forEach(r=>{const i=r.spaceName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All",value:"All"},...s]}function Mt(e,t){return`${e}-${t?"email":"sms"}`}function Pt(e){return e===dt||e===ht}function ze({value:e,onChange:t,options:s,className:r,dropdownWidth:i}){return n.jsx(c.Select,{className:r,options:s,value:e,onChange:t,dropdownMatchSelectWidth:i??260})}const er=[{label:"All levels",value:"All"},{label:"Critical",value:"Critical"},{label:"High",value:"High"},{label:"Medium",value:"Medium"},{label:"Low",value:"Low"}];function tr({value:e,onChange:t,options:s}){return n.jsx(ze,{className:"w-[140px]",value:e,onChange:t,options:s||er})}const sr=[{label:"All Types",value:"All"},{label:"Weapon Detection",value:"Weapon"},{label:"Unauthorized Access",value:"Unauthorized"},{label:"Aggressive Behavior",value:"Aggressive"}];function rr({value:e,onChange:t,options:s}){return n.jsx(ze,{className:"w-[220px]",dropdownWidth:280,value:e,onChange:t,options:s||sr})}function nr({value:e,onChange:t,options:s}){return n.jsx(ze,{className:"w-[100px]",value:e,onChange:t,options:s||[]})}const ir=[{label:"All",value:"All"},{label:"SOS",value:"SOS"},{label:"911",value:"911"},{label:"Aegix",value:"Aegix"},{label:"Eli",value:"Eli"},{label:"Skydio",value:"Skydio"}];function ar({value:e,onChange:t,options:s}){return n.jsx(ze,{className:"w-[130px]",value:e,onChange:t,options:s||ir})}function ts({columns:e,data:t,loading:s=!1,pageSize:r=10,rowKey:i="id",toolbar:a,tableProps:o}){return n.jsxs("div",{children:[a,n.jsx(c.Table,{rowKey:i,dataSource:t,columns:e,loading:s,pagination:{pageSize:r,showSizeChanger:!0,showTotal:l=>`Total: ${l}`},bordered:!0,...o})]})}function ft({data:e,loading:t=!1,pageSize:s=10,columns:r,severityOptions:i,spaceOptions:a,renderActions:o,onAlertIdClick:l,onRefetch:f,excludeCompleted:h=!0}){const[d,A]=u.useState("All"),[m,I]=u.useState("All"),[w,p]=u.useState("All"),[S,L]=u.useState("All"),[F,$]=u.useState(""),[U,V]=u.useState([{label:"All",value:"All"}]),[Y,G]=u.useState(new Set),{rules:W,alerts:T}=ye(),C={6:{title:"Email",kind:"icon",icon:n.jsx(De.MailOutlined,{})},7:{title:"SMS",kind:"icon",icon:n.jsx(De.MessageOutlined,{})}},R=u.useMemo(()=>Zs(e),[e]),K=u.useMemo(()=>Xs(e),[e]);u.useEffect(()=>{let x=!0;return(async()=>{try{const b=await W.getLookups(),M=(Array.isArray(b.thirdParties)?b.thirdParties:[]).map(O=>({label:O.thirdPartyName,value:String(O.thirdPartyId)}));x&&V([{label:"All",value:"All"},...M])}catch(b){console.error("Error loading third party options",b)}})(),()=>{x=!1}},[W]);const ee=u.useMemo(()=>(e||[]).some(x=>tt(x).length>0),[e]),E=u.useMemo(()=>(e||[]).filter(x=>{const b=d==="All"||x.priority===d,k=`${x.id} ${x.description} ${x.statusType}`.toLowerCase(),M=!F||k.includes(F.toLowerCase()),O=m==="All"||(x.anomalyName||"").toLowerCase()===m.toLowerCase(),B=w==="All"||(x.spaceName||"").toLowerCase()===w.toLowerCase(),q=!ee||S==="All"||tt(x).includes(Number(S)),z=!h||!["completed","false positive"].includes(String(x.statusType||"").toLowerCase());return b&&M&&O&&B&&q&&z}),[e,d,F,m,w,S,ee,h]),v=R,y=a&&a.length?a:K,j=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:x=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${Vs[x]}`,backgroundColor:zs[x]},children:x})},{title:"Tracker",key:"tracker",width:140,render:(x,b)=>n.jsx("a",{onClick:k=>{k.preventDefault(),l?.(b,{tab:"track",sourceTab:"active"})},className:"text-blue-600 hover:underline",children:"Tracker"})},{title:"Call to action/Human in the loop",key:"actions",width:320,render:(x,b)=>{if(o)return n.jsx(n.Fragment,{children:o(b)});const k=tt(b);if(!k.length)return null;const M=async(O,B)=>{const q=Mt(b.id,O);G(z=>new Set(z).add(q));try{const z=await T.sendSMSorEmailNotifications?.(b.id,O,B);z?.responseStatus?(he.toast.success(z.data||(O?"Email sent successfully":"SMS sent successfully")),f?.()):he.toast.error(z?.data||z?.errorMessage||"Failed to send notification")}catch(z){he.toast.error(z?.message||"Failed to send notification")}finally{G(z=>{const ne=new Set(z);return ne.delete(q),ne})}};return n.jsx(c.Space,{size:"middle",children:k.map(O=>{const B=C[O];if(!B)return null;const q=O===dt,z=O===ht,{isDisabled:ne,buttonText:fe,tooltipTitle:le}=Js(O,b,B.title),re=Mt(b.id,q),ie=Pt(O)&&Y.has(re),Se=()=>{M(q,z)};return n.jsx(c.Tooltip,{title:le,children:n.jsx(c.Button,{size:"small",disabled:ne,loading:ie,onClick:Pt(O)?Se:void 0,icon:!ie&&(B.kind==="img"&&B.src?n.jsx("img",{src:B.src,alt:B.alt||B.title}):B.icon),className:"flex flex-col items-center justify-center gap-1",style:{height:"fit-content"},children:fe})},O)})})}},{title:"Alert Timestamp",dataIndex:"timestamp",key:"timestamp",width:220,render:(x,b)=>{const k=b?.timeElapsed,M=b?.timeRemaining,O=k?Tt(k):0,B=M?Tt(M):0,q=Math.round(O/(O+B)*100);return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-[70px]",children:"Elapsed:"}),n.jsx("span",{className:"font-medium",children:k??"-"})]}),n.jsx(c.Progress,{percent:q,showInfo:!1,size:"small",strokeColor:Os(b.priority)}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"w-[70px]",children:"Remaining"}),n.jsx("span",{className:"font-medium",children:M??"-"})]})]})}},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(x,b)=>n.jsxs("div",{children:[n.jsx("a",{onClick:k=>{k.preventDefault(),l?.(b,{sourceTab:"active"})},className:"inline-block mb-1 text-blue-600",children:b.alertNumber}),n.jsx("div",{className:"text-black/65",children:x})]})}],g=r&&r.length?r:j;return n.jsx("div",{children:n.jsx(ts,{rowKey:"id",data:E,columns:g,loading:t,pageSize:s,toolbar:n.jsxs(c.Row,{gutter:[12,12],className:"mb-3",align:"middle",children:[n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Severity"}),n.jsx(tr,{value:d,onChange:A,options:i})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Anomaly type"}),n.jsx(rr,{value:m,onChange:I,options:v})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Space"}),n.jsx(nr,{value:w,onChange:p,options:y})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Action Taken"}),n.jsx(ar,{value:S,onChange:L,options:U})]})}),n.jsx(c.Col,{flex:"auto"}),n.jsx(c.Col,{flex:"none",children:n.jsx(c.Input.Search,{allowClear:!0,placeholder:"Search",onSearch:$,onChange:x=>$(x.target.value),className:"w-[260px] ",enterButton:!0})})]})})})}var Fe=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},or={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},lr=class{#e=or;#t=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#t&&e!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:e}),this.#e=e,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},Ee=new lr;function cr(e){setTimeout(e,0)}var Oe=typeof window>"u"||"Deno"in globalThis;function de(){}function ur(e,t){return typeof e=="function"?e(t):e}function rt(e){return typeof e=="number"&&e>=0&&e!==1/0}function ss(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Re(e,t){return typeof e=="function"?e(t):e}function pe(e,t){return typeof e=="function"?e(t):e}function Dt(e,t){const{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:l}=e;if(o){if(r){if(t.queryHash!==mt(o,t.options))return!1}else if(!Le(t.queryKey,o))return!1}if(s!=="all"){const f=t.isActive();if(s==="active"&&!f||s==="inactive"&&f)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||i&&i!==t.state.fetchStatus||a&&!a(t))}function Ft(e,t){const{exact:s,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(s){if(Me(t.options.mutationKey)!==Me(a))return!1}else if(!Le(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function mt(e,t){return(t?.queryKeyHashFn||Me)(e)}function Me(e){return JSON.stringify(e,(t,s)=>it(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}function Le(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>Le(e[s],t[s])):!1}var dr=Object.prototype.hasOwnProperty;function nt(e,t,s=0){if(e===t)return e;if(s>500)return t;const r=Ut(e)&&Ut(t);if(!r&&!(it(e)&&it(t)))return t;const a=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),l=o.length,f=r?new Array(l):{};let h=0;for(let d=0;d<l;d++){const A=r?d:o[d],m=e[A],I=t[A];if(m===I){f[A]=m,(r?d<a:dr.call(e,A))&&h++;continue}if(m===null||I===null||typeof m!="object"||typeof I!="object"){f[A]=I;continue}const w=nt(m,I,s+1);f[A]=w,w===m&&h++}return a===l&&h===a?e:f}function We(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const s in e)if(e[s]!==t[s])return!1;return!0}function Ut(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function it(e){if(!Lt(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!Lt(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Lt(e){return Object.prototype.toString.call(e)==="[object Object]"}function hr(e){return new Promise(t=>{Ee.setTimeout(t,e)})}function at(e,t,s){if(typeof s.structuralSharing=="function")return s.structuralSharing(e,t);if(s.structuralSharing!==!1){if(process.env.NODE_ENV!=="production")try{return nt(e,t)}catch(r){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${s.queryHash}]: ${r}`),r}return nt(e,t)}return t}function fr(e,t,s=0){const r=[...e,t];return s&&r.length>s?r.slice(1):r}function mr(e,t,s=0){const r=[t,...e];return s&&r.length>s?r.slice(0,-1):r}var Ke=Symbol();function rs(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===Ke&&console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${e.queryHash}'`),!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ke?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function pt(e,t){return typeof e=="function"?e(...t):!!e}function pr(e,t,s){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i)}),e}var yr=class extends Fe{#e;#t;#s;constructor(){super(),this.#s=e=>{if(!Oe&&window.addEventListener){const t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#s=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){const e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},yt=new yr;function ot(){let e,t;const s=new Promise((i,a)=>{e=i,t=a});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return s.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},s.reject=i=>{r({status:"rejected",reason:i}),t(i)},s}var gr=cr;function vr(){let e=[],t=0,s=l=>{l()},r=l=>{l()},i=gr;const a=l=>{t?e.push(l):i(()=>{s(l)})},o=()=>{const l=e;e=[],l.length&&i(()=>{r(()=>{l.forEach(f=>{s(f)})})})};return{batch:l=>{let f;t++;try{f=l()}finally{t--,t||o()}return f},batchCalls:l=>(...f)=>{a(()=>{l(...f)})},schedule:a,setNotifyFunction:l=>{s=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{i=l}}}var ae=vr(),xr=class extends Fe{#e=!0;#t;#s;constructor(){super(),this.#s=e=>{if(!Oe&&window.addEventListener){const t=()=>e(!0),s=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#s=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(s=>{s(e)}))}isOnline(){return this.#e}},Ye=new xr;function br(e){return Math.min(1e3*2**e,3e4)}function ns(e){return(e??"online")==="online"?Ye.isOnline():!0}var lt=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function is(e){let t=!1,s=0,r;const i=ot(),a=()=>i.status!=="pending",o=p=>{if(!a()){const S=new lt(p);m(S),e.onCancel?.(S)}},l=()=>{t=!0},f=()=>{t=!1},h=()=>yt.isFocused()&&(e.networkMode==="always"||Ye.isOnline())&&e.canRun(),d=()=>ns(e.networkMode)&&e.canRun(),A=p=>{a()||(r?.(),i.resolve(p))},m=p=>{a()||(r?.(),i.reject(p))},I=()=>new Promise(p=>{r=S=>{(a()||h())&&p(S)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),w=()=>{if(a())return;let p;const S=s===0?e.initialPromise:void 0;try{p=S??e.fn()}catch(L){p=Promise.reject(L)}Promise.resolve(p).then(A).catch(L=>{if(a())return;const F=e.retry??(Oe?0:3),$=e.retryDelay??br,U=typeof $=="function"?$(s,L):$,V=F===!0||typeof F=="number"&&s<F||typeof F=="function"&&F(s,L);if(t||!V){m(L);return}s++,e.onFail?.(s,L),hr(U).then(()=>h()?void 0:I()).then(()=>{t?m(L):w()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:l,continueRetry:f,canStart:d,start:()=>(d()?w():I().then(w),i)}}var as=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),rt(this.gcTime)&&(this.#e=Ee.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Oe?1/0:300*1e3))}clearGcTimeout(){this.#e&&(Ee.clearTimeout(this.#e),this.#e=void 0)}},Sr=class extends as{#e;#t;#s;#n;#r;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#n=e.client,this.#s=this.#n.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=Bt(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#r?.promise}setOptions(e){if(this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const t=Bt(this.options);t.data!==void 0&&(this.setState($t(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const s=at(this.state.data,e,this.options);return this.#i({data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(de).catch(de):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>pe(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ke||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Re(e.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e==="static"?!1:this.state.isInvalidated?!0:!ss(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#r?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#r?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#r&&(this.#o?this.#r.cancel({revert:!0}):this.#r.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}async fetch(e,t){if(this.state.fetchStatus!=="idle"&&this.#r?.status()!=="rejected"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#r)return this.#r.continueRetry(),this.#r.promise}if(e&&this.setOptions(e),!this.options.queryFn){const l=this.observers.find(f=>f.options.queryFn);l&&this.setOptions(l.options)}process.env.NODE_ENV!=="production"&&(Array.isArray(this.options.queryKey)||console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']"));const s=new AbortController,r=l=>{Object.defineProperty(l,"signal",{enumerable:!0,get:()=>(this.#o=!0,s.signal)})},i=()=>{const l=rs(this.options,t),h=(()=>{const d={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(d),d})();return this.#o=!1,this.options.persister?this.options.persister(l,h,this):l(h)},o=(()=>{const l={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(l),l})();this.options.behavior?.onFetch(o,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#i({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=is({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof lt&&l.revert&&this.setState({...this.#t,fetchStatus:"idle"}),s.abort()},onFail:(l,f)=>{this.#i({type:"failed",failureCount:l,error:f})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0});try{const l=await this.#r.start();if(l===void 0)throw process.env.NODE_ENV!=="production"&&console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),new Error(`${this.queryHash} data is undefined`);return this.setData(l),this.#s.config.onSuccess?.(l,this),this.#s.config.onSettled?.(l,this.state.error,this),l}catch(l){if(l instanceof lt){if(l.silent)return this.#r.promise;if(l.revert){if(this.state.data===void 0)throw l;return this.state.data}}throw this.#i({type:"error",error:l}),this.#s.config.onError?.(l,this),this.#s.config.onSettled?.(this.state.data,l,this),l}finally{this.scheduleGc()}}#i(e){const t=s=>{switch(e.type){case"failed":return{...s,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...os(s.data,this.options),fetchMeta:e.meta??null};case"success":const r={...s,...$t(e.data,e.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?r:void 0,r;case"error":const i=e.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...e.state}}};this.state=t(this.state),ae.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function os(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ns(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function $t(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Bt(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,r=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var Ar=class extends Fe{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=ot(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#s=void 0;#n=void 0;#r;#a;#o;#i;#p;#h;#f;#c;#u;#l;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),qt(this.#t,this.options)?this.#d():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return ct(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ct(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#S(),this.#t.removeObserver(this)}setOptions(e){const t=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof pe(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#A(),this.#t.setOptions(this.options),t._defaulted&&!We(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&_t(this.#t,s,this.options,t)&&this.#d(),this.updateResult(),r&&(this.#t!==s||pe(this.options.enabled,this.#t)!==pe(t.enabled,this.#t)||Re(this.options.staleTime,this.#t)!==Re(t.staleTime,this.#t))&&this.#y();const i=this.#g();r&&(this.#t!==s||pe(this.options.enabled,this.#t)!==pe(t.enabled,this.#t)||i!==this.#l)&&this.#v(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),s=this.createResult(t,e);return jr(this,s)&&(this.#n=s,this.#a=this.options,this.#r=this.#t.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(s,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),s=this.#e.getQueryCache().build(this.#e,t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#d(e){this.#A();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(de)),t}#y(){this.#b();const e=Re(this.options.staleTime,this.#t);if(Oe||this.#n.isStale||!rt(e))return;const s=ss(this.#n.dataUpdatedAt,e)+1;this.#c=Ee.setTimeout(()=>{this.#n.isStale||this.updateResult()},s)}#g(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#S(),this.#l=e,!(Oe||pe(this.options.enabled,this.#t)===!1||!rt(this.#l)||this.#l===0)&&(this.#u=Ee.setInterval(()=>{(this.options.refetchIntervalInBackground||yt.isFocused())&&this.#d()},this.#l))}#x(){this.#y(),this.#v(this.#g())}#b(){this.#c&&(Ee.clearTimeout(this.#c),this.#c=void 0)}#S(){this.#u&&(Ee.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const s=this.#t,r=this.options,i=this.#n,a=this.#r,o=this.#a,f=e!==s?e.state:this.#s,{state:h}=e;let d={...h},A=!1,m;if(t._optimisticResults){const W=this.hasListeners(),T=!W&&qt(e,t),C=W&&_t(e,s,t,r);(T||C)&&(d={...d,...os(h.data,e.options)}),t._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:I,errorUpdatedAt:w,status:p}=d;m=d.data;let S=!1;if(t.placeholderData!==void 0&&m===void 0&&p==="pending"){let W;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(W=i.data,S=!0):W=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,W!==void 0&&(p="success",m=at(i?.data,W,t),A=!0)}if(t.select&&m!==void 0&&!S)if(i&&m===a?.data&&t.select===this.#p)m=this.#h;else try{this.#p=t.select,m=t.select(m),m=at(i?.data,m,t),this.#h=m,this.#i=null}catch(W){this.#i=W}this.#i&&(I=this.#i,m=this.#h,w=Date.now(),p="error");const L=d.fetchStatus==="fetching",F=p==="pending",$=p==="error",U=F&&L,V=m!==void 0,G={status:p,fetchStatus:d.fetchStatus,isPending:F,isSuccess:p==="success",isError:$,isInitialLoading:U,isLoading:U,data:m,dataUpdatedAt:d.dataUpdatedAt,error:I,errorUpdatedAt:w,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:d.dataUpdateCount>0||d.errorUpdateCount>0,isFetchedAfterMount:d.dataUpdateCount>f.dataUpdateCount||d.errorUpdateCount>f.errorUpdateCount,isFetching:L,isRefetching:L&&!F,isLoadingError:$&&!V,isPaused:d.fetchStatus==="paused",isPlaceholderData:A,isRefetchError:$&&V,isStale:gt(e,t),refetch:this.refetch,promise:this.#o,isEnabled:pe(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const W=G.data!==void 0,T=G.status==="error"&&!W,C=ee=>{T?ee.reject(G.error):W&&ee.resolve(G.data)},R=()=>{const ee=this.#o=G.promise=ot();C(ee)},K=this.#o;switch(K.status){case"pending":e.queryHash===s.queryHash&&C(K);break;case"fulfilled":(T||G.data!==K.value)&&R();break;case"rejected":(!T||G.error!==K.reason)&&R();break}}return G}updateResult(){const e=this.#n,t=this.createResult(this.#t,this.options);if(this.#r=this.#t.state,this.#a=this.options,this.#r.data!==void 0&&(this.#f=this.#t),We(t,e))return;this.#n=t;const s=()=>{if(!e)return!0;const{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;const a=new Set(i??this.#m);return this.options.throwOnError&&a.add("error"),Object.keys(this.#n).some(o=>{const l=o;return this.#n[l]!==e[l]&&a.has(l)})};this.#w({listeners:s()})}#A(){const e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;const t=this.#t;this.#t=e,this.#s=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#x()}#w(e){ae.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function wr(e,t){return pe(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function qt(e,t){return wr(e,t)||e.state.data!==void 0&&ct(e,t,t.refetchOnMount)}function ct(e,t,s){if(pe(t.enabled,e)!==!1&&Re(t.staleTime,e)!=="static"){const r=typeof s=="function"?s(e):s;return r==="always"||r!==!1&>(e,t)}return!1}function _t(e,t,s,r){return(e!==t||pe(r.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&>(e,s)}function gt(e,t){return pe(t.enabled,e)!==!1&&e.isStaleByTime(Re(t.staleTime,e))}function jr(e,t){return!We(e.getCurrentResult(),t)}function Qt(e){return{onFetch:(t,s)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},f=0;const h=async()=>{let d=!1;const A=w=>{pr(w,()=>t.signal,()=>d=!0)},m=rs(t.options,t.fetchOptions),I=async(w,p,S)=>{if(d)return Promise.reject();if(p==null&&w.pages.length)return Promise.resolve(w);const F=(()=>{const Y={client:t.client,queryKey:t.queryKey,pageParam:p,direction:S?"backward":"forward",meta:t.options.meta};return A(Y),Y})(),$=await m(F),{maxPages:U}=t.options,V=S?mr:fr;return{pages:V(w.pages,$,U),pageParams:V(w.pageParams,p,U)}};if(i&&a.length){const w=i==="backward",p=w?Nr:Ht,S={pages:a,pageParams:o},L=p(r,S);l=await I(S,L,w)}else{const w=e??a.length;do{const p=f===0?o[0]??r.initialPageParam:Ht(r,l);if(f>0&&p==null)break;l=await I(l,p),f++}while(f<w)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(h,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s):t.fetchFn=h}}}function Ht(e,{pages:t,pageParams:s}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,s[r],s):void 0}function Nr(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}var Cr=class extends as{#e;#t;#s;#n;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#s=e.mutationCache,this.#t=[],this.state=e.state||ls(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#n?.continue()??this.execute(this.state.variables)}async execute(e){const t=()=>{this.#r({type:"continue"})},s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#n=is({fn:()=>this.options.mutationFn?this.options.mutationFn(e,s):Promise.reject(new Error("No mutationFn found")),onFail:(a,o)=>{this.#r({type:"failed",failureCount:a,error:o})},onPause:()=>{this.#r({type:"pause"})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#s.canRun(this)});const r=this.state.status==="pending",i=!this.#n.canStart();try{if(r)t();else{this.#r({type:"pending",variables:e,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(e,this,s);const o=await this.options.onMutate?.(e,s);o!==this.state.context&&this.#r({type:"pending",context:o,variables:e,isPaused:i})}const a=await this.#n.start();return await this.#s.config.onSuccess?.(a,e,this.state.context,this,s),await this.options.onSuccess?.(a,e,this.state.context,s),await this.#s.config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,e,this.state.context,s),this.#r({type:"success",data:a}),a}catch(a){try{await this.#s.config.onError?.(a,e,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,e,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,e,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#r({type:"error",error:a}),a}finally{this.#s.runNext(this)}}#r(e){const t=s=>{switch(e.type){case"failed":return{...s,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...s,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:e.error,failureCount:s.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),ae.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function ls(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Tr=class extends Fe{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(e,t,s){const r=new Cr({client:e,mutationCache:this,mutationId:++this.#s,options:e.defaultMutationOptions(t),state:s});return this.add(r),r}add(e){this.#e.add(e);const t=Qe(e);if(typeof t=="string"){const s=this.#t.get(t);s?s.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){const t=Qe(e);if(typeof t=="string"){const s=this.#t.get(t);if(s)if(s.length>1){const r=s.indexOf(e);r!==-1&&s.splice(r,1)}else s[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){const t=Qe(e);if(typeof t=="string"){const r=this.#t.get(t)?.find(i=>i.state.status==="pending");return!r||r===e}else return!0}runNext(e){const t=Qe(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){ae.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Ft(t,s))}findAll(e={}){return this.getAll().filter(t=>Ft(e,t))}notify(e){ae.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return ae.batch(()=>Promise.all(e.map(t=>t.continue().catch(de))))}};function Qe(e){return e.options.scope?.id}var Ir=class extends Fe{#e;#t=void 0;#s;#n;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#r()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){const t=this.options;this.options=this.#e.defaultMutationOptions(e),We(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&Me(t.mutationKey)!==Me(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(e){this.#r(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#r(),this.#a()}mutate(e,t){return this.#n=t,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(e)}#r(){const e=this.#s?.state??ls();this.#t={...e,isPending:e.status==="pending",isSuccess:e.status==="success",isError:e.status==="error",isIdle:e.status==="idle",mutate:this.mutate,reset:this.reset}}#a(e){ae.batch(()=>{if(this.#n&&this.hasListeners()){const t=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#n.onSuccess?.(e.data,t,s,r)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(e.data,null,t,s,r)}catch(i){Promise.reject(i)}}else if(e?.type==="error"){try{this.#n.onError?.(e.error,t,s,r)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(void 0,e.error,t,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(t=>{t(this.#t)})})}},Rr=class extends Fe{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,s){const r=t.queryKey,i=t.queryHash??mt(r,t);let a=this.get(i);return a||(a=new Sr({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){ae.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){const t={exact:!0,...e};return this.getAll().find(s=>Dt(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Dt(e,s)):t}notify(e){ae.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ae.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ae.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},kr=class{#e;#t;#s;#n;#r;#a;#o;#i;constructor(e={}){this.#e=e.queryCache||new Rr,this.#t=e.mutationCache||new Tr,this.#s=e.defaultOptions||{},this.#n=new Map,this.#r=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=yt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=Ye.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#i?.(),this.#i=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),s=this.#e.build(this,t),r=s.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&s.isStaleByTime(Re(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:s})=>{const r=s.data;return[t,r]})}setQueryData(e,t,s){const r=this.defaultQueryOptions({queryKey:e}),a=this.#e.get(r.queryHash)?.state.data,o=ur(t,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return ae.batch(()=>this.#e.findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,s)]))}getQueryState(e){const t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){const t=this.#e;ae.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#e;return ae.batch(()=>(s.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},r=ae.batch(()=>this.#e.findAll(e).map(i=>i.cancel(s)));return Promise.all(r).then(de).catch(de)}invalidateQueries(e,t={}){return ae.batch(()=>(this.#e.findAll(e).forEach(s=>{s.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){const s={...t,cancelRefetch:t.cancelRefetch??!0},r=ae.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,s);return s.throwOnError||(a=a.catch(de)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(de)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#e.build(this,t);return s.isStaleByTime(Re(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(de).catch(de)}fetchInfiniteQuery(e){return e.behavior=Qt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(de).catch(de)}ensureInfiniteQueryData(e){return e.behavior=Qt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ye.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(e){this.#s=e}setQueryDefaults(e,t){this.#n.set(Me(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(r=>{Le(e,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(e,t){this.#r.set(Me(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],s={};return t.forEach(r=>{Le(e,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(e){if(e._defaulted)return e;const t={...this.#s.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=mt(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===Ke&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#s.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},cs=ce.createContext(void 0),vt=e=>{const t=ce.useContext(cs);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Er=({client:e,children:t})=>(ce.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),n.jsx(cs.Provider,{value:e,children:t})),us=ce.createContext(!1),Or=()=>ce.useContext(us);us.Provider;function Mr(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Pr=ce.createContext(Mr()),Dr=()=>ce.useContext(Pr),Fr=(e,t,s)=>{const r=s?.state.error&&typeof e.throwOnError=="function"?pt(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ur=e=>{ce.useEffect(()=>{e.clearReset()},[e])},Lr=({result:e,errorResetBoundary:t,throwOnError:s,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||pt(s,[e.error,r])),$r=e=>{if(e.suspense){const s=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Br=(e,t)=>e.isLoading&&e.isFetching&&!t,qr=(e,t)=>e?.suspense&&t.isPending,Gt=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function _r(e,t,s){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=Or(),i=Dr(),a=vt(),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=a.getQueryCache().get(o.queryHash);process.env.NODE_ENV!=="production"&&(o.queryFn||console.error(`[${o.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),o._optimisticResults=r?"isRestoring":"optimistic",$r(o),Fr(o,i,l),Ur(i);const f=!a.getQueryCache().get(o.queryHash),[h]=ce.useState(()=>new t(a,o)),d=h.getOptimisticResult(o),A=!r&&e.subscribed!==!1;if(ce.useSyncExternalStore(ce.useCallback(m=>{const I=A?h.subscribe(ae.batchCalls(m)):de;return h.updateResult(),I},[h,A]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),ce.useEffect(()=>{h.setOptions(o)},[o,h]),qr(o,d))throw Gt(o,h,i);if(Lr({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw d.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Oe&&Br(d,r)&&(f?Gt(o,h,i):l?.promise)?.catch(de).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?d:h.trackResult(d)}function xt(e,t){return _r(e,Ar)}function Qr(e,t){const s=vt(),[r]=ce.useState(()=>new Ir(s,e));ce.useEffect(()=>{r.setOptions(e)},[r,e]);const i=ce.useSyncExternalStore(ce.useCallback(o=>r.subscribe(ae.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=ce.useCallback((o,l)=>{r.mutate(o,l).catch(de)},[r]);if(i.error&&pt(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function bt(){const{alerts:e}=ye(),t=vt();return Qr({mutationFn:s=>e.updateAlertStatus(s),onSuccess:()=>{t.invalidateQueries({queryKey:["alerts","list"]}),t.invalidateQueries({queryKey:["alerts","report"]})}})}function Hr(e,t){return e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZone:t})}function Gr(e,t){try{const i=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(e).find(o=>o.type==="timeZoneName")?.value;let a;try{const l=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"shortOffset"}).formatToParts(e).find(f=>f.type==="timeZoneName");l?.value&&l.value.startsWith("GMT")&&(a=l.value.replace("GMT",""))}catch{}return{abbr:i,offset:a}}catch{return{}}}function Wr(e){if(!e)return"-";try{const t=new Date(e),s=h=>String(h).padStart(2,"0"),r=s(t.getMonth()+1),i=s(t.getDate()),a=t.getFullYear(),o=s(t.getHours()),l=s(t.getMinutes()),f=s(t.getSeconds());return`${r}/${i}/${a} ${o}:${l}:${f}`}catch{return"-"}}function ut(e){if(!e)return"-";try{return new Date(e).toLocaleString("en-US",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return"-"}}const Kr={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},Yr={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"};function ds({alerts:e,loading:t=!1,pageSize:s=10,severityOptions:r,anomalyOptions:i,spaceOptions:a,onAlertIdClick:o}){const l=bt(),f=["completed","false positive"],h=async m=>{try{const I=await l.mutateAsync({alertUniqueId:m.alertId??m.id,alertId:m.id,status:"Reopen",notes:"Reopened",modifiedBy:0});if(I?.responseStatus){const w=I?.data||"Alert reopened successfully.";he.toast.success(w)}else{const w=I?.errorMessage||"Failed to reopen alert";he.toast.error(w)}}catch{he.toast.error("Failed to reopen alert. Please try again.")}},d=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:m=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${Kr[m]}`,backgroundColor:Yr[String(m)]},children:m})},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:200,render:m=>Wr(m)},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(m,I)=>n.jsxs("div",{children:[n.jsx("a",{onClick:w=>{w.preventDefault(),o?.(I,{sourceTab:"archived"})},className:"inline-block mb-1 text-blue-600",children:I.alertNumber}),n.jsx("div",{className:"text-black/65",children:m})]})},{title:"",key:"menu",width:60,align:"right",render:(m,I)=>n.jsx(c.Dropdown,{trigger:["click"],menu:{items:[{key:"reopen",label:"Reopen"}],onClick:({key:w})=>{w==="reopen"&&h(I)}},children:n.jsx(c.Button,{type:"text",icon:n.jsx(De.MoreOutlined,{})})})}],A=(e||[]).filter(m=>f.includes((m.statusType||"").toLowerCase()));return n.jsx(ft,{data:A,loading:t,pageSize:s,columns:d,severityOptions:r,anomalyOptions:i,spaceOptions:a,renderActions:void 0,onAlertIdClick:o,excludeCompleted:!1})}function zr({size:e=120,time:t,timeZone:s="America/New_York"}){const{hours:r,minutes:i,seconds:a}=u.useMemo(()=>{const A=new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"numeric",second:"numeric",hour12:!1}).formatToParts(t);return{hours:parseInt(A.find(m=>m.type==="hour")?.value||"0",10),minutes:parseInt(A.find(m=>m.type==="minute")?.value||"0",10),seconds:parseInt(A.find(m=>m.type==="second")?.value||"0",10)}},[t,s]),o=a*6,l=i*6+a*.1,f=r%12*30+i*.5,h=e/2;return n.jsxs("div",{className:"relative rounded-full border border-gray-300 bg-white",style:{width:e,height:e},role:"img","aria-label":"Analog Clock",children:[[...Array(12)].map((d,A)=>{const m=A*30,I=6,w=h-4,p=w-I,S=(m-90)*(Math.PI/180),L=h+p*Math.cos(S),F=h+p*Math.sin(S),$=h+w*Math.cos(S),U=h+w*Math.sin(S);return n.jsx("svg",{className:"absolute inset-0",width:e,height:e,children:n.jsx("line",{x1:L,y1:F,x2:$,y2:U,stroke:"#9CA3AF",strokeWidth:A%3===0?2:1,strokeLinecap:"round"})},A)}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${f}deg)`},children:n.jsx("line",{x1:h,y1:h,x2:h,y2:h-e*.25,stroke:"#1F2937",strokeWidth:4,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${l}deg)`},children:n.jsx("line",{x1:h,y1:h,x2:h,y2:h-e*.35,stroke:"#374151",strokeWidth:3,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${o}deg)`},children:n.jsx("line",{x1:h,y1:h+e*.08,x2:h,y2:h-e*.38,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"})}),n.jsx("div",{className:"absolute bg-gray-900 rounded-full",style:{width:8,height:8,left:h-4,top:h-4}})]})}function hs({label:e="USA",timeZone:t="America/New_York",updateIntervalMs:s=1e3,className:r}){const[i,a]=u.useState(new Date);u.useEffect(()=>{const h=setInterval(()=>a(new Date),s);return()=>clearInterval(h)},[s]);const o=u.useMemo(()=>Hr(i,t),[i,t]),{abbr:l,offset:f}=u.useMemo(()=>Gr(i,t),[i,t]);return n.jsxs("div",{className:`flex items-center gap-3 ${r||""}`,children:[n.jsx(zr,{time:i,timeZone:t,size:80}),n.jsxs("div",{className:"flex flex-col items-baseline gap-1",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[n.jsx("span",{className:"uppercase",children:e}),l&&n.jsx("span",{className:"px-1.5 py-0.5 rounded-md border text-[10px] leading-none text-gray-600 bg-gray-50",children:l}),f&&n.jsx("span",{className:"text-xs text-gray-500",children:f})]}),n.jsx("div",{className:"text-2xl font-semibold text-gray-700 tracking-wide",children:o})]})]})}const Vr=[{SeverityId:1,Code:"LOW",DisplayName:"Low",SortOrder:10,IsActive:!0},{SeverityId:2,Code:"MEDIUM",DisplayName:"Medium",SortOrder:20,IsActive:!0},{SeverityId:3,Code:"HIGH",DisplayName:"High",SortOrder:30,IsActive:!0},{SeverityId:4,Code:"CRITICAL",DisplayName:"Critical",SortOrder:40,IsActive:!0}],Jr=[{RuleId:"0938aa00-dfa7-4258-805a-67396366c776",RuleVersionId:"36d2d581-57c3-45c3-8705-8235935fdf96",Name:"License Plate Recognition",Description:"License Plate Recognition",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:3,AnomalyId:"915976ef-4eb6-4f7b-bbe6-e53862517fc9",Level:"global"},{RuleId:"2437286a-db6a-4d35-814e-9ac49f158dde",RuleVersionId:"00000000-0000-0000-0000-000000000000",Name:"Monitor And Track Onsite Vehicle timelog",Description:"Monitor And Track Onsite Vehicle timelog",VersionCount:0,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:3,AnomalyId:"9fd651ab-4312-4826-84b6-94d735894477",Level:"global"},{RuleId:"b99120ba-7a83-4ade-b5d9-a420550fe351",RuleVersionId:"d7b14dae-a7b1-474e-a357-199182c02ac3",Name:"Watchlist person detected",Description:"Watchlist person detected",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:4,AnomalyId:"bb3a3d3a-73a3-4f5a-8804-1baadbd0d412",Level:"global"},{RuleId:"ffc2c24f-adb7-4aba-ace7-f19c54e21530",RuleVersionId:"6ab3178f-bf77-4a1e-898d-1d5dbef749c5",Name:"Weapon Detection",Description:"Weapon Detection",VersionCount:1,ActionCount:0,ApplicabilityPeriodCount:0,SuppressionCount:0,AssignmentCount:0,ExclusionCount:0,IsDeleted:!1,SeverityId:4,AnomalyId:"ac82c3a2-72e6-4f9c-88fb-851a3ca3c4de",Level:"global"}],Zr=[{userRoleId:1,userRoleName:"Super Admin"},{userRoleId:2,userRoleName:"Security Officer"},{userRoleId:3,userRoleName:"Security Admin"},{userRoleId:4,userRoleName:"Regulatory Officer/First Responder"},{userRoleId:5,userRoleName:"User"}],Pe={severities:Vr,rules:Jr,userRoles:Zr},{Text:Xr}=c.Typography;function en({sortBy:e,onChange:t,showActions:s,onSave:r,onClear:i,saving:a}){return n.jsxs(c.Row,{gutter:[16,16],align:"middle",children:[n.jsx(c.Col,{xs:24,md:8,lg:5,children:n.jsxs(c.Space,{className:"w-full items-center",direction:"horizontal",size:12,children:[n.jsx(Xr,{className:"text-gray-600 whitespace-nowrap",children:"Sort By:"}),n.jsx(c.Select,{placeholder:"By Severity",value:e,onChange:o=>t({sortBy:o}),options:[{label:"By Severity",value:"By Severity"},{label:"By Created Date",value:"By Created Date"}],className:"w-full",style:{minWidth:"200px"}})]})}),n.jsx(c.Col,{xs:24,md:8,style:{alignSelf:"end"},children:s?n.jsxs(c.Space,{className:"w-full",direction:"horizontal",size:8,children:[n.jsx(c.Button,{onClick:i,disabled:a,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:r,loading:a,children:"Save"})]}):null})]})}const{Text:Te}=c.Typography;function tn(e){const{selectedRule:t,setSelectedRule:s,ruleOptions:r,minsOptions:i,roleOptions:a,l1mins:o,setL1mins:l,l1role:f,setL1role:h,l2mins:d,setL2mins:A,l2role:m,setL2role:I,l3mins:w,setL3mins:p,l3role:S,setL3role:L,actions:F,setActions:$,thirdPartyIds:U,setThirdPartyIds:V,humanLoop:Y,setHumanLoop:G,onClear:W,onSave:T,saving:C,onActionTypesLoaded:R}=e,{rules:K}=ye(),[ee,E]=u.useState([]),[v,y]=u.useState([]),[j,g]=u.useState(!1);u.useEffect(()=>{let k=!1;return(async()=>{try{g(!0);const M=await K.getLookups();if(k||!M||!Array.isArray(M.actionTypes))return;const O=M.actionTypes.map(q=>({label:q.name,value:String(q.actionTypeId)}));E(O),R&&R(M.actionTypes);const B=Array.isArray(M.thirdParties)?M.thirdParties.map(q=>({label:q.thirdPartyName,value:q.thirdPartyId})):[];y(B)}catch(M){console.error("Error loading lookups",M)}finally{k||g(!1)}})(),()=>{k=!0}},[]);const x=typeof o=="number"||typeof f=="number"||typeof d=="number"||typeof m=="number"||typeof w=="number"||typeof S=="number"||Array.isArray(F)&&F.length>0||Array.isArray(U)&&U.length>0||!!Y,b=!!t&&x&&!C;return n.jsxs(c.Spin,{spinning:!!C||j,children:[n.jsxs(c.Row,{gutter:[16,16],align:"bottom",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Te,{className:"text-gray-700 font-medium block mb-1",children:"Rules"}),n.jsx(c.Select,{placeholder:"Rules",value:t,onChange:s,options:r,className:"w-full"})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Te,{className:"text-gray-700 font-medium block mb-1",children:"Level 1 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Te,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:o,onChange:l,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:f,onChange:h,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Te,{className:"text-gray-700 font-medium block mb-1",children:"Level 2 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Te,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:d,onChange:A,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:m,onChange:I,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(Te,{className:"text-gray-700 font-medium block mb-1",children:"Level 3 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Te,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:w,onChange:p,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:S,onChange:L,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:5,children:n.jsxs("div",{children:[n.jsx(Te,{className:"text-gray-700 font-medium block mb-1",children:"Pick Actions"}),n.jsx(c.Select,{mode:"multiple",placeholder:"Select response actions",className:"w-full",value:F,onChange:$,options:ee})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:3,children:n.jsx("div",{className:"flex items-end h-full",children:n.jsx(c.Checkbox,{checked:Y,onChange:k=>G(k.target.checked),children:"Human-In-The-Loop"})})})]}),n.jsxs(c.Row,{gutter:[16,16],align:"bottom",className:"mt-4",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:5,children:n.jsxs("div",{children:[n.jsx(Te,{className:"text-gray-700 font-medium block mb-1",children:"Third Party App"}),n.jsx(c.Select,{mode:"multiple",placeholder:"Third Party app",className:"w-full",value:U,onChange:V,options:v})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(c.Button,{onClick:W,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:T,loading:!!C,disabled:!b,children:"Save"})]})})]})]})}function sn({entries:e,userRoles:t,onEdit:s,loading:r}){const i=new Map(t.map(o=>[o.userRoleId,o.userRoleName])),a=o=>o.map(l=>i.get(l)||String(l)).join(", ");return n.jsx(c.Table,{rowKey:"id",dataSource:e,pagination:!1,loading:r,columns:[{title:"Rule",dataIndex:"ruleOrSeverityLabel",key:"rule"},{title:"Level 1",key:"l1",render:(o,l)=>n.jsxs("span",{children:[l.l1.minutes?`Action taken in (${l.l1.minutes} Mins)`:"No Action taken in 0 Min",l.l1.roles?.length?`, Escalate to (${a(l.l1.roles)})`:""]})},{title:"Level 2",key:"l2",render:(o,l)=>n.jsxs("span",{children:[l.l2.minutes?`Action taken in (${l.l2.minutes} Mins)`:"No Action taken in 0 Min",l.l2.roles?.length?`, Escalate to (${a(l.l2.roles)})`:""]})},{title:"Level 3",key:"l3",render:(o,l)=>n.jsxs("span",{children:[l.l3.minutes?`Action taken in (${l.l3.minutes} Mins)`:"No Action taken in 0 Min",l.l3.roles?.length?`, Escalate to (${a(l.l3.roles)})`:""]})},{title:"Pick Actions",key:"actionsCol",render:(o,l)=>l.actions&&l.actions.length?l.actions.join(", "):"-"},{title:"Notify",key:"notify",render:(o,l)=>l.notify&&l.notify.length?l.notify.join(", "):"-"},{title:"Human-In-The-Loop",key:"humanLoop",render:(o,l)=>l.humanLoop?"Yes":"No"},{title:"Actions",key:"ops",render:(o,l)=>n.jsx(c.Button,{type:"text",onClick:()=>s(l.id),children:n.jsx(De.EditOutlined,{})})}]})}const{Title:rn}=c.Typography;function fs({userRoles:e,rules:t,rawRules:s}){const{rules:r}=ye(),[i,a]=u.useState(!1),[o,l]=u.useState(s),[f,h]=u.useState({}),d=u.useMemo(()=>e.map(p=>({label:p.userRoleName,value:p.userRoleId})),[e]),A=u.useMemo(()=>(t||[]).map((p,S)=>({key:p.RuleId||p.Name||String(S),ruleName:p.Name||"-",ruleDesc:p.Description||""})),[t]);u.useEffect(()=>{let p=!1;return(async()=>{try{a(!0);const S=await r.getRules();p||(l(Array.isArray(S)?S:[]),h({}))}catch{!p&&Array.isArray(s)&&l(s)}finally{p||a(!1)}})(),()=>{p=!0}},[]),u.useEffect(()=>{!o&&Array.isArray(s)&&l(s)},[s]);const m=u.useMemo(()=>{if(!Array.isArray(o)||!o.length)return{};const p={};for(const S of A){const L=o.find($=>$?.ruleId===S.key||$?.ruleName===S.key||$?.RuleId===S.key||$?.ruleName===S.ruleName||$?.Name===S.ruleName),F=Array.isArray(L?.userRoleIds)?L.userRoleIds:[];F.length&&(p[S.key]=F)}return p},[o,A]),I=()=>{h({})},w=async()=>{try{if(!o||!Array.isArray(o)||Object.keys(f).length===0){he.toast.info("No changes to save");return}a(!0);const p=Object.entries(f).map(async([S,L])=>{const F=o.find(G=>G?.ruleId===S||G?.ruleName===S||G?.RuleId===S),$=typeof F?.recordId=="number"?F.recordId:void 0;if(!F||typeof $!="number")throw new Error(`Unable to find recordId for rule ${S}`);const U=Array.isArray(L)?L:[],V=U.map(G=>{const W=e.find(T=>T.userRoleId===G);return{id:G,name:W?.userRoleName??String(G)}}),Y={...F,ruleId:S,userRoleIds:U,userRoles:V,actions:[{actionTypeId:4,actionTypeUniqueId:"bc0973d4-9be0-4efb-8545-c9112ba06c1f",name:"Audible Warning",notificationType:"Alarm",category:"Hardware",description:"Test",isSystemDefined:!0,isActive:!0,displayOrder:0}]};return r.updateRule($,Y)});await Promise.all(p),he.toast.success("Alert assignment saved");try{const S=await r.getRules();l(Array.isArray(S)?S:[]),h({})}catch(S){console.error("Failed to refresh rules after save",S)}}catch(p){console.error("Failed to save alert assignment",p)}finally{a(!1)}};return n.jsxs("div",{className:"w-full",children:[n.jsx("div",{className:"flex items-center justify-between",children:n.jsx(rn,{level:4,className:"!mb-4",children:"Alert Assignment"})}),n.jsx(c.Table,{rowKey:"key",dataSource:A,loading:i,pagination:!1,columns:[{title:"Rule Name",dataIndex:"ruleName",key:"ruleName"},{title:"Description",dataIndex:"ruleDesc",key:"ruleDesc"},{title:"Alert Notification To",key:"assign",render:(p,S)=>n.jsx(c.Select,{mode:"multiple",placeholder:"Dropdown with Multi select",className:"w-full",value:f[S.key]??m[S.key]??[],onChange:L=>h(F=>({...F,[S.key]:L})),options:d})}]}),n.jsxs(c.Space,{className:"mt-4",children:[n.jsx(c.Button,{onClick:I,disabled:i,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:w,loading:i,disabled:i||Object.keys(f).length===0,children:"Save"})]})]})}const{Title:Wt}=c.Typography;function ms({severities:e,rules:t,userRoles:s,rawRules:r,onSave:i}){const{rules:a,alerts:o}=ye(),[l,f]=u.useState("By Severity"),[h,d]=u.useState("By severity"),[A,m]=u.useState("By Severity"),[I,w]=u.useState(!1),[p,S]=u.useState(!1),[L,F]=u.useState(!1),[$,U]=u.useState(null),[V,Y]=u.useState("rules"),[G,W]=u.useState(),[T,C]=u.useState(),[R,K]=u.useState(),[ee,E]=u.useState(),[v,y]=u.useState(),[j,g]=u.useState(),[x,b]=u.useState(),[k,M]=u.useState(),[O,B]=u.useState([]),[q,z]=u.useState([]),[ne,fe]=u.useState(!1),[le,re]=u.useState({}),[ie,Se]=u.useState({}),[ge,Ve]=u.useState(s||[]),[Ue,Ae]=u.useState([]),[Je,N]=u.useState(!1),[Q,se]=u.useState(!1),[ue,Z]=u.useState(r||[]);u.useEffect(()=>{r&&r.length&&Z(r)},[r]),u.useEffect(()=>{if(!ue||!ue.length)return;const P=Object.keys(le).length>0||Object.keys(ie).length>0;if(Ue.length&&!P)return;const X=ue.map((_,D)=>{const J=t.find(je=>je.RuleId===(_.ruleId||_.ruleName))?.Name||_.ruleName||_.Name||"-",H=_.escalationSettings||{},te=typeof H.level1UserRoleId=="number"&&H.level1UserRoleId>0?[H.level1UserRoleId]:[],we=typeof H.level2UserRoleId=="number"&&H.level2UserRoleId>0?[H.level2UserRoleId]:[],Xe=typeof H.level3UserRoleId=="number"&&H.level3UserRoleId>0?[H.level3UserRoleId]:[],wt=(Array.isArray(H.escalationSettingsActionTypeIds)?H.escalationSettingsActionTypeIds:[]).map(je=>le[je]||String(je)),Nt=(Array.isArray(H.thirdPartyId)?H.thirdPartyId:[]).map(je=>ie[je]||String(je)),et=typeof H.humanLoop=="boolean"?H.humanLoop:null;return{id:String(_.ruleId||_.ruleName||D),ruleOrSeverityLabel:J,l1:{minutes:H.level1PostAssistTime??void 0,roles:te},l2:{minutes:H.level2PostAssistTime??void 0,roles:we},l3:{minutes:H.level3PostAssistTime??void 0,roles:Xe},actions:wt,notify:Nt,humanLoop:et}});Ae(X)},[ue,t,le,ie]);const ve=u.useMemo(()=>e.map(P=>({label:P.DisplayName,value:P.SeverityId})),[e]),$e=u.useMemo(()=>t.map(P=>({label:P.Name,value:P.RuleId})),[t]),me=u.useMemo(()=>ge.map(P=>({label:P.userRoleName,value:P.userRoleId})),[ge]),Ze=u.useMemo(()=>[1,3,5,10,15,20,30,45,60].map(P=>({label:`${P}`,value:P})),[]);u.useEffect(()=>{let P=!1;async function X(){try{F(!0),U(null);const _=await o.getAdminSettings();if(!P&&_){const D=Jt(_.sortBy);f(D),m(D),w(!1)}}catch(_){if(!P){const D=_ instanceof Error?_.message:"Failed to load admin settings";U(D)}}finally{P||F(!1)}}return X(),()=>{P=!0}},[]),u.useEffect(()=>{if(!T)return;const P=J=>{const H=Number(J);return!isNaN(H)&&H>0?H:void 0},X=J=>{const H=Number(J);return!isNaN(H)&&H>0?H:void 0},D=(ue||[]).find(J=>J?.ruleId===T||J?.ruleName===T||J?.RuleId===T)?.escalationSettings;if(D&&typeof D=="object"){K(X(D.level1PostAssistTime)),E(P(D.level1UserRoleId)),y(X(D.level2PostAssistTime)),g(P(D.level2UserRoleId)),b(X(D.level3PostAssistTime)),M(P(D.level3UserRoleId));const J=Array.isArray(D.escalationSettingsActionTypeIds)?D.escalationSettingsActionTypeIds:[];B(J.map(H=>String(H))),z(Array.isArray(D.thirdPartyId)?D.thirdPartyId:[]),fe(!!D.humanLoop)}},[V,T,ue]);const As=async()=>{try{se(!0);const P=await a.getRules(),X=Array.isArray(P)?P:Array.isArray(P?.data)?P.data:[];Z(X);const _=X.map((D,J)=>{const H=t.find(ke=>ke.RuleId===(D.ruleId||D.ruleName))?.Name||D.ruleName||D.Name||"-",te=D.escalationSettings||{},we=typeof te.level1UserRoleId=="number"&&te.level1UserRoleId>0?[te.level1UserRoleId]:[],Xe=typeof te.level2UserRoleId=="number"&&te.level2UserRoleId>0?[te.level2UserRoleId]:[],At=typeof te.level3UserRoleId=="number"&&te.level3UserRoleId>0?[te.level3UserRoleId]:[],jt=(Array.isArray(te.escalationSettingsActionTypeIds)?te.escalationSettingsActionTypeIds:[]).map(ke=>le[ke]||String(ke)),et=(Array.isArray(te.thirdPartyId)?te.thirdPartyId:[]).map(ke=>ie[ke]||String(ke)),je=typeof te.humanLoop=="boolean"?te.humanLoop:null;return{id:String(D.ruleId||D.ruleName||J),ruleOrSeverityLabel:H,l1:{minutes:te.level1PostAssistTime??void 0,roles:we},l2:{minutes:te.level2PostAssistTime??void 0,roles:Xe},l3:{minutes:te.level3PostAssistTime??void 0,roles:At},actions:jt,notify:et,humanLoop:je}});Ae(_)}catch(P){console.error("Failed to refetch entries",P)}finally{se(!1)}};u.useEffect(()=>{let P=!1;return(async()=>{try{const X=await a.getLookups();if(P||!X)return;const _={};if(Array.isArray(X.thirdParties))for(const J of X.thirdParties)typeof J.thirdPartyId=="number"&&(_[J.thirdPartyId]=J.thirdPartyName);Se(_);const D=Array.isArray(X.userRoles)?X.userRoles.map(J=>({userRoleId:J.userRoleId??J.id,userRoleName:J.userRoleName??J.name})):[];P||Ve(D.length?D:s||[])}catch(X){console.error("Error loading lookups",X)}})(),()=>{P=!0}},[]);const ws=async()=>{S(!0);try{const P=await o.setAdminSettings({sortBy:l,groupBy:"string"});P?.responseStatus&&P?.data&&he.toast.success(P.data),m(l),w(!1)}catch(P){console.error("Error saving admin settings",P)}finally{S(!1)}},js=()=>{f(A),w(!1)},Ns=async()=>{N(!0),i?.({ruleId:T,levels:[{minutes:R,role:ee},{minutes:v,role:j},{minutes:x,role:k}],actions:O,thirdPartyIds:q,humanLoop:ne});try{if(T){const _=Array.isArray(O)?O.map(we=>Number(we)):[],D=(ue||[]).find(we=>we?.ruleId===T||we?.ruleName===T||we?.RuleId===T),J=typeof D?.recordId=="number"?D.recordId:void 0;if(!D||typeof J!="number"){he.toast.error("Unable to find rule recordId for update");return}const H={...D,actions:[{actionTypeId:4,actionTypeUniqueId:"bc0973d4-9be0-4efb-8545-c9112ba06c1f",name:"Audible Warning",notificationType:"Alarm",category:"Hardware",description:"Test",isSystemDefined:!0,isActive:!0,displayOrder:0}],escalationSettings:{level1UserRoleId:ee??0,level1PostAssistTime:R??0,level2UserRoleId:j??0,level2PostAssistTime:v??0,level3UserRoleId:k??0,level3PostAssistTime:x??0,escalationSettingsActionTypeIds:_,thirdPartyId:Array.isArray(q)?q:[],humanLoop:ne}},te=await a.updateRule(J,H);if(te?.responseStatus||te?.ok||te){he.toast.success("Escalation settings saved"),await As(),C(void 0),K(void 0),E(void 0),y(void 0),g(void 0),b(void 0),M(void 0),B([]),z([]),fe(!1);return}}}catch(_){console.error("Error saving escalation settings",_)}finally{N(!1)}const X=t.find(_=>_.RuleId===T)?.Name||"-";Ae(_=>[..._,{id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ruleOrSeverityLabel:X,l1:{minutes:R,roles:ee?[ee]:[]},l2:{minutes:v,roles:j?[j]:[]},l3:{minutes:x,roles:k?[k]:[]},actions:(Array.isArray(O)?O:[]).map(D=>{const J=Number(D);return le[J]||String(D)}),notify:(Array.isArray(q)?q:[]).map(D=>ie[D]||String(D)),humanLoop:!!ne}])},Cs=()=>{f("By Severity"),d("By severity"),Y("rules"),W(void 0),C(void 0),K(void 0),E(void 0),y(void 0),g(void 0),b(void 0),M(void 0),B([]),z([]),fe(!1)};return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"mb-6",children:[n.jsx(Wt,{level:4,className:"!mb-2",children:"Admin Settings"}),n.jsxs(c.Spin,{spinning:L,children:[$?n.jsxs("div",{className:"text-sm text-red-600 mb-2",children:["Failed to load settings: ",$]}):null,n.jsx(en,{sortBy:l,groupBy:h,onChange:P=>{P.sortBy&&(f(P.sortBy),w(!0)),P.groupBy&&(d(P.groupBy),w(!0))},showActions:I,onSave:ws,onClear:js,saving:p})]})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsxs("div",{children:[n.jsx(Wt,{level:4,className:"!mb-4",children:"Escalation Settings"}),n.jsx(tn,{escBasis:V,setEscBasis:Y,selectedSeverity:G,setSelectedSeverity:W,selectedRule:T,setSelectedRule:C,severityOptions:ve,ruleOptions:$e,minsOptions:Ze,roleOptions:me,l1mins:R,setL1mins:K,l1role:ee,setL1role:E,l2mins:v,setL2mins:y,l2role:j,setL2role:g,l3mins:x,setL3mins:b,l3role:k,setL3role:M,actions:O,setActions:B,thirdPartyIds:q,setThirdPartyIds:z,humanLoop:ne,setHumanLoop:fe,onClear:Cs,onSave:Ns,saving:Je,onActionTypesLoaded:P=>{const X={};for(const _ of P)typeof _.actionTypeId=="number"&&(X[_.actionTypeId]=_.name);re(X)}})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(sn,{entries:Ue,userRoles:ge,loading:Q,onEdit:P=>{Y("rules");const X=Ue.find(D=>D.id===P),_=t.find(D=>D.RuleId===P)||(X?t.find(D=>D.Name===X.ruleOrSeverityLabel):void 0);C(_?_.RuleId:P)}}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(fs,{userRoles:ge,rules:t,rawRules:r}),n.jsx(c.Divider,{})]})}const{Title:Kt,Text:He}=c.Typography;function ps({severities:e,rules:t,onSave:s,onCancel:r}){const{rules:i,alerts:a}=ye(),o=[{label:"By Severity",value:"By Severity"},{label:"By Created Date",value:"By Created Date"}],[l,f]=u.useState("By Severity"),[h,d]=u.useState(new Set),[A,m]=u.useState(null),[I,w]=u.useState(null),[p,S]=u.useState({inApp:!1,sms:!1,email:!1}),[L,F]=u.useState([]),[$,U]=u.useState(!0),[V,Y]=u.useState(!1);u.useEffect(()=>{let T=!1;return(async()=>{try{const C=await a.getPreferenceSettings();if(T||!C)return;S({inApp:!!C.inApp,sms:!!C.sms,email:!!C.email});const R=Jt(C.sortBy);f(R==="By Created Date"?"By Created Date":"By Severity"),m(Et(C.doNotDisturbStart)),w(Et(C.doNotDisturbEnd)),Array.isArray(C.anomalyIds)&&d(new Set(C.anomalyIds.map(K=>String(K))))}catch(C){console.error("Error in loading my preferences: ",C)}})(),()=>{T=!0}},[]),u.useEffect(()=>{let T=!1;return(async()=>{try{U(!0);const C=await i.getLookups();if(T||!C)return;const R=Array.isArray(C.anomalies)?C.anomalies:[];F(R)}catch(C){console.error("Failed to load anomalies lookups",C)}finally{T||U(!1)}})(),()=>{T=!0}},[]);const G=T=>{d(C=>{const R=new Set(C);return R.has(T)?R.delete(T):R.add(T),R})},W=async()=>{s?.({sortBy:l,subscribedRuleIds:Array.from(h),dnd:{from:A,to:I},channels:p});try{Y(!0);const T=A?A.format?.("HH:mm:ss")??"00:00:00":"00:00:00",C=I?I.format?.("HH:mm:ss")??"00:00:00":"00:00:00",R=Array.from(h).map(ee=>Number(ee)).filter(ee=>Number.isFinite(ee)),K=await a.setPreferenceSettings({anomalyIds:R,doNotDisturbStart:T,doNotDisturbEnd:C,inApp:!!p.inApp,sms:!!p.sms,email:!!p.email,sortBy:l});K?.responseStatus&&he.toast.success(K?.data||"Preferences updated successfully.")}catch(T){console.error("Error in saving my preferences: ",T)}finally{Y(!1)}};return n.jsxs("div",{className:"w-full",children:[n.jsx(c.Row,{gutter:[16,16],align:"middle",className:"mb-4",children:n.jsx(c.Col,{xs:24,md:8,children:n.jsxs(c.Space,{direction:"horizontal",size:12,className:"w-full items-center",children:[n.jsx(He,{className:"text-gray-600",children:"Sort By:"}),n.jsx(c.Select,{className:"w-[240px]",value:l,options:o,onChange:f})]})})}),n.jsxs("div",{className:"mb-4",children:[n.jsx(Kt,{level:5,className:"!mb-2",children:"Anomalies"}),$?n.jsx("div",{className:"py-4",children:n.jsx(c.Spin,{})}):n.jsx(c.Space,{direction:"vertical",size:10,className:"w-full",children:(Array.isArray(L)?L:[]).map(T=>{const C=String(T.recordId),R=T.anomalyName;return n.jsx(c.Checkbox,{checked:h.has(C),onChange:()=>G(C),children:R},C)})})]}),n.jsxs("div",{className:"mb-4",children:[n.jsx(Kt,{level:5,className:"!mb-2",children:"Notification Timing & Channels"}),n.jsx(c.Row,{gutter:[16,16],align:"middle",className:"mb-3",children:n.jsx(c.Col,{xs:24,md:12,children:n.jsxs(c.Space,{direction:"horizontal",size:12,className:"w-full items-center",children:[n.jsx(He,{children:"Do Not Disturb mode:"}),n.jsxs(c.Space,{size:12,className:"w-full",children:[n.jsxs(c.Space,{direction:"horizontal",size:8,className:"items-center",children:[n.jsx(He,{children:"From"}),n.jsx(c.TimePicker,{value:A,onChange:T=>m(T),format:"HH:mm"})]}),n.jsxs(c.Space,{direction:"horizontal",size:8,className:"items-center",children:[n.jsx(He,{children:"To"}),n.jsx(c.TimePicker,{value:I,onChange:T=>w(T),format:"HH:mm"})]})]})]})})}),n.jsxs(c.Row,{gutter:[24,12],children:[n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.inApp,onChange:T=>S({...p,inApp:T.target.checked}),children:"In-app"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.sms,onChange:T=>S({...p,sms:T.target.checked}),children:"SMS"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.email,onChange:T=>S({...p,email:T.target.checked}),children:"Email"})})]})]}),n.jsx(c.Divider,{}),n.jsxs(c.Space,{className:"gap-3",children:[n.jsx(c.Button,{onClick:r,disabled:V,children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:W,loading:V,children:"Save"})]})]})}function ys({severities:e,rules:t,userRoles:s,rawRules:r}){const[i,a]=u.useState("global");return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"inline-flex rounded-xl overflow-hidden border border-gray-200 mb-4",children:[n.jsx("button",{onClick:()=>a("global"),className:`px-5 py-2 text-base font-medium outline-none ${i==="global"?" bg-black text-white":" bg-white text-black"}`,style:{border:"0"},children:"Global Settings"}),n.jsx("button",{onClick:()=>a("prefs"),className:`px-5 py-2 text-base font-medium outline-none ${i==="prefs"?"bg-black text-white":"bg-white"}`,children:"My Preferences"})]}),i==="global"?n.jsx(ms,{severities:e,rules:t,userRoles:s,rawRules:r}):n.jsx(ps,{severities:e,rules:t})]})}const nn="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAIZSURBVHgBnZW/b9NAFMe/z3H6i1ZNJUBFQsL/QQkLCFBtRhhKF1ibhBmpXbtgFlYqsTG0gRGWwgAjMb8EYmjYGN0pCCrVVaX+SBxf37PiqHWcOu5Xsux79+6j77vz3RH66IbdsDTQPCFngmBwqMCPBwVXoe204Fd/2ZfrSWMpHrDshtGCvsY9FlKkFNYD+Es/7EtuX+itp1sLnLrScTWoPMYsfnty/lUPtAOs4syiUgQOoWHJpG9kdBiX11Z+UaZCk1YT+vOzACuzYxgf7hZbyBGvhTi9af+7SkQbyKi7M8N4ZJ5D+eU2dg9UN07KvyNOS8io6UkNFXMMj1/vnACKAuTmNXZpIqME+LF+iIbX7ukjkClODWTQw+ujuGYMYfXzXnICbxSBDrxAUvYDhkrZp6ggUC8+sDI7mpj9YmESb3/uJ5Z9TJ5A3eORvzsBpgs6lufGT2TKPNY3fbxh6Knis0FTSjnx+LP3u5DJicDi/t7MCFadPaRJQTl02/5vKcKnpITluYkwrWjksebs48Pvg3SoUkXtq32hxt+1pITI8Zc/zcGACN59ty/WdWnklV5ukZ+49wU8MUJIF3mBGlqUr3Dv1+wpl20v9UuP75pElyrgc3XK7UJFbLvK4DJiv9ggDmWcjO9G4imWvW00yV/hjvtpOFnpQOVLkcO+0EhyevGrROG1ol1hREFc8ZGxyddIje+v9c4i9+gI5z7MozLxclgAAAAASUVORK5CYII=",an="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAKeSURBVHgBjVVdbtpAEJ5ZmygPfTBSaVWpUt0bwFuURgJOUG5QeoLACbw+QeAEwA3SGxgJokh9CDeI+xSpTRU/Imw8nbFZx6QQGAl5d2fm229+dkDYI2f6oaUAOwhWExBcPnL4FwFBSLCexpCMf+qPi12++PKgpR/cGOwRa1pwQIjgOoWkf6s/hOVzVd588R+/xWjf5YAY8Y0+ErQrZFfnXg3lK3uGm7A+RISOxfbit5NprqBxxgBoeEIVHehqtI9lSz+5McaaITaA2J17bycFaBayMOS8IaT+zHuv4Ui58P9oAvB4Ga0paUgqbFGswL5idIcIx3P9DCiXrQB7iJawcTiCkMMIUlj7Jo8zr6Yv/EfRXXIqRnzUxnP9u46Id8Q5Sslq3+pqWErHAPKqvxROC/ZMuJwKJ8bkPouUkrYUqgt5IgMDKAxfAYT8nAZnmR2A5J47YSjrFKyOYpZN2SiIJ8YjRqVfASyAFVg9s2F2gXwRsClMXdnYcFpq5PyiQ8KEilaywc79+aEow2i7fdCF46SIpuTvCGi2kWSXjCM4QqS4Zl3yjwQ0UySwrBfGRJNjQKW4ZrmEpL45CxUDTGWdgmoZgxOoDA6zxYgr7ZudhWk3x6Sp4kl0nZmgujQhcH5Cvqy/Hxi5hdL+dgsWxR2rma4FkLeDw+PMM243+t2YB0jDDI9nMBquyWqI3tjmLYguQfqDzxebty/DIcnePr9jfePVfDhSzv2/Hs8LAY3kMmFfTCl+rl3uu1GWF6Jx+X3vkpa+58jeeNyXvY3Pd8N+a0hvgK9ge3hMTmG5CPTnSICWcFpXaDfZUcAck99yOnZM/id3hcmAFV/hgEilU6p0TcH2gpZYS98xc/kXUJ8YImPFzfeLh0cgXbMp8n/yD3ySPZSK0MWKAAAAAElFTkSuQmCC";function on(e){const t=(e.status||"").toLowerCase()==="completed"?n.jsx("img",{src:nn,alt:"completed",style:{width:20,height:20}}):n.jsx("img",{src:an,alt:"pending",style:{width:20,height:20}});return{title:n.jsxs("div",{className:"flex flex-col gap-0 min-w-0",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("span",{className:"block text-sm break-words mb-1 overflow-visible whitespace-normal",children:n.jsx("b",{children:e.title})}),e.description?n.jsx("span",{className:"text-gray-500 text-xs",children:e.description}):null]}),e.timestamp?n.jsx("span",{className:"text-gray-500 text-xs",children:e.timestamp}):null]}),icon:t,description:null}}function ln({data:e}){return n.jsx("div",{className:"w-full",children:n.jsx(c.Tabs,{type:"card",items:[{key:"action",label:"Action Taken",children:n.jsxs("div",{className:"w-full",children:[n.jsx(c.Card,{className:"mb-4 rounded-md p-4",bordered:!0,children:n.jsxs("div",{className:"grid grid-cols-4 gap-6 text-xs",children:[n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Alert ID"}),n.jsx("span",{className:"text-black",children:e.summary.alertNumber})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Severity"}),n.jsx("span",{className:"text-black",children:e.summary.severity})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Location"}),n.jsx("span",{className:"text-black",children:e.summary.location})]})]})}),n.jsxs(c.Card,{className:"rounded-md p-4",bordered:!0,children:[n.jsx("div",{className:"flex items-center justify-between",children:n.jsx("h4",{className:"text-sm text-black font-medium",children:"Response Timeline/ Audit trail/log"})}),n.jsx("div",{className:"mt-2",children:n.jsx(c.Steps,{direction:"vertical",size:"small",current:1,items:(e.timeline||[]).map(on)})})]})]})},{key:"notification",label:"Notification Sent",children:n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(e.notifications||[]).map((t,s)=>n.jsxs(c.Card,{className:"rounded-md p-4",bordered:!0,children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("h4",{className:"text-sm text-black font-medium",children:t.channelLabel}),n.jsx("span",{className:"text-xs text-gray-500 mt-1",children:Vt(t.sentAt)?.format("MM/DD/YYYY HH:mm:ss")})]}),n.jsxs("span",{className:"text-[11px] px-2 py-1 rounded-full bg-green-50 text-green-700 border border-green-200",children:[t.delivered,"/",t.total," Delivered"]})]}),n.jsxs("div",{className:"mt-4 text-xs",children:[n.jsxs("div",{className:"text-black",children:[" ",t.messageTitle]}),t.messageBody?n.jsx("div",{className:"text-gray-600",children:t.messageBody}):null]}),n.jsxs("div",{className:"mt-4",children:[n.jsxs("div",{className:"text-xs text-black font-medium",children:["Recipients (",t.total,")"]}),n.jsx("div",{className:"mt-2 flex flex-col gap-3 text-xs",children:(t.recipients||[]).map((r,i)=>{const a=String(r?.notificationReceipientType||"").toLowerCase()==="EscalationNotification".toLowerCase();return n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsxs("span",{className:"text-black",children:[r.name," - ",n.jsx("span",{style:{color:a?"#FF3B30":"#FFB86A"},children:a?"Escalation Notification":"Alert Notification"})]}),n.jsxs("span",{className:"text-gray-500",children:[r.role," . ",r.phone]})]}),n.jsx("span",{className:`text-[11px] px-3 py-[2px] rounded ${r.status==="Delivered"?"bg-green-50 text-green-700 border border-green-200":"bg-red-50 text-red-700 border border-red-200"}`,children:r.status})]},i)})})]})]},s)),e?.notifications?.length?null:n.jsx("span",{className:"text-gray-500 text-xs",children:"No notifications."})]})}]})})}const cn=({alertId:e,id:t,priority:s,spaceName:r,alertNumber:i,statusHistory:a,notifGroups:o})=>{const l={alertId:e??String(t??""),incidentId:"-",severity:s||"",location:r||"",alertNumber:i??""},f=a?.length?a.map(d=>{const A=(d?.status||d?.eventStatus||"").toLowerCase()==="completed"?"Completed":"Inprogress",m=d?.createdDate?ut(d.createdDate):d?.timestamp?ut(d.timestamp):"";return{status:A,title:d?.status||d?.eventStatus||"Status Update",description:d?.description||d?.actionNotes||"",timestamp:m}}):[],h={summary:l,timeline:f,notifications:o??[]};return n.jsx(ln,{data:h})};const un=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),dn=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,s,r)=>r?r.toUpperCase():s.toLowerCase()),Yt=e=>{const t=dn(e);return t.charAt(0).toUpperCase()+t.slice(1)},gs=(...e)=>e.filter((t,s,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===s).join(" ").trim(),hn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var fn={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const mn=u.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:s=2,absoluteStrokeWidth:r,className:i="",children:a,iconNode:o,...l},f)=>u.createElement("svg",{ref:f,...fn,width:t,height:t,stroke:e,strokeWidth:r?Number(s)*24/Number(t):s,className:gs("lucide",i),...!a&&!hn(l)&&{"aria-hidden":"true"},...l},[...o.map(([h,d])=>u.createElement(h,d)),...Array.isArray(a)?a:[a]]));const vs=(e,t)=>{const s=u.forwardRef(({className:r,...i},a)=>u.createElement(mn,{ref:a,iconNode:t,className:gs(`lucide-${un(Yt(e))}`,`lucide-${e}`,r),...i}));return s.displayName=Yt(e),s};const pn=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],xs=vs("maximize-2",pn);const yn=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],gn=vs("minimize-2",yn),vn=({isOpen:e,onClose:t,src:s,type:r="image"})=>{const[i,a]=u.useState(!1),[o,l]=u.useState(!1);return u.useEffect(()=>{e&&l(!1)},[e,s]),u.useEffect(()=>{e&&(!s||o)&&t()},[e,s,o,t]),e?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-70",role:"button",tabIndex:0,"aria-label":"Close media preview",onClick:t,onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),t())},onTouchStart:t,children:n.jsxs("div",{className:`relative ${i?"w-full h-full":"max-w-5xl max-h-[90vh] w-full"} flex items-center justify-center`,onClick:f=>f.stopPropagation(),children:[r==="image"?n.jsx("img",{src:s,alt:"preview",className:`object-contain rounded-lg shadow-lg ${i?"w-full h-full":"max-w-full max-h-[90vh]"}`,onError:()=>l(!0)}):n.jsx("video",{src:s,controls:!0,className:`object-contain rounded-lg shadow-lg ${i?"w-full h-full":"max-w-full max-h-[90vh]"}`,onError:()=>l(!0)}),n.jsx("button",{onClick:t,className:"absolute top-3 right-3 text-white bg-black/50 rounded-full p-2 hover:bg-black/70",children:"✕"}),n.jsx("button",{onClick:()=>a(!i),className:"absolute bottom-3 right-3 text-white bg-black/50 rounded-full p-2 hover:bg-black/70",children:i?n.jsx(gn,{size:20}):n.jsx(xs,{size:20})})]})}):null};function xn(e){if(!e||typeof e!="string")return!1;const t=e.split("?")[0].toLowerCase();return t.endsWith(".mp4")||t.endsWith(".webm")||t.endsWith(".ogg")||t.endsWith(".m3u8")}function st(e){const t=(e?.mediaType||e?.type||"").toString().toLowerCase();return t==="video"||t==="mp4"?!0:xn(e?.mediaUrl||e)}function bn(e){const t=e;return t?Array.isArray(t)?t:[t]:[]}const Sn={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},An={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},wn=({isModalOpen:e,handleModalClose:t,selectedRow:s,fetchAlertLogs:r,alertStatusList:i=[],alertStatusLoading:a=!1,initialTab:o="details",sourceTab:l})=>{const[f,h]=u.useState(),[d,A]=u.useState(""),[m,I]=u.useState(!1),w=u.useRef(null),[p,S]=u.useState("details"),[L,F]=u.useState(void 0),$=bt(),{alerts:U}=ye(),[V,Y]=u.useState(!1),[G,W]=u.useState(void 0),[T,C]=u.useState(void 0),[R,K]=u.useState({}),ee=s?.originalData||{},{eventName:E,alertId:v,timestamp:y,description:j,spaceName:g,assignTeam:x,priority:b,statusType:k,id:M,alertDetails:O,statusHistory:B,mediaDetails:q,alertNumber:z}=ee,ne=N=>{const Q=String(N||"").toLowerCase();return Q==="delivered"||Q==="sent"?"Delivered":Q==="failed"?"Failed":"Queued"},fe=N=>({name:N?.receipientName||N?.recipientName||"-",role:N?.receipientRoleName||"",phone:N?.receipentPhoneNumber||N?.recipientPhoneNumber||N?.receipientEmail||N?.recipientEmail||"",status:ne(N?.messageStatus),notificationReceipientType:N?.notificationReceipientType||""}),le=(N,Q)=>{const se=Q.map(fe),ue=se.filter(me=>me.status==="Delivered").length,Z=Q.map(me=>me?.sentAt).filter(Boolean).sort((me,Ze)=>new Date(Ze).getTime()-new Date(me).getTime())[0],ve=Q[0]||{},$e=[ve?.severityName,ve?.anomalyName].filter(Boolean).join(" - ")||`${N} Notification`;return{channelLabel:`${N} Notification`,sentAt:Z||"",messageTitle:$e,messageBody:"",total:se.length,delivered:ue,recipients:se}},re=N=>{const Q=new Map;return(N||[]).forEach(se=>{const ue=String(se?.notificationType||"Unknown"),Z=Q.get(ue)||[];Z.push(se),Q.set(ue,Z)}),Array.from(Q.entries()).map(([se,ue])=>le(se,ue))},ie=async N=>{try{const Q=await U.getAlertNotifications(N),se=re(Q);F(se)}catch{F(void 0)}};u.useEffect(()=>{if(p!=="track"||!M)return;let N=!1;return ie(M).then(()=>{N&&F(void 0)}),()=>{N=!0}},[p,M]),u.useEffect(()=>{e&&S(o)},[e,o]);const ge=l==="archived"||["completed","false positive"].includes(String(k||"").toLowerCase()),Ve=N=>{const Q=String(N?.value||"").toLowerCase(),se=String(N?.statusName||"").toLowerCase();return Q.includes("reopen")||se.includes("reopen")},Ue=(i||[]).filter(N=>{const Q=Ve(N);return typeof l<"u"?l==="archived"?Q:!Q:ge?Q:!Q}).map(N=>({value:N.value,label:N.statusName})),Ae=u.useMemo(()=>bn(q),[q]);u.useEffect(()=>{let N=!1;const Q=new AbortController,se=async Z=>{if(Z){N||K(ve=>({...ve,[Z]:!1}));try{const ve=await fetch(Z,{method:"HEAD",signal:Q.signal});if(ve.ok){N||K(me=>({...me,[Z]:!0}));return}if(ve.status===404){N||K(me=>({...me,[Z]:!1}));return}if(!(await fetch(Z,{method:"GET",signal:Q.signal})).ok)throw new Error("Media not available");N||K(me=>({...me,[Z]:!0}))}catch{N||K(ve=>({...ve,[Z]:!1}))}}};return K({}),Ae.filter(Z=>!st(Z)).map(Z=>Z?.mediaUrl||Z).filter(Z=>typeof Z=="string"&&Z.length>0).forEach(Z=>se(Z)),()=>{N=!0,Q.abort()}},[Ae]);const Je=async()=>{try{I(!0);const N={alertUniqueId:v,alertId:M,status:f?String(f):void 0,notes:d.trim(),modifiedBy:0},Q=await $.mutateAsync(N);if(Q?.responseStatus){const se=Q?.data||"Alert updated successfully.";he.toast.success(se,{autoClose:1500,onClose:()=>{r(),t()}}),h(void 0),A("")}else{const se=Q?.errorMessage||"Failed to update alert status";he.toast.error(se)}}catch(N){console.error("Error updating alert status:",N),he.toast.error("Failed to update alert status. Please try again.")}finally{I(!1)}};return n.jsx(c.Modal,{open:e,onCancel:t,width:1e3,styles:{body:{maxHeight:"70vh",overflowY:"auto"}},footer:p==="details"?n.jsxs("div",{className:"flex flex-row gap-2 justify-start",children:[n.jsx(c.Button,{onClick:t,className:"bg-[#6C757D] text-white",children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:Je,loading:m,children:m?"Saving...":"Save Changes"})]}):null,children:s&&n.jsx(c.Tabs,{activeKey:p,onChange:N=>S(N),items:[{key:"details",label:"Alert Detail",children:n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"flex flex-col gap-2",children:[n.jsx("div",{className:"text-sm font-bold",children:E||"Alert Event"}),O?.firstName?n.jsxs("div",{className:"text-sm text-gray-500",children:["Resident ID/Name: ",O?.firstName," ",O?.lastName||""," ",O?.residentId||""]}):null,n.jsxs("div",{className:"text-sm text-gray-500",children:["Timestamp: ",ut(y)]}),n.jsxs("div",{className:"font-sm text-gray-500",children:[n.jsx("b",{className:"text-black text-sm/6",children:"Description:"})," ",j||"No description available"]}),g&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Space: ",g]}),x&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Assigned to: ",x]}),n.jsxs("div",{className:"flex gap-2 justify-start mt-3",children:[n.jsxs(c.Tag,{className:"font-sm text-gray-500 rounded-[8px] py-2 px-3",style:{border:`2px solid ${Sn[String(b)]||"#DFE4EA"}`,backgroundColor:An[String(b)]},children:["Severity: ",b||"N/A"]}),n.jsxs(c.Tag,{className:"font-sm text-gray-500 rounded-[8px] py-2 px-3",style:String(k||"").toLowerCase()==="completed"?{background:"#E7F6EC",border:"0.68px solid var(--Green, #34C759)"}:{background:"#E0EDFF",border:"1px solid var(--Grays-Gray-4, #D1D1D6)"},children:["Status: ",k||"N/A"]})]}),n.jsx("div",{className:"w-full flex flex-col justify-start items-start mt-2 font-bold",children:n.jsxs("div",{className:"w-full mt-4",children:[n.jsx("div",{className:"flex flex-col gap-2",children:n.jsx(c.Select,{placeholder:"Change Status",className:"w-full text-gray-500",onChange:N=>h(N),value:f,options:Ue,loading:a})}),n.jsxs("div",{className:"flex flex-col gap-2 mt-3",children:[n.jsx("label",{htmlFor:"action-details-input",className:"text-xs text-gray-500 font-medium",children:"Action Taken (Comments)"}),n.jsx("textarea",{id:"action-details-input",placeholder:"Enter details...",className:"w-full text-gray-500 h-20 border border-grey-500 rounded-md p-2",value:d,onChange:N=>A(N.target.value)})]})]})})]}),n.jsx("div",{className:"flex flex-col gap-4",children:n.jsxs("div",{className:"w-full mt-1",children:[n.jsxs("div",{className:"w-full flex items-center justify-between",children:[n.jsx("h3",{className:"text-black font-bold text-sm",children:"Camera Footage"}),Ae.length>1?n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>w.current?.prev?.(),className:"w-6 h-6 flex items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 text-gray-600","aria-label":"Previous media",children:n.jsx(De.LeftOutlined,{style:{fontSize:12}})}),n.jsx("button",{type:"button",onClick:()=>w.current?.next?.(),className:"w-6 h-6 flex items-center justify-center rounded-full bg-gray-200 hover:bg-gray-300 text-gray-600","aria-label":"Next media",children:n.jsx(De.RightOutlined,{style:{fontSize:12}})})]}):null]}),Ae.length?n.jsx("div",{className:"w-full",children:n.jsx(c.Carousel,{ref:w,dots:!0,className:"w-full",children:Ae.map((N,Q)=>n.jsxs("div",{className:"flex justify-center items-center",children:[st(N)?n.jsxs("video",{width:"240",height:"200",controls:!0,className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg",children:[n.jsx("source",{src:N.mediaUrl||N}),"Your browser does not support the video tag."]}):n.jsx("img",{src:N.mediaUrl||N,alt:N.caption||`media-${Q}`,className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg"}),N.caption&&n.jsx("p",{className:"text-xs text-gray-500 mt-1",children:N.caption}),!st(N)&&R[String(N.mediaUrl||N)]?n.jsx("button",{onClick:()=>{Y(!0),W(N.mediaUrl||N),C(N.type||"image")},className:"absolute bottom-3 right-3 text-white bg-black/50 rounded-full p-2 hover:bg-black/70",children:n.jsx(xs,{size:20})}):null]},Q))})}):null]})}),n.jsx(vn,{isOpen:V,onClose:()=>Y(!1),src:G||"",type:T||"image"})]})},{key:"track",label:"Track Incident",children:n.jsx(cn,{alertId:v,id:M,priority:b,spaceName:g,alertNumber:z,statusHistory:B,notifGroups:L})}]})})};function bs(){const{alerts:e}=ye(),t=xt({queryKey:["alerts","statusList"],queryFn:()=>e.getAlertStatusList(),staleTime:5*6e4});return{list:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function St({alerts:e,loading:t=!1,columns:s,onRefetch:r}){const[i,a]=u.useState(!1),[o,l]=u.useState(null),[f,h]=u.useState("details"),{list:d,loading:A}=bs();function m(L,F){l(L),h(F?.tab??"details"),p(F?.sourceTab??"active"),a(!0)}function I(){a(!1)}const[w,p]=u.useState("active"),S=o?{originalData:{...o,alertId:o.alertId??o.id,mediaDetails:o.mediaDetails}}:null;return n.jsxs("div",{className:"p-6 flex flex-col items-start justify-start min-h-screen w-full overflow-auto",children:[n.jsxs("div",{className:"w-1/2 flex items-center justify-between mb-4",children:[n.jsx("h1",{className:"text-xl font-bold text-black",children:"Alert Console"}),n.jsx(hs,{label:"USA",timeZone:"America/New_York"})]}),n.jsx(c.Tabs,{defaultActiveKey:"active",className:"w-full",tabBarStyle:{fontSize:"medium"},onChange:L=>{L==="active"&&r?.()},items:[{key:"active",label:"Active",children:n.jsx(ft,{data:e,loading:t,pageSize:10,columns:s||[],onAlertIdClick:m,onRefetch:r})},{key:"archived",label:"Archived",children:n.jsx(ds,{alerts:e,loading:t,columns:s||[],onAlertIdClick:m})},{key:"settings",label:"Settings",children:n.jsx(jn,{})}]}),n.jsx(wn,{isModalOpen:i,handleModalClose:I,selectedRow:S,fetchAlertLogs:()=>{},alertStatusList:d,alertStatusLoading:A,initialTab:f,sourceTab:w})]})}function jn(){const[e,t]=u.useState([]),[s,r]=u.useState([]),[i,a]=u.useState([]),{rules:o}=ye();return u.useEffect(()=>{let l=!0;return(async()=>{try{const f=await o.getRules();if(!l)return;a(Array.isArray(f)?f:[]);const h=(f||[]).map((d,A)=>({RuleId:d.ruleId||d.ruleName||String(A),Name:d.ruleName||d.Name||"-",Description:d.ruleDesc||d.Description||"",SeverityId:0}));t(h.length?h:Pe.rules);try{const d=await o.getLookups(),A=Array.isArray(d?.userRoles)?d.userRoles.map(m=>({userRoleId:m.userRoleId??m.id,userRoleName:m.userRoleName??m.name})):[];r(A.length?A:Pe.userRoles)}catch{r(Pe.userRoles)}}catch{t(Pe.rules),r(Pe.userRoles)}})(),()=>{l=!1}},[]),n.jsx(ys,{severities:Pe.severities,rules:e,userRoles:s,rawRules:i})}function Ss(){const{alerts:e}=ye(),t=xt({queryKey:["alerts","list"],queryFn:()=>e.listAlerts(),staleTime:3e4});return{alerts:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function Nn(e){const{alerts:t,loading:s,refetch:r}=Ss();return n.jsx(St,{alerts:t,loading:s,columns:e.columns,onRefetch:r})}function Cn({tenant:e,apiDomain:t,rulesDomain:s,headers:r,alerts:i,loading:a,columns:o}){const[l]=u.useState(()=>new kr),f=u.useMemo(()=>({alertsBaseUrl:t,rulesBaseUrl:s||t,headers:r||void 0}),[t,s,r]);return n.jsx(Er,{client:l,children:n.jsx(es,{tenant:e,override:f,children:Array.isArray(i)?n.jsx(St,{alerts:i,loading:!!a,columns:o}):n.jsx(Nn,{columns:o})})})}function Tn(e){const{alerts:t}=ye(),s=xt({queryKey:["alerts","report",e],queryFn:()=>t.getAlertsReport(e),staleTime:6e4});return{data:s.data??[],loading:s.isLoading,error:s.error,refetch:s.refetch}}const In=[{title:"ID",dataIndex:"id",key:"id",width:120},{title:"Priority",dataIndex:"priority",key:"priority",width:120},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:220},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description"}];exports.AlertAssignment=fs;exports.AlertConsole=St;exports.AlertConsoleWidget=Cn;exports.AlertsTable=ft;exports.ApiProvider=es;exports.ArchivedTable=ds;exports.Clock=hs;exports.DataTable=ts;exports.MyPreferencesPanel=ps;exports.SettingsPanel=ms;exports.SettingsTabs=ys;exports.exampleAlertColumns=In;exports.useAlertStatusList=bs;exports.useAlerts=Ss;exports.useAlertsReport=Tn;exports.useApi=ye;exports.useUpdateAlertStatus=bt;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|