@ssgc/alert-console 2.4.0 → 2.4.1
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 +1060 -1054
- 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"),u=require("react"),c=require("antd"),Ee=require("@ant-design/icons"),me=require("react-toastify");function Rs(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 ue=Rs(u),ks="#FF3B30",Es="#FF9500",Ms="#FFCC00",Os="#34C759",Be={critical:ks,high:Es,medium:Ms,low:Os},Ct={Critical:Be.critical,High:Be.high,Medium:Be.medium,Low:Be.low};function Ps(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 st(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="",Ds=zt,Fs="",Us="",It={snl:{alerts:zt,rules:Ds},schools:{alerts:Fs,rules:Us}};function ve(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{}}}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 xe(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||{}};return{async listAlerts(){const s=ve(e.baseUrl,"/api/Alert"),r=await xe(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertStatusList(){const s=ve(e.baseUrl,"/api/Alert/AlertStatusList"),r=await xe(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=ve(e.baseUrl,"/Alerts/GetAlertsReport"),i=qe(r,s),a=await xe(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=ve(e.baseUrl,"/api/Alert/status");return xe(r,{method:"PUT",headers:t,body:JSON.stringify(s??{})})},async getAdminSettings(){const s=ve(e.baseUrl,"/api/Alert/GetAdminSettings"),r=await xe(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=ve(e.baseUrl,"/api/Alert/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??"",groupBy:s?.groupBy??null};return xe(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=ve(e.baseUrl,"/api/Alert/GetPreferenceSettings"),r=await xe(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=ve(e.baseUrl,"/api/Alert/SetPreferenceSettings"),i=await xe(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=ve(e.baseUrl,"/api/Alert/GetNotifications"),i=qe(r,{alertId:s}),a=await xe(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=ve(e.baseUrl,"/api/Alert/NotificationToFamilyMembers"),i=qe(r,{alertId:s});return xe(i,{method:"POST",headers:t})},async sendSMSorEmailNotifications(s,r,i){const a=ve(e.baseUrl,"/api/Alert/SendSMSorEmailNotifications"),o=qe(a,{alertId:s,isEmail:r,isSMS:i});return xe(o,{method:"POST",headers:t})},async getTimeZoneMasters(){const s=ve(e.baseUrl,"/api/UserPreference/GetTimeZoneMasters"),r=await xe(s,{method:"GET",headers:t});return Array.isArray(r)?r:r&&typeof r=="object"&&Array.isArray(r.data)?r.data:[]}}}function Rt(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{}}}async function _e(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?.errorMessage||a?.message||`HTTP ${r.status}`;throw new Error(o)}return a}function qs(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 _s(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ge={exports:{}},Qs=Ge.exports,kt;function Hs(){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+)?$/,B=/\[([^\]]+)]|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,U={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(k){var x=["th","st","nd","rd"],y=k%100;return"["+k+(x[(y-20)%10]||x[y]||x[0])+"]"}},L=function(k,x,y){var j=String(k);return!j||j.length>=x?k:""+Array(x+1-j.length).join(y)+k},E={s:L,z:function(k){var x=-k.utcOffset(),y=Math.abs(x),j=Math.floor(y/60),g=y%60;return(x<=0?"+":"-")+L(j,2,"0")+":"+L(g,2,"0")},m:function k(x,y){if(x.date()<y.date())return-k(y,x);var j=12*(y.year()-x.year())+(y.month()-x.month()),g=x.clone().add(j,A),b=y-g<0,v=x.clone().add(j+(b?-1:1),A);return+(-(j+(y-g)/(b?g-v:v-g))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:A,y:I,w:d,d:h,D:w,h:f,m:l,s:o,ms:a,Q:m}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},z="en",G={};G[z]=U;var W="$isDayjsObject",Y=function(k){return k instanceof K||!(!k||!k[W])},T=function k(x,y,j){var g;if(!x)return z;if(typeof x=="string"){var b=x.toLowerCase();G[b]&&(g=b),y&&(G[b]=y,g=b);var v=x.split("-");if(!g&&v.length>1)return k(v[0])}else{var M=x.name;G[M]=x,g=M}return!j&&g&&(z=g),g||!j&&z},C=function(k,x){if(Y(k))return k.clone();var y=typeof x=="object"?x:{};return y.date=k,y.args=arguments,new K(y)},R=E;R.l=T,R.i=Y,R.w=function(k,x){return C(k,{locale:x.$L,utc:x.$u,x:x.$x,$offset:x.$offset})};var K=(function(){function k(y){this.$L=T(y.locale,null,!0),this.parse(y),this.$x=this.$x||y.x||{},this[W]=!0}var x=k.prototype;return x.parse=function(y){this.$d=(function(j){var g=j.date,b=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 v=g.match(S);if(v){var M=v[2]-1||0,$=(v[7]||"0").substring(0,3);return b?new Date(Date.UTC(v[1],M,v[3]||1,v[4]||0,v[5]||0,v[6]||0,$)):new Date(v[1],M,v[3]||1,v[4]||0,v[5]||0,v[6]||0,$)}}return new Date(g)})(y),this.init()},x.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()},x.$utils=function(){return R},x.isValid=function(){return this.$d.toString()!==p},x.isSame=function(y,j){var g=C(y);return this.startOf(j)<=g&&g<=this.endOf(j)},x.isAfter=function(y,j){return C(y)<this.startOf(j)},x.isBefore=function(y,j){return this.endOf(j)<C(y)},x.$g=function(y,j,g){return R.u(y)?this[j]:this.set(g,y)},x.unix=function(){return Math.floor(this.valueOf()/1e3)},x.valueOf=function(){return this.$d.getTime()},x.startOf=function(y,j){var g=this,b=!!R.u(j)||j,v=R.p(y),M=function(de,se){var oe=R.w(g.$u?Date.UTC(g.$y,se,de):new Date(g.$y,se,de),g);return b?oe:oe.endOf(h)},$=function(de,se){return R.w(g.toDate()[de].apply(g.toDate("s"),(b?[0,0,0,0]:[23,59,59,999]).slice(se)),g)},O=this.$W,F=this.$M,q=this.$D,Z="set"+(this.$u?"UTC":"");switch(v){case I:return b?M(1,0):M(31,11);case A:return b?M(1,F):M(0,F+1);case d:var re=this.$locale().weekStart||0,ae=(O<re?O+7:O)-re;return M(b?q-ae:q+(6-ae),F);case h:case w:return $(Z+"Hours",0);case f:return $(Z+"Minutes",1);case l:return $(Z+"Seconds",2);case o:return $(Z+"Milliseconds",3);default:return this.clone()}},x.endOf=function(y){return this.startOf(y,!1)},x.$set=function(y,j){var g,b=R.p(y),v="set"+(this.$u?"UTC":""),M=(g={},g[h]=v+"Date",g[w]=v+"Date",g[A]=v+"Month",g[I]=v+"FullYear",g[f]=v+"Hours",g[l]=v+"Minutes",g[o]=v+"Seconds",g[a]=v+"Milliseconds",g)[b],$=b===h?this.$D+(j-this.$W):j;if(b===A||b===I){var O=this.clone().set(w,1);O.$d[M]($),O.init(),this.$d=O.set(w,Math.min(this.$D,O.daysInMonth())).$d}else M&&this.$d[M]($);return this.init(),this},x.set=function(y,j){return this.clone().$set(y,j)},x.get=function(y){return this[R.p(y)]()},x.add=function(y,j){var g,b=this;y=Number(y);var v=R.p(j),M=function(F){var q=C(b);return R.w(q.date(q.date()+Math.round(F*y)),b)};if(v===A)return this.set(A,this.$M+y);if(v===I)return this.set(I,this.$y+y);if(v===h)return M(1);if(v===d)return M(7);var $=(g={},g[l]=r,g[f]=i,g[o]=s,g)[v]||1,O=this.$d.getTime()+y*$;return R.w(O,this)},x.subtract=function(y,j){return this.add(-1*y,j)},x.format=function(y){var j=this,g=this.$locale();if(!this.isValid())return g.invalidDate||p;var b=y||"YYYY-MM-DDTHH:mm:ssZ",v=R.z(this),M=this.$H,$=this.$m,O=this.$M,F=g.weekdays,q=g.months,Z=g.meridiem,re=function(se,oe,Se,ge){return se&&(se[oe]||se(j,b))||Se[oe].slice(0,ge)},ae=function(se){return R.s(M%12||12,se,"0")},de=Z||function(se,oe,Se){var ge=se<12?"AM":"PM";return Se?ge.toLowerCase():ge};return b.replace(B,(function(se,oe){return oe||(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 re(g.monthsShort,O,q,3);case"MMMM":return re(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 re(g.weekdaysMin,j.$W,F,2);case"ddd":return re(g.weekdaysShort,j.$W,F,3);case"dddd":return F[j.$W];case"H":return String(M);case"HH":return R.s(M,2,"0");case"h":return ae(1);case"hh":return ae(2);case"a":return de(M,$,!0);case"A":return de(M,$,!1);case"m":return String($);case"mm":return R.s($,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 v}return null})(se)||v.replace(":","")}))},x.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},x.diff=function(y,j,g){var b,v=this,M=R.p(j),$=C(y),O=($.utcOffset()-this.utcOffset())*r,F=this-$,q=function(){return R.m(v,$)};switch(M){case I:b=q()/12;break;case A:b=q();break;case m:b=q()/3;break;case d:b=(F-O)/6048e5;break;case h:b=(F-O)/864e5;break;case f:b=F/i;break;case l:b=F/r;break;case o:b=F/s;break;default:b=F}return g?b:R.a(b)},x.daysInMonth=function(){return this.endOf(A).$D},x.$locale=function(){return G[this.$L]},x.locale=function(y,j){if(!y)return this.$L;var g=this.clone(),b=T(y,j,!0);return b&&(g.$L=b),g},x.clone=function(){return R.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()},k})(),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(k){ee[k[1]]=function(x){return this.$g(x,k[0],k[1])}})),C.extend=function(k,x){return k.$i||(k(x,K,C),k.$i=!0),C},C.locale=T,C.isDayjs=Y,C.unix=function(k){return C(1e3*k)},C.en=G[z],C.Ls=G,C.p={},C}))})(Ge)),Ge.exports}var Gs=Hs();const Zt=_s(Gs);function Vt(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 Jt(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}=Jt(e);return Zt().hour(t).minute(s).second(r).millisecond(0)}function je(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Ws(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function Mt(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 Ne(e,t){const s={...t.headers,...Ws()},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 ie=(...e)=>e.find(t=>t!=null);function Ks(e){return{id:String(ie(e?.AlertId,e?.alertId)??""),priority:ie(e?.Priority,e?.priority,"Low"),timestamp:ie(e?.Timestamp,e?.timestamp,""),statusType:ie(e?.Status,e?.statusType,""),description:ie(e?.Description,e?.description,""),eventName:ie(e?.EventName,e?.eventName),ruleName:ie(e?.RuleName,e?.ruleName),spaceName:ie(e?.SpaceName,e?.spaceName),assignTeam:ie(e?.AssignTeam,e?.assignTeam),cameraName:ie(e?.CameraName,e?.cameraName),type:ie(e?.Type,e?.type),mediaDetails:ie(e?.MediaDetails,e?.mediaDetails),additionalMedia:ie(e?.AdditionalMedia,e?.additionalMedia),timeElapsed:ie(e?.TimeElapsed,e?.timeElapsed),timeRemaining:ie(e?.TimeRemaining,e?.timeRemaining),anomalyName:ie(e?.AnomalyName,e?.anomalyName),alertDetails:ie(e?.AlertDetails,e?.alertDetails),statusHistory:ie(e?.StatusHistory,e?.statusHistory),isEmailSent:ie(e?.IsEmailSent,e?.isEmailSent),isSMSSent:ie(e?.IsSMSSent,e?.isSMSSent),timeZoneUniqueId:ie(e?.TimeZoneUniqueId,e?.timeZoneUniqueId)}}function Ys(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=je(e.baseUrl,"/api/detectionpolicy/alerts?customerId=99e5c8b5-b9d4-4d35-8885-7f121c532664"),r=await Ne(s,{method:"GET",headers:t});return Array.isArray(r?.Items)?(r?.Items).map(Ks):[]},async getAlertStatusList(){const s=je(e.baseUrl,"/api/detectionpolicy/alerts/StatusList"),r=await Ne(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertsReport(s){const r=je(e.baseUrl,"/api/detectionpolicy/alerts/GetAlertsReport"),i=Mt(r,s),a=await Ne(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=je(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 Ne(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getAdminSettings(){const s=je(e.baseUrl,"/api/detectionpolicy/alerts/GetAdminSettings"),r=await Ne(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=je(e.baseUrl,"/api/detectionpolicy/alerts/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??""};return Ne(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=je(e.baseUrl,"/api/detectionpolicy/alerts/GetPreferenceSettings"),r=await Ne(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=je(e.baseUrl,"/api/detectionpolicy/alerts/SetPreferenceSettings"),i=h=>{const{hours:d,minutes:A,seconds:m}=Jt(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 Ne(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=je(e.baseUrl,"/api/detectionpolicy/alerts/GetNotifications"),i=Mt(r,{alertId:s}),a=await Ne(i,{method:"GET",headers:t});return Array.isArray(a)?a:a&&typeof a=="object"&&Array.isArray(a.data)?a.data:[]}}}function zs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Te(e,t){const s={...t.headers,...zs()},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 Zs(e){const t={"Content-Type":"application/json",...e.headers||{}},s=new URL("/api/detectionpolicy/rules",e.baseUrl).toString();return{async getRules(){const r=await Te(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async setEscalationSettings(r){return Te(s,{method:"POST",headers:t,body:JSON.stringify(r??{})})},async getLookups(){const r=E=>new URL(E,e.baseUrl).toString(),i=[Te(r("/api/detectionpolicy/lookups/actiontypes"),{method:"GET",headers:t}),Te(r("/api/detectionpolicy/lookups/anomalies"),{method:"GET",headers:t}),Te(r("/api/detectionpolicy/lookups/thirdparty"),{method:"GET",headers:t}),Te(r("/api/detectionpolicy/lookups/severity"),{method:"GET",headers:t}),Te(r("/api/detectionpolicy/lookups/scheduletypes"),{method:"GET",headers:t})],[a,o,l,f,h]=await Promise.allSettled(i),d=E=>E.status==="fulfilled"&&Array.isArray(E.value)?E.value:[],A=d(a),m=d(o),I=d(l),w=d(f),p=d(h),S=A.map(E=>({actionTypeId:Number(E?.ActionTypeId),name:E?.DisplayName??E?.Name??""})),B=m.map(E=>({recordId:E?.AnomalyId,anomalyName:E?.DisplayName??E?.Name??""})),U=I.map(E=>({thirdPartyId:Number(E?.ThirdPartyId),thirdPartyName:E?.ThirdPartyName??E?.Name??""})),L={actionTypes:S,anomalies:B,thirdParties:U};return w.length&&(L.severities=w),p.length&&(L.scheduleTypes=p),L},async updateRule(r,i){const a=`${s}/${r}`;return Te(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"?Ys({baseUrl:r.alertsBaseUrl,headers:r.headers}):$s({baseUrl:r.alertsBaseUrl,headers:r.headers}),o=r.tenant==="schools"?Zs({baseUrl:r.rulesBaseUrl,headers:r.headers}):qs({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 Vs={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Js={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},ht=6,ft=7;function Xs(e,t,s){const r=e===ht,i=e===ft,a=t.isEmailSent??!1,o=t.isSMSSent??!1,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 er(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 tr(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 Ot(e,t){return`${e}-${t?"email":"sms"}`}function Pt(e){return e===ht||e===ft}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 sr=[{label:"All levels",value:"All"},{label:"Critical",value:"Critical"},{label:"High",value:"High"},{label:"Medium",value:"Medium"},{label:"Low",value:"Low"}];function rr({value:e,onChange:t,options:s}){return n.jsx(ze,{className:"w-[140px]",value:e,onChange:t,options:s||sr})}const nr=[{label:"All Types",value:"All"},{label:"Weapon Detection",value:"Weapon"},{label:"Unauthorized Access",value:"Unauthorized"},{label:"Aggressive Behavior",value:"Aggressive"}];function ir({value:e,onChange:t,options:s}){return n.jsx(ze,{className:"w-[220px]",dropdownWidth:280,value:e,onChange:t,options:s||nr})}function ar({value:e,onChange:t,options:s}){return n.jsx(ze,{className:"w-[100px]",value:e,onChange:t,options:s||[]})}const or=[{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 lr({value:e,onChange:t,options:s}){return n.jsx(ze,{className:"w-[130px]",value:e,onChange:t,options:s||or})}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 mt({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,B]=u.useState("All"),[U,L]=u.useState(""),[E,z]=u.useState([{label:"All",value:"All"}]),[G,W]=u.useState(new Set),{rules:Y,alerts:T}=ye(),C={6:{title:"Email",kind:"icon",icon:n.jsx(Ee.MailOutlined,{})},7:{title:"SMS",kind:"icon",icon:n.jsx(Ee.MessageOutlined,{})}},R=u.useMemo(()=>er(e),[e]),K=u.useMemo(()=>tr(e),[e]);u.useEffect(()=>{let b=!0;return(async()=>{try{const v=await Y.getLookups(),$=(Array.isArray(v.thirdParties)?v.thirdParties:[]).map(O=>({label:O.thirdPartyName,value:String(O.thirdPartyId)}));b&&z([{label:"All",value:"All"},...$])}catch(v){console.error("Error loading third party options",v)}})(),()=>{b=!1}},[Y]);const ee=u.useMemo(()=>(e||[]).some(b=>st(b).length>0),[e]),k=u.useMemo(()=>(e||[]).filter(b=>{const v=d==="All"||b.priority===d,M=`${b.id} ${b.description} ${b.statusType}`.toLowerCase(),$=!U||M.includes(U.toLowerCase()),O=m==="All"||(b.anomalyName||"").toLowerCase()===m.toLowerCase(),F=w==="All"||(b.spaceName||"").toLowerCase()===w.toLowerCase(),q=!ee||S==="All"||st(b).includes(Number(S)),Z=!h||!["completed","false positive"].includes(String(b.statusType||"").toLowerCase());return v&&$&&O&&F&&q&&Z}),[e,d,U,m,w,S,ee,h]),x=R,y=a&&a.length?a:K,j=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:b=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${Js[b]}`,backgroundColor:Vs[b]},children:b})},{title:"Tracker",key:"tracker",width:140,render:(b,v)=>n.jsx("a",{onClick:M=>{M.preventDefault(),l?.(v,{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:(b,v)=>{if(o)return n.jsx(n.Fragment,{children:o(v)});const M=st(v);if(!M.length)return null;const $=async(O,F)=>{const q=Ot(v.id,O);W(Z=>new Set(Z).add(q));try{const Z=await T.sendSMSorEmailNotifications?.(v.id,O,F);Z?.responseStatus?(me.toast.success(Z.data||(O?"Email sent successfully":"SMS sent successfully")),f?.()):me.toast.error(Z?.data||Z?.errorMessage||"Failed to send notification")}catch(Z){me.toast.error(Z?.message||"Failed to send notification")}finally{W(Z=>{const re=new Set(Z);return re.delete(q),re})}};return n.jsx(c.Space,{size:"middle",children:M.map(O=>{const F=C[O];if(!F)return null;const q=O===ht,Z=O===ft,{isDisabled:re,buttonText:ae,tooltipTitle:de}=Xs(O,v,F?.title),se=Ot(v.id,q),oe=Pt(O)&&G.has(se),Se=()=>{$(q,Z)};return n.jsx(c.Tooltip,{title:de,children:n.jsx(c.Button,{size:"small",disabled:re,loading:oe,onClick:Pt(O)?Se:void 0,icon:!oe&&(F.kind==="img"&&F.src?n.jsx("img",{src:F.src,alt:F.alt||F.title}):F.icon),className:"flex flex-col items-center justify-center gap-1",style:{height:"fit-content"},children:ae})},O)})})}},{title:"Alert Timestamp",dataIndex:"timestamp",key:"timestamp",width:220,render:(b,v)=>{const M=v?.timeElapsed,$=v?.timeRemaining,O=M?Tt(M):0,F=$?Tt($):0,q=Math.round(O/(O+F)*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:M??"-"})]}),n.jsx(c.Progress,{percent:q,showInfo:!1,size:"small",strokeColor:Ps(v.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:$??"-"})]})]})}},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(b,v)=>n.jsxs("div",{children:[n.jsx("a",{onClick:M=>{M.preventDefault(),l?.(v,{sourceTab:"active"})},className:"inline-block mb-1 text-blue-600",children:v.alertNumber}),n.jsx("div",{className:"text-black/65",children:b})]})}],g=r&&r.length?r:j;return n.jsx("div",{children:n.jsx(ts,{rowKey:"id",data:k,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(rr,{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(ir,{value:m,onChange:I,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(ar,{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(lr,{value:S,onChange:B,options:E})]})}),n.jsx(c.Col,{flex:"auto"}),n.jsx(c.Col,{flex:"none",children:n.jsx(c.Input.Search,{allowClear:!0,placeholder:"Search",onSearch:L,onChange:b=>L(b.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(){}},cr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ur=class{#e=cr;#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)}},ke=new ur;function dr(e){setTimeout(e,0)}var Me=typeof window>"u"||"Deno"in globalThis;function fe(){}function hr(e,t){return typeof e=="function"?e(t):e}function nt(e){return typeof e=="number"&&e>=0&&e!==1/0}function ss(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ie(e,t){return typeof e=="function"?e(t):e}function be(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!==pt(o,t.options))return!1}else if(!$e(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(Oe(t.options.mutationKey)!==Oe(a))return!1}else if(!$e(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function pt(e,t){return(t?.queryKeyHashFn||Oe)(e)}function Oe(e){return JSON.stringify(e,(t,s)=>at(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}function $e(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>$e(e[s],t[s])):!1}var fr=Object.prototype.hasOwnProperty;function it(e,t,s=0){if(e===t)return e;if(s>500)return t;const r=Ut(e)&&Ut(t);if(!r&&!(at(e)&&at(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:fr.call(e,A))&&h++;continue}if(m===null||I===null||typeof m!="object"||typeof I!="object"){f[A]=I;continue}const w=it(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 at(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 mr(e){return new Promise(t=>{ke.setTimeout(t,e)})}function ot(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 it(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 it(e,t)}return t}function pr(e,t,s=0){const r=[...e,t];return s&&r.length>s?r.slice(1):r}function yr(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 yt(e,t){return typeof e=="function"?e(...t):!!e}function gr(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 vr=class extends Fe{#e;#t;#s;constructor(){super(),this.#s=e=>{if(!Me&&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"}},gt=new vr;function lt(){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 xr=dr;function br(){let e=[],t=0,s=l=>{l()},r=l=>{l()},i=xr;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 le=br(),Sr=class extends Fe{#e=!0;#t;#s;constructor(){super(),this.#s=e=>{if(!Me&&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 Sr;function Ar(e){return Math.min(1e3*2**e,3e4)}function ns(e){return(e??"online")==="online"?Ye.isOnline():!0}var ct=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=lt(),a=()=>i.status!=="pending",o=p=>{if(!a()){const S=new ct(p);m(S),e.onCancel?.(S)}},l=()=>{t=!0},f=()=>{t=!1},h=()=>gt.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(B){p=Promise.reject(B)}Promise.resolve(p).then(A).catch(B=>{if(a())return;const U=e.retry??(Me?0:3),L=e.retryDelay??Ar,E=typeof L=="function"?L(s,B):L,z=U===!0||typeof U=="number"&&s<U||typeof U=="function"&&U(s,B);if(t||!z){m(B);return}s++,e.onFail?.(s,B),mr(E).then(()=>h()?void 0:I()).then(()=>{t?m(B):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(),nt(this.gcTime)&&(this.#e=ke.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Me?1/0:300*1e3))}clearGcTimeout(){this.#e&&(ke.clearTimeout(this.#e),this.#e=void 0)}},wr=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=ot(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(fe).catch(fe):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>be(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=>Ie(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 ct&&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 ct){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),le.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 jr=class extends Fe{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=lt(),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 ut(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return ut(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 be(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||be(this.options.enabled,this.#t)!==be(t.enabled,this.#t)||Ie(this.options.staleTime,this.#t)!==Ie(t.staleTime,this.#t))&&this.#y();const i=this.#g();r&&(this.#t!==s||be(this.options.enabled,this.#t)!==be(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 Cr(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(fe)),t}#y(){this.#b();const e=Ie(this.options.staleTime,this.#t);if(Me||this.#n.isStale||!nt(e))return;const s=ss(this.#n.dataUpdatedAt,e)+1;this.#c=ke.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,!(Me||be(this.options.enabled,this.#t)===!1||!nt(this.#l)||this.#l===0)&&(this.#u=ke.setInterval(()=>{(this.options.refetchIntervalInBackground||gt.isFocused())&&this.#d()},this.#l))}#x(){this.#y(),this.#v(this.#g())}#b(){this.#c&&(ke.clearTimeout(this.#c),this.#c=void 0)}#S(){this.#u&&(ke.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 Y=this.hasListeners(),T=!Y&&qt(e,t),C=Y&&_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 Y;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(Y=i.data,S=!0):Y=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,Y!==void 0&&(p="success",m=ot(i?.data,Y,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=ot(i?.data,m,t),this.#h=m,this.#i=null}catch(Y){this.#i=Y}this.#i&&(I=this.#i,m=this.#h,w=Date.now(),p="error");const B=d.fetchStatus==="fetching",U=p==="pending",L=p==="error",E=U&&B,z=m!==void 0,W={status:p,fetchStatus:d.fetchStatus,isPending:U,isSuccess:p==="success",isError:L,isInitialLoading:E,isLoading:E,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:B,isRefetching:B&&!U,isLoadingError:L&&!z,isPaused:d.fetchStatus==="paused",isPlaceholderData:A,isRefetchError:L&&z,isStale:vt(e,t),refetch:this.refetch,promise:this.#o,isEnabled:be(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const Y=W.data!==void 0,T=W.status==="error"&&!Y,C=ee=>{T?ee.reject(W.error):Y&&ee.resolve(W.data)},R=()=>{const ee=this.#o=W.promise=lt();C(ee)},K=this.#o;switch(K.status){case"pending":e.queryHash===s.queryHash&&C(K);break;case"fulfilled":(T||W.data!==K.value)&&R();break;case"rejected":(!T||W.error!==K.reason)&&R();break}}return W}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){le.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Nr(e,t){return be(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function qt(e,t){return Nr(e,t)||e.state.data!==void 0&&ut(e,t,t.refetchOnMount)}function ut(e,t,s){if(be(t.enabled,e)!==!1&&Ie(t.staleTime,e)!=="static"){const r=typeof s=="function"?s(e):s;return r==="always"||r!==!1&&vt(e,t)}return!1}function _t(e,t,s,r){return(e!==t||be(r.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&vt(e,s)}function vt(e,t){return be(t.enabled,e)!==!1&&e.isStaleByTime(Ie(t.staleTime,e))}function Cr(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=>{gr(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 U=(()=>{const G={client:t.client,queryKey:t.queryKey,pageParam:p,direction:S?"backward":"forward",meta:t.options.meta};return A(G),G})(),L=await m(U),{maxPages:E}=t.options,z=S?yr:pr;return{pages:z(w.pages,L,E),pageParams:z(w.pageParams,p,E)}};if(i&&a.length){const w=i==="backward",p=w?Tr:Ht,S={pages:a,pageParams:o},B=p(r,S);l=await I(S,B,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 Tr(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}var Ir=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),le.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 Rr=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 Ir({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(){le.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){le.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return le.batch(()=>Promise.all(e.map(t=>t.continue().catch(fe))))}};function Qe(e){return e.options.scope?.id}var kr=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&&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??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){le.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)})})}},Er=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??pt(r,t);let a=this.get(i);return a||(a=new wr({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(){le.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){le.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){le.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){le.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Mr=class{#e;#t;#s;#n;#r;#a;#o;#i;constructor(e={}){this.#e=e.queryCache||new Er,this.#t=e.mutationCache||new Rr,this.#s=e.defaultOptions||{},this.#n=new Map,this.#r=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=gt.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(Ie(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=hr(t,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return le.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;le.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#e;return le.batch(()=>(s.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},r=le.batch(()=>this.#e.findAll(e).map(i=>i.cancel(s)));return Promise.all(r).then(fe).catch(fe)}invalidateQueries(e,t={}){return le.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=le.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(fe)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(fe)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#e.build(this,t);return s.isStaleByTime(Ie(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(fe).catch(fe)}fetchInfiniteQuery(e){return e.behavior=Qt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(fe).catch(fe)}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(Oe(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(r=>{$e(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=>{$e(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=pt(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=ue.createContext(void 0),xt=e=>{const t=ue.useContext(cs);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Or=({client:e,children:t})=>(ue.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),n.jsx(cs.Provider,{value:e,children:t})),us=ue.createContext(!1),Pr=()=>ue.useContext(us);us.Provider;function Dr(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Fr=ue.createContext(Dr()),Ur=()=>ue.useContext(Fr),Lr=(e,t,s)=>{const r=s?.state.error&&typeof e.throwOnError=="function"?yt(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},$r=e=>{ue.useEffect(()=>{e.clearReset()},[e])},Br=({result:e,errorResetBoundary:t,throwOnError:s,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||yt(s,[e.error,r])),qr=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))}},_r=(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 Hr(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=Pr(),i=Ur(),a=xt(),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",qr(o),Lr(o,i,l),$r(i);const f=!a.getQueryCache().get(o.queryHash),[h]=ue.useState(()=>new t(a,o)),d=h.getOptimisticResult(o),A=!r&&e.subscribed!==!1;if(ue.useSyncExternalStore(ue.useCallback(m=>{const I=A?h.subscribe(le.batchCalls(m)):fe;return h.updateResult(),I},[h,A]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),ue.useEffect(()=>{h.setOptions(o)},[o,h]),Qr(o,d))throw Gt(o,h,i);if(Br({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&&!Me&&_r(d,r)&&(f?Gt(o,h,i):l?.promise)?.catch(fe).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?d:h.trackResult(d)}function Ze(e,t){return Hr(e,jr)}function Gr(e,t){const s=xt(),[r]=ue.useState(()=>new kr(s,e));ue.useEffect(()=>{r.setOptions(e)},[r,e]);const i=ue.useSyncExternalStore(ue.useCallback(o=>r.subscribe(le.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=ue.useCallback((o,l)=>{r.mutate(o,l).catch(fe)},[r]);if(i.error&&yt(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function bt(){const{alerts:e}=ye(),t=xt();return Gr({mutationFn:s=>e.updateAlertStatus(s),onSuccess:()=>{t.invalidateQueries({queryKey:["alerts","list"]}),t.invalidateQueries({queryKey:["alerts","report"]})}})}function Wr(e,t){return e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZone:t})}function Kr(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 Yr(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 dt(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 zr={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},Zr={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.";me.toast.success(w)}else{const w=I?.errorMessage||"Failed to reopen alert";me.toast.error(w)}}catch{me.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 ${zr[m]}`,backgroundColor:Zr[String(m)]},children:m})},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:200,render:m=>Yr(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(Ee.MoreOutlined,{})})})}],A=(e||[]).filter(m=>f.includes((m.statusType||"").toLowerCase()));return n.jsx(mt,{data:A,loading:t,pageSize:s,columns:d,severityOptions:r,anomalyOptions:i,spaceOptions:a,renderActions:void 0,onAlertIdClick:o,excludeCompleted:!1})}function Vr({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),B=h+p*Math.cos(S),U=h+p*Math.sin(S),L=h+w*Math.cos(S),E=h+w*Math.sin(S);return n.jsx("svg",{className:"absolute inset-0",width:e,height:e,children:n.jsx("line",{x1:B,y1:U,x2:L,y2:E,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(()=>Wr(i,t),[i,t]),{abbr:l,offset:f}=u.useMemo(()=>Kr(i,t),[i,t]);return n.jsxs("div",{className:`flex items-center gap-3 ${r||""}`,children:[n.jsx(Vr,{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 Jr=[{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}],Xr=[{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"}],en=[{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"}],De={severities:Jr,rules:Xr,userRoles:en},{Text:tn}=c.Typography;function sn({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(tn,{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:Ce}=c.Typography;function rn(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:B,actions:U,setActions:L,thirdPartyIds:E,setThirdPartyIds:z,humanLoop:G,setHumanLoop:W,isAutoExpire:Y,setAutoExpire:T,onClear:C,onSave:R,saving:K,onActionTypesLoaded:ee}=e,{rules:k}=ye(),[x,y]=u.useState([]),[j,g]=u.useState([]),[b,v]=u.useState(!1);u.useEffect(()=>{let F=!1;return(async()=>{try{v(!0);const q=await k.getLookups();if(F||!q||!Array.isArray(q.actionTypes))return;const Z=q.actionTypes.map(ae=>({label:ae.name,value:String(ae.actionTypeId)}));y(Z),ee&&ee(q.actionTypes);const re=Array.isArray(q.thirdParties)?q.thirdParties.map(ae=>({label:ae.thirdPartyName,value:ae.thirdPartyId})):[];g(re)}catch(q){console.error("Error loading lookups",q)}finally{F||v(!1)}})(),()=>{F=!0}},[]);const M=F=>n.jsxs(c.Tag,{children:[n.jsx(Ee.PlusOutlined,{})," ",F.length," more"]}),$=typeof o=="number"||typeof f=="number"||typeof d=="number"||typeof m=="number"||typeof w=="number"||typeof S=="number"||Array.isArray(U)&&U.length>0||Array.isArray(E)&&E.length>0||!!G||!!Y,O=!!t&&$&&!K;return n.jsxs(c.Spin,{spinning:!!K||b,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(Ce,{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(Ce,{className:"text-gray-700 font-medium block mb-1",children:"Level 1 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ce,{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(Ce,{className:"text-gray-700 font-medium block mb-1",children:"Level 2 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ce,{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(Ce,{className:"text-gray-700 font-medium block mb-1",children:"Level 3 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ce,{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:B,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ce,{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:U,onChange:L,options:x,maxTagCount:1,maxTagPlaceholder:M})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ce,{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:E,onChange:z,options:j})]})})]}),n.jsxs(c.Row,{gutter:[16,16],align:"bottom",className:"mt-4 items-center",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:7,children:n.jsxs("div",{className:"flex items-center h-full gap-8",children:[n.jsx(c.Checkbox,{checked:G,onChange:F=>W(F.target.checked),className:"w-full",children:"Human-In-The-Loop"}),n.jsx(c.Checkbox,{checked:Y,onChange:F=>T(F.target.checked),className:"w-full",children:"Auto-expire in 5 minutes"})]})}),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:C,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:R,loading:!!K,disabled:!O,children:"Save"})]})})]})]})}function nn({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?.length?l.actions.join(", "):"-"},{title:"Notify",key:"notify",render:(o,l)=>l.notify?.length?l.notify.join(", "):"-"},{title:"Human-In-The-Loop",key:"humanLoop",render:(o,l)=>l.humanLoop?"Yes":"No"},{title:"Auto Expire",key:"isAutoExpire",render:(o,l)=>l.isAutoExpire?"Yes":"No"},{title:"Actions",key:"ops",render:(o,l)=>n.jsx(c.Button,{type:"text",onClick:()=>s(l.id),children:n.jsx(Ee.EditOutlined,{})})}]})}const{Title:an}=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 B=o.find(L=>L?.ruleId===S.key||L?.ruleName===S.key||L?.RuleId===S.key||L?.ruleName===S.ruleName||L?.Name===S.ruleName),U=Array.isArray(B?.userRoleIds)?B.userRoleIds:[];U.length&&(p[S.key]=U)}return p},[o,A]),I=()=>{h({})},w=async()=>{try{if(!o||!Array.isArray(o)||Object.keys(f).length===0){me.toast.info("No changes to save");return}a(!0);const p=Object.entries(f).map(async([S,B])=>{const U=o.find(W=>W?.ruleId===S||W?.ruleName===S||W?.RuleId===S),L=typeof U?.recordId=="number"?U.recordId:void 0;if(!U||typeof L!="number")throw new Error(`Unable to find recordId for rule ${S}`);const E=Array.isArray(B)?B:[],z=E.map(W=>{const Y=e.find(T=>T.userRoleId===W);return{id:W,name:Y?.userRoleName??String(W)}}),G={...U,ruleId:S,userRoleIds:E,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(L,G)});await Promise.all(p),me.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(an,{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:B=>h(U=>({...U,[S.key]:B})),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),[B,U]=u.useState(!1),[L,E]=u.useState(null),[z,G]=u.useState("rules"),[W,Y]=u.useState(),[T,C]=u.useState(),[R,K]=u.useState(),[ee,k]=u.useState(),[x,y]=u.useState(),[j,g]=u.useState(),[b,v]=u.useState(),[M,$]=u.useState(),[O,F]=u.useState([]),[q,Z]=u.useState([]),[re,ae]=u.useState(!1),[de,se]=u.useState(!1),[oe,Se]=u.useState({}),[ge,Ve]=u.useState({}),[Pe,Re]=u.useState(s||[]),[Ue,N]=u.useState([]),[H,ne]=u.useState(!1),[Ae,J]=u.useState(!1),[ce,Le]=u.useState(r||[]);u.useEffect(()=>{r&&r.length&&Le(r)},[r]),u.useEffect(()=>{if(!ce||!ce.length)return;const P=Object.keys(oe).length>0||Object.keys(ge).length>0;if(Ue.length&&!P)return;const X=ce.map((_,D)=>{const V=t.find(he=>he.RuleId===(_.ruleId||_.ruleName))?.Name||_.ruleName||_.Name||"-",Q=_.escalationSettings||{},te=typeof Q.level1UserRoleId=="number"&&Q.level1UserRoleId>0?[Q.level1UserRoleId]:[],we=typeof Q.level2UserRoleId=="number"&&Q.level2UserRoleId>0?[Q.level2UserRoleId]:[],Xe=typeof Q.level3UserRoleId=="number"&&Q.level3UserRoleId>0?[Q.level3UserRoleId]:[],wt=(Array.isArray(Q.escalationSettingsActionTypeIds)?Q.escalationSettingsActionTypeIds:[]).map(he=>oe[he]||String(he)),Nt=(Array.isArray(Q.thirdPartyId)?Q.thirdPartyId:[]).map(he=>ge[he]||String(he)),et=typeof Q.humanLoop=="boolean"?Q.humanLoop:null,tt=typeof Q.isAutoExpire=="boolean"?Q.isAutoExpire:null;return{id:String(_.ruleId||_.ruleName||D),ruleOrSeverityLabel:V,l1:{minutes:Q.level1PostAssistTime??void 0,roles:te},l2:{minutes:Q.level2PostAssistTime??void 0,roles:we},l3:{minutes:Q.level3PostAssistTime??void 0,roles:Xe},actions:wt,notify:Nt,humanLoop:et,isAutoExpire:tt}});N(X)},[ce,t,oe,ge]);const pe=u.useMemo(()=>e.map(P=>({label:P.DisplayName,value:P.SeverityId})),[e]),Je=u.useMemo(()=>t.map(P=>({label:P.Name,value:P.RuleId})),[t]),As=u.useMemo(()=>Pe.map(P=>({label:P.userRoleName,value:P.userRoleId})),[Pe]),ws=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{U(!0),E(null);const _=await o.getAdminSettings();if(!P&&_){const D=Vt(_.sortBy);f(D),m(D),w(!1)}}catch(_){if(!P){const D=_ instanceof Error?_.message:"Failed to load admin settings";E(D)}}finally{P||U(!1)}}return X(),()=>{P=!0}},[]),u.useEffect(()=>{if(!T)return;const P=V=>{const Q=Number(V);return!isNaN(Q)&&Q>0?Q:void 0},X=V=>{const Q=Number(V);return!isNaN(Q)&&Q>0?Q:void 0},D=(ce||[]).find(V=>V?.ruleId===T||V?.ruleName===T||V?.RuleId===T)?.escalationSettings;if(D&&typeof D=="object"){K(X(D.level1PostAssistTime)),k(P(D.level1UserRoleId)),y(X(D.level2PostAssistTime)),g(P(D.level2UserRoleId)),v(X(D.level3PostAssistTime)),$(P(D.level3UserRoleId));const V=Array.isArray(D.escalationSettingsActionTypeIds)?D.escalationSettingsActionTypeIds:[];F(V.map(Q=>String(Q))),Z(Array.isArray(D.thirdPartyId)?D.thirdPartyId:[]),ae(!!D.humanLoop),se(!!D.isAutoExpire)}},[z,T,ce]);const js=async()=>{try{J(!0);const P=await a.getRules(),X=Array.isArray(P)?P:Array.isArray(P?.data)?P.data:[];Le(X);const _=X.map((D,V)=>{const Q=t.find(he=>he.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(he=>oe[he]||String(he)),et=(Array.isArray(te.thirdPartyId)?te.thirdPartyId:[]).map(he=>ge[he]||String(he)),tt=typeof te.humanLoop=="boolean"?te.humanLoop:null;return{id:String(D.ruleId||D.ruleName||V),ruleOrSeverityLabel:Q,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:tt}});N(_)}catch(P){console.error("Failed to refetch entries",P)}finally{J(!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 V of X.thirdParties)typeof V.thirdPartyId=="number"&&(_[V.thirdPartyId]=V.thirdPartyName);Ve(_);const D=Array.isArray(X.userRoles)?X.userRoles.map(V=>({userRoleId:V.userRoleId??V.id,userRoleName:V.userRoleName??V.name})):[];P||Re(D.length?D:s||[])}catch(X){console.error("Error loading lookups",X)}})(),()=>{P=!0}},[]);const Ns=async()=>{S(!0);try{const P=await o.setAdminSettings({sortBy:l,groupBy:"string"});P?.responseStatus&&P?.data&&me.toast.success(P.data),m(l),w(!1)}catch(P){console.error("Error saving admin settings",P)}finally{S(!1)}},Cs=()=>{f(A),w(!1)},Ts=async()=>{ne(!0),i?.({ruleId:T,levels:[{minutes:R,role:ee},{minutes:x,role:j},{minutes:b,role:M}],actions:O,thirdPartyIds:q,humanLoop:re,isAutoExpire:de});try{if(T){const _=Array.isArray(O)?O.map(we=>Number(we)):[],D=(ce||[]).find(we=>we?.ruleId===T||we?.ruleName===T||we?.RuleId===T),V=typeof D?.recordId=="number"?D.recordId:void 0;if(!D||typeof V!="number"){me.toast.error("Unable to find rule recordId for update");return}const Q={...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:x??0,level3UserRoleId:M??0,level3PostAssistTime:b??0,escalationSettingsActionTypeIds:_,thirdPartyId:Array.isArray(q)?q:[],humanLoop:re,isAutoExpire:de}},te=await a.updateRule(V,Q);if(te?.responseStatus||te?.ok||te){me.toast.success("Escalation settings saved"),await js(),C(void 0),K(void 0),k(void 0),y(void 0),g(void 0),v(void 0),$(void 0),F([]),Z([]),ae(!1),se(!1);return}}}catch(_){console.error("Error saving escalation settings",_)}finally{ne(!1)}const X=t.find(_=>_.RuleId===T)?.Name||"-";N(_=>[..._,{id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ruleOrSeverityLabel:X,l1:{minutes:R,roles:ee?[ee]:[]},l2:{minutes:x,roles:j?[j]:[]},l3:{minutes:b,roles:M?[M]:[]},actions:(Array.isArray(O)?O:[]).map(D=>{const V=Number(D);return oe[V]||String(D)}),notify:(Array.isArray(q)?q:[]).map(D=>ge[D]||String(D)),humanLoop:!!re,isAutoExpire:!!de}])},Is=()=>{f("By Severity"),d("By severity"),G("rules"),Y(void 0),C(void 0),K(void 0),k(void 0),y(void 0),g(void 0),v(void 0),$(void 0),F([]),Z([]),ae(!1),se(!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:B,children:[L?n.jsxs("div",{className:"text-sm text-red-600 mb-2",children:["Failed to load settings: ",L]}):null,n.jsx(sn,{sortBy:l,groupBy:h,onChange:P=>{P.sortBy&&(f(P.sortBy),w(!0)),P.groupBy&&(d(P.groupBy),w(!0))},showActions:I,onSave:Ns,onClear:Cs,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(rn,{escBasis:z,setEscBasis:G,selectedSeverity:W,setSelectedSeverity:Y,selectedRule:T,setSelectedRule:C,severityOptions:pe,ruleOptions:Je,minsOptions:ws,roleOptions:As,l1mins:R,setL1mins:K,l1role:ee,setL1role:k,l2mins:x,setL2mins:y,l2role:j,setL2role:g,l3mins:b,setL3mins:v,l3role:M,setL3role:$,actions:O,setActions:F,thirdPartyIds:q,setThirdPartyIds:Z,humanLoop:re,setHumanLoop:ae,onClear:Is,onSave:Ts,saving:H,onActionTypesLoaded:P=>{const X={};for(const _ of P)typeof _.actionTypeId=="number"&&(X[_.actionTypeId]=_.name);Se(X)},isAutoExpire:de,setAutoExpire:se})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(nn,{entries:Ue,userRoles:Pe,loading:Ae,onEdit:P=>{G("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:Pe,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}),[B,U]=u.useState([]),[L,E]=u.useState(!0),[z,G]=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=Vt(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{E(!0);const C=await i.getLookups();if(T||!C)return;const R=Array.isArray(C.anomalies)?C.anomalies:[];U(R)}catch(C){console.error("Failed to load anomalies lookups",C)}finally{T||E(!1)}})(),()=>{T=!0}},[]);const W=T=>{d(C=>{const R=new Set(C);return R.has(T)?R.delete(T):R.add(T),R})},Y=async()=>{s?.({sortBy:l,subscribedRuleIds:Array.from(h),dnd:{from:A,to:I},channels:p});try{G(!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&&me.toast.success(K?.data||"Preferences updated successfully.")}catch(T){console.error("Error in saving my preferences: ",T)}finally{G(!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"}),L?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(B)?B:[]).map(T=>{const C=String(T.recordId),R=T.anomalyName;return n.jsx(c.Checkbox,{checked:h.has(C),onChange:()=>W(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:z,children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:Y,loading:z,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 on="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=",ln="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 cn(e){const t=(e.status||"").toLowerCase()==="completed"?n.jsx("img",{src:on,alt:"completed",style:{width:20,height:20}}):n.jsx("img",{src:ln,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 un({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(cn)})})]})]})},{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:Zt(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 dn=({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?dt(d.createdDate):d?.timestamp?dt(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(un,{data:h})};const hn=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),fn=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,s,r)=>r?r.toUpperCase():s.toLowerCase()),Yt=e=>{const t=fn(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(),mn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var pn={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 yn=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,...pn,width:t,height:t,stroke:e,strokeWidth:r?Number(s)*24/Number(t):s,className:gs("lucide",i),...!a&&!mn(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(yn,{ref:a,iconNode:t,className:gs(`lucide-${hn(Yt(e))}`,`lucide-${e}`,r),...i}));return s.displayName=Yt(e),s};const gn=[["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",gn);const vn=[["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"}]],xn=vs("minimize-2",vn),bn=({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(xn,{size:20}):n.jsx(xs,{size:20})})]})}):null};function Sn(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 rt(e){const t=(e?.mediaType||e?.type||"").toString().toLowerCase();return t==="video"||t==="mp4"?!0:Sn(e?.mediaUrl||e)}function An(e){const t=e;return t?Array.isArray(t)?t:[t]:[]}const wn={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},jn={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Nn=({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"),[B,U]=u.useState(void 0),L=bt(),{alerts:E}=ye(),[z,G]=u.useState(!1),[W,Y]=u.useState(void 0),[T,C]=u.useState(void 0),[R,K]=u.useState({}),ee=s?.originalData||{},{eventName:k,alertId:x,timestamp:y,description:j,spaceName:g,assignTeam:b,priority:v,statusType:M,id:$,alertDetails:O,statusHistory:F,mediaDetails:q,alertNumber:Z}=ee,re=N=>{const H=String(N||"").toLowerCase();return H==="delivered"||H==="sent"?"Delivered":H==="failed"?"Failed":"Queued"},ae=N=>({name:N?.receipientName||N?.recipientName||"-",role:N?.receipientRoleName||"",phone:N?.receipentPhoneNumber||N?.recipientPhoneNumber||N?.receipientEmail||N?.recipientEmail||"",status:re(N?.messageStatus),notificationReceipientType:N?.notificationReceipientType||""}),de=(N,H)=>{const ne=H.map(ae),Ae=ne.filter(pe=>pe.status==="Delivered").length,J=H.map(pe=>pe?.sentAt).filter(Boolean).sort((pe,Je)=>new Date(Je).getTime()-new Date(pe).getTime())[0],ce=H[0]||{},Le=[ce?.severityName,ce?.anomalyName].filter(Boolean).join(" - ")||`${N} Notification`;return{channelLabel:`${N} Notification`,sentAt:J||"",messageTitle:Le,messageBody:"",total:ne.length,delivered:Ae,recipients:ne}},se=N=>{const H=new Map;return(N||[]).forEach(ne=>{const Ae=String(ne?.notificationType||"Unknown"),J=H.get(Ae)||[];J.push(ne),H.set(Ae,J)}),Array.from(H.entries()).map(([ne,Ae])=>de(ne,Ae))},oe=async N=>{try{const H=await E.getAlertNotifications(N),ne=se(H);U(ne)}catch{U(void 0)}};u.useEffect(()=>{if(p!=="track"||!$)return;let N=!1;return oe($).then(()=>{N&&U(void 0)}),()=>{N=!0}},[p,$]),u.useEffect(()=>{e&&S(o)},[e,o]);const ge=l==="archived"||["completed","false positive"].includes(String(M||"").toLowerCase()),Ve=N=>{const H=String(N?.value||"").toLowerCase(),ne=String(N?.statusName||"").toLowerCase();return H.includes("reopen")||ne.includes("reopen")},Pe=(i||[]).filter(N=>{const H=Ve(N);return typeof l<"u"?l==="archived"?H:!H:ge?H:!H}).map(N=>({value:N.value,label:N.statusName})),Re=u.useMemo(()=>An(q),[q]);u.useEffect(()=>{let N=!1;const H=new AbortController,ne=async J=>{if(J){N||K(ce=>({...ce,[J]:!1}));try{const ce=await fetch(J,{method:"HEAD",signal:H.signal});if(ce.ok){N||K(pe=>({...pe,[J]:!0}));return}if(ce.status===404){N||K(pe=>({...pe,[J]:!1}));return}if(!(await fetch(J,{method:"GET",signal:H.signal})).ok)throw new Error("Media not available");N||K(pe=>({...pe,[J]:!0}))}catch{N||K(ce=>({...ce,[J]:!1}))}}};return K({}),Re.filter(J=>!rt(J)).map(J=>J?.mediaUrl||J).filter(J=>typeof J=="string"&&J.length>0).forEach(J=>ne(J)),()=>{N=!0,H.abort()}},[Re]);const Ue=async()=>{try{I(!0);const N={alertUniqueId:x,alertId:$,status:f?String(f):void 0,notes:d.trim(),modifiedBy:0},H=await L.mutateAsync(N);if(H?.responseStatus){const ne=H?.data||"Alert updated successfully.";me.toast.success(ne,{autoClose:1500,onClose:()=>{r(),t()}}),h(void 0),A("")}else{const ne=H?.errorMessage||"Failed to update alert status";me.toast.error(ne)}}catch(N){console.error("Error updating alert status:",N),me.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:Ue,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:k||"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: ",dt(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]}),b&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Assigned to: ",b]}),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 ${wn[String(v)]||"#DFE4EA"}`,backgroundColor:jn[String(v)]},children:["Severity: ",v||"N/A"]}),n.jsxs(c.Tag,{className:"font-sm text-gray-500 rounded-[8px] py-2 px-3",style:String(M||"").toLowerCase()==="completed"?{background:"#E7F6EC",border:"0.68px solid var(--Green, #34C759)"}:{background:"#E0EDFF",border:"1px solid var(--Grays-Gray-4, #D1D1D6)"},children:["Status: ",M||"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:Pe,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"}),Re.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(Ee.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(Ee.RightOutlined,{style:{fontSize:12}})})]}):null]}),Re.length?n.jsx("div",{className:"w-full",children:n.jsx(c.Carousel,{ref:w,dots:!0,className:"w-full",children:Re.map((N,H)=>n.jsxs("div",{className:"flex justify-center items-center",children:[rt(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-${H}`,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}),!rt(N)&&R[String(N.mediaUrl||N)]?n.jsx("button",{onClick:()=>{G(!0),Y(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]},H))})}):null]})}),n.jsx(bn,{isOpen:z,onClose:()=>G(!1),src:W||"",type:T||"image"})]})},{key:"track",label:"Track Incident",children:n.jsx(dn,{alertId:x,id:$,priority:v,spaceName:g,alertNumber:Z,statusHistory:F,notifGroups:B})}]})})};function bs(){const{alerts:e}=ye(),t=Ze({queryKey:["alerts","statusList"],queryFn:()=>e.getAlertStatusList(),staleTime:5*6e4});return{list:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function Cn(){const{alerts:e}=ye(),t=Ze({queryKey:["alerts","timeZoneMasters"],queryFn:()=>e.getTimeZoneMasters?e.getTimeZoneMasters():Promise.resolve([]),staleTime:30*6e4,enabled:typeof e.getTimeZoneMasters=="function"});return{timeZoneMasters:t.data??[],loading:t.isLoading,error:t.error}}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(),{timeZoneMasters:m}=Cn(),I=u.useMemo(()=>{const E="America/New_York";if(!e.length||!m.length)return{label:"USA",ianaTimeZoneId:E};const z=e[0].timeZoneUniqueId;if(!z)return{label:"USA",ianaTimeZoneId:E};const G=m.find(W=>W.timeZoneUniqueId===z);return G?{label:G.timeZoneName,ianaTimeZoneId:G.ianaTimeZoneId}:{label:"USA",ianaTimeZoneId:E}},[e,m]);function w(L,E){l(L),h(E?.tab??"details"),B(E?.sourceTab??"active"),a(!0)}function p(){a(!1)}const[S,B]=u.useState("active"),U=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:I.label,timeZone:I.ianaTimeZoneId})]}),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(mt,{data:e,loading:t,pageSize:10,columns:s||[],onAlertIdClick:w,onRefetch:r})},{key:"archived",label:"Archived",children:n.jsx(ds,{alerts:e,loading:t,columns:s||[],onAlertIdClick:w})},{key:"settings",label:"Settings",children:n.jsx(Tn,{})}]}),n.jsx(Nn,{isModalOpen:i,handleModalClose:p,selectedRow:U,fetchAlertLogs:()=>{},alertStatusList:d,alertStatusLoading:A,initialTab:f,sourceTab:S})]})}function Tn(){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:De.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:De.userRoles)}catch{r(De.userRoles)}}catch{t(De.rules),r(De.userRoles)}})(),()=>{l=!1}},[]),n.jsx(ys,{severities:De.severities,rules:e,userRoles:s,rawRules:i})}function Ss(){const{alerts:e}=ye(),t=Ze({queryKey:["alerts","list"],queryFn:()=>e.listAlerts(),staleTime:3e4});return{alerts:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function In(e){const{alerts:t,loading:s,refetch:r}=Ss();return n.jsx(St,{alerts:t,loading:s,columns:e.columns,onRefetch:r})}function Rn({tenant:e,apiDomain:t,rulesDomain:s,headers:r,alerts:i,loading:a,columns:o}){const[l]=u.useState(()=>new Mr),f=u.useMemo(()=>({alertsBaseUrl:t,rulesBaseUrl:s||t,headers:r||void 0}),[t,s,r]);return n.jsx(Or,{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(In,{columns:o})})})}function kn(e){const{alerts:t}=ye(),s=Ze({queryKey:["alerts","report",e],queryFn:()=>t.getAlertsReport(e),staleTime:6e4});return{data:s.data??[],loading:s.isLoading,error:s.error,refetch:s.refetch}}const En=[{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=Rn;exports.AlertsTable=mt;exports.ApiProvider=es;exports.ArchivedTable=ds;exports.Clock=hs;exports.DataTable=ts;exports.MyPreferencesPanel=ps;exports.SettingsPanel=ms;exports.SettingsTabs=ys;exports.exampleAlertColumns=En;exports.useAlertStatusList=bs;exports.useAlerts=Ss;exports.useAlertsReport=kn;exports.useApi=ye;exports.useUpdateAlertStatus=bt;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),u=require("react"),c=require("antd"),Me=require("@ant-design/icons"),pe=require("react-toastify");function ks(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 de=ks(u),Es="#FF3B30",Ms="#FF9500",Os="#FFCC00",Ps="#34C759",qe={critical:Es,high:Ms,medium:Os,low:Ps},Tt={Critical:qe.critical,High:qe.high,Medium:qe.medium,Low:qe.low};function Ds(e){return Tt[e]||Tt.Low}function It(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 Rt(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="",Fs=Zt,Us="",Ls="",kt={snl:{alerts:Zt,rules:Fs},schools:{alerts:Us,rules:Ls}};function be(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function $s(){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 Se(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 Bs(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=be(e.baseUrl,"/api/Alert"),r=await Se(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertStatusList(){const s=be(e.baseUrl,"/api/Alert/AlertStatusList"),r=await Se(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=be(e.baseUrl,"/Alerts/GetAlertsReport"),i=_e(r,s),a=await Se(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=be(e.baseUrl,"/api/Alert/status");return Se(r,{method:"PUT",headers:t,body:JSON.stringify(s??{})})},async getAdminSettings(){const s=be(e.baseUrl,"/api/Alert/GetAdminSettings"),r=await Se(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=be(e.baseUrl,"/api/Alert/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??"",groupBy:s?.groupBy??null};return Se(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=be(e.baseUrl,"/api/Alert/GetPreferenceSettings"),r=await Se(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=be(e.baseUrl,"/api/Alert/SetPreferenceSettings"),i=await Se(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=be(e.baseUrl,"/api/Alert/GetNotifications"),i=_e(r,{alertId:s}),a=await Se(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=be(e.baseUrl,"/api/Alert/NotificationToFamilyMembers"),i=_e(r,{alertId:s});return Se(i,{method:"POST",headers:t})},async sendSMSorEmailNotifications(s,r,i){const a=be(e.baseUrl,"/api/Alert/SendSMSorEmailNotifications"),o=_e(a,{alertId:s,isEmail:r,isSMS:i});return Se(o,{method:"POST",headers:t})},async getTimeZoneMasters(){const s=be(e.baseUrl,"/api/UserPreference/GetTimeZoneMasters"),r=await Se(s,{method:"GET",headers:t});return Array.isArray(r)?r:r&&typeof r=="object"&&Array.isArray(r.data)?r.data:[]}}}function Et(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function qs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Qe(e,t){const s={...t.headers,...qs()},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=Et(e.baseUrl,"/api/Rules"),r=Et(e.baseUrl,"/api/Rules/lookups");return{async getRules(){const i=await Qe(s,{method:"GET",headers:t});return Array.isArray(i)?i:[]},async setEscalationSettings(i){return Qe(s,{method:"POST",headers:t,body:JSON.stringify(i??{})})},async getLookups(){return Qe(r,{method:"GET",headers:t})},async updateRule(i,a){const o=`${s}/${i}`;return Qe(o,{method:"PUT",headers:t,body:JSON.stringify(a??{})})}}}function Qs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ke={exports:{}},Hs=Ke.exports,Mt;function Gs(){return Mt||(Mt=1,(function(e,t){(function(s,r){e.exports=r()})(Hs,(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+)?$/,$=/\[([^\]]+)]|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(k){var x=["th","st","nd","rd"],y=k%100;return"["+k+(x[(y-20)%10]||x[y]||x[0])+"]"}},L=function(k,x,y){var j=String(k);return!j||j.length>=x?k:""+Array(x+1-j.length).join(y)+k},E={s:L,z:function(k){var x=-k.utcOffset(),y=Math.abs(x),j=Math.floor(y/60),g=y%60;return(x<=0?"+":"-")+L(j,2,"0")+":"+L(g,2,"0")},m:function k(x,y){if(x.date()<y.date())return-k(y,x);var j=12*(y.year()-x.year())+(y.month()-x.month()),g=x.clone().add(j,A),b=y-g<0,v=x.clone().add(j+(b?-1:1),A);return+(-(j+(y-g)/(b?g-v:v-g))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:A,y:I,w:d,d:h,D:w,h:f,m:l,s:o,ms:a,Q:m}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},z="en",H={};H[z]=F;var W="$isDayjsObject",Y=function(k){return k instanceof K||!(!k||!k[W])},T=function k(x,y,j){var g;if(!x)return z;if(typeof x=="string"){var b=x.toLowerCase();H[b]&&(g=b),y&&(H[b]=y,g=b);var v=x.split("-");if(!g&&v.length>1)return k(v[0])}else{var M=x.name;H[M]=x,g=M}return!j&&g&&(z=g),g||!j&&z},C=function(k,x){if(Y(k))return k.clone();var y=typeof x=="object"?x:{};return y.date=k,y.args=arguments,new K(y)},R=E;R.l=T,R.i=Y,R.w=function(k,x){return C(k,{locale:x.$L,utc:x.$u,x:x.$x,$offset:x.$offset})};var K=(function(){function k(y){this.$L=T(y.locale,null,!0),this.parse(y),this.$x=this.$x||y.x||{},this[W]=!0}var x=k.prototype;return x.parse=function(y){this.$d=(function(j){var g=j.date,b=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 v=g.match(S);if(v){var M=v[2]-1||0,D=(v[7]||"0").substring(0,3);return b?new Date(Date.UTC(v[1],M,v[3]||1,v[4]||0,v[5]||0,v[6]||0,D)):new Date(v[1],M,v[3]||1,v[4]||0,v[5]||0,v[6]||0,D)}}return new Date(g)})(y),this.init()},x.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()},x.$utils=function(){return R},x.isValid=function(){return this.$d.toString()!==p},x.isSame=function(y,j){var g=C(y);return this.startOf(j)<=g&&g<=this.endOf(j)},x.isAfter=function(y,j){return C(y)<this.startOf(j)},x.isBefore=function(y,j){return this.endOf(j)<C(y)},x.$g=function(y,j,g){return R.u(y)?this[j]:this.set(g,y)},x.unix=function(){return Math.floor(this.valueOf()/1e3)},x.valueOf=function(){return this.$d.getTime()},x.startOf=function(y,j){var g=this,b=!!R.u(j)||j,v=R.p(y),M=function(he,ee){var oe=R.w(g.$u?Date.UTC(g.$y,ee,he):new Date(g.$y,ee,he),g);return b?oe:oe.endOf(h)},D=function(he,ee){return R.w(g.toDate()[he].apply(g.toDate("s"),(b?[0,0,0,0]:[23,59,59,999]).slice(ee)),g)},U=this.$W,B=this.$M,q=this.$D,se="set"+(this.$u?"UTC":"");switch(v){case I:return b?M(1,0):M(31,11);case A:return b?M(1,B):M(0,B+1);case d:var ie=this.$locale().weekStart||0,ae=(U<ie?U+7:U)-ie;return M(b?q-ae:q+(6-ae),B);case h:case w:return D(se+"Hours",0);case f:return D(se+"Minutes",1);case l:return D(se+"Seconds",2);case o:return D(se+"Milliseconds",3);default:return this.clone()}},x.endOf=function(y){return this.startOf(y,!1)},x.$set=function(y,j){var g,b=R.p(y),v="set"+(this.$u?"UTC":""),M=(g={},g[h]=v+"Date",g[w]=v+"Date",g[A]=v+"Month",g[I]=v+"FullYear",g[f]=v+"Hours",g[l]=v+"Minutes",g[o]=v+"Seconds",g[a]=v+"Milliseconds",g)[b],D=b===h?this.$D+(j-this.$W):j;if(b===A||b===I){var U=this.clone().set(w,1);U.$d[M](D),U.init(),this.$d=U.set(w,Math.min(this.$D,U.daysInMonth())).$d}else M&&this.$d[M](D);return this.init(),this},x.set=function(y,j){return this.clone().$set(y,j)},x.get=function(y){return this[R.p(y)]()},x.add=function(y,j){var g,b=this;y=Number(y);var v=R.p(j),M=function(B){var q=C(b);return R.w(q.date(q.date()+Math.round(B*y)),b)};if(v===A)return this.set(A,this.$M+y);if(v===I)return this.set(I,this.$y+y);if(v===h)return M(1);if(v===d)return M(7);var D=(g={},g[l]=r,g[f]=i,g[o]=s,g)[v]||1,U=this.$d.getTime()+y*D;return R.w(U,this)},x.subtract=function(y,j){return this.add(-1*y,j)},x.format=function(y){var j=this,g=this.$locale();if(!this.isValid())return g.invalidDate||p;var b=y||"YYYY-MM-DDTHH:mm:ssZ",v=R.z(this),M=this.$H,D=this.$m,U=this.$M,B=g.weekdays,q=g.months,se=g.meridiem,ie=function(ee,oe,xe,ye){return ee&&(ee[oe]||ee(j,b))||xe[oe].slice(0,ye)},ae=function(ee){return R.s(M%12||12,ee,"0")},he=se||function(ee,oe,xe){var ye=ee<12?"AM":"PM";return xe?ye.toLowerCase():ye};return b.replace($,(function(ee,oe){return oe||(function(xe){switch(xe){case"YY":return String(j.$y).slice(-2);case"YYYY":return R.s(j.$y,4,"0");case"M":return U+1;case"MM":return R.s(U+1,2,"0");case"MMM":return ie(g.monthsShort,U,q,3);case"MMMM":return ie(q,U);case"D":return j.$D;case"DD":return R.s(j.$D,2,"0");case"d":return String(j.$W);case"dd":return ie(g.weekdaysMin,j.$W,B,2);case"ddd":return ie(g.weekdaysShort,j.$W,B,3);case"dddd":return B[j.$W];case"H":return String(M);case"HH":return R.s(M,2,"0");case"h":return ae(1);case"hh":return ae(2);case"a":return he(M,D,!0);case"A":return he(M,D,!1);case"m":return String(D);case"mm":return R.s(D,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 v}return null})(ee)||v.replace(":","")}))},x.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},x.diff=function(y,j,g){var b,v=this,M=R.p(j),D=C(y),U=(D.utcOffset()-this.utcOffset())*r,B=this-D,q=function(){return R.m(v,D)};switch(M){case I:b=q()/12;break;case A:b=q();break;case m:b=q()/3;break;case d:b=(B-U)/6048e5;break;case h:b=(B-U)/864e5;break;case f:b=B/i;break;case l:b=B/r;break;case o:b=B/s;break;default:b=B}return g?b:R.a(b)},x.daysInMonth=function(){return this.endOf(A).$D},x.$locale=function(){return H[this.$L]},x.locale=function(y,j){if(!y)return this.$L;var g=this.clone(),b=T(y,j,!0);return b&&(g.$L=b),g},x.clone=function(){return R.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()},k})(),X=K.prototype;return C.prototype=X,[["$ms",a],["$s",o],["$m",l],["$H",f],["$W",h],["$M",A],["$y",I],["$D",w]].forEach((function(k){X[k[1]]=function(x){return this.$g(x,k[0],k[1])}})),C.extend=function(k,x){return k.$i||(k(x,K,C),k.$i=!0),C},C.locale=T,C.isDayjs=Y,C.unix=function(k){return C(1e3*k)},C.en=H[z],C.Ls=H,C.p={},C}))})(Ke)),Ke.exports}var Ws=Gs();const Vt=Qs(Ws);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 Xt(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 Ot(e){const{hours:t,minutes:s,seconds:r}=Xt(e);return Vt().hour(t).minute(s).second(r).millisecond(0)}function Ce(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Ks(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function Pt(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 Te(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?.Message||`HTTP ${r.status}`;throw new Error(o)}return a}const ne=(...e)=>e.find(t=>t!=null);function Ys(e){return{id:String(ne(e?.AlertId,e?.alertId)??""),priority:ne(e?.Priority,e?.priority,"Low"),timestamp:ne(e?.Timestamp,e?.timestamp,""),statusType:ne(e?.Status,e?.statusType,""),description:ne(e?.Description,e?.description,""),eventName:ne(e?.EventName,e?.eventName),ruleName:ne(e?.RuleName,e?.ruleName),spaceName:ne(e?.SpaceName,e?.spaceName),assignTeam:ne(e?.AssignTeam,e?.assignTeam),cameraName:ne(e?.CameraName,e?.cameraName),type:ne(e?.Type,e?.type),mediaDetails:ne(e?.MediaDetails,e?.mediaDetails),additionalMedia:ne(e?.AdditionalMedia,e?.additionalMedia),timeElapsed:ne(e?.TimeElapsed,e?.timeElapsed),timeRemaining:ne(e?.TimeRemaining,e?.timeRemaining),anomalyName:ne(e?.AnomalyName,e?.anomalyName),alertDetails:ne(e?.AlertDetails,e?.alertDetails),statusHistory:ne(e?.StatusHistory,e?.statusHistory),isEmailSent:ne(e?.IsEmailSent,e?.isEmailSent),isSMSSent:ne(e?.IsSMSSent,e?.isSMSSent),timeZoneUniqueId:ne(e?.TimeZoneUniqueId,e?.timeZoneUniqueId)}}function zs(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts?customerId=99e5c8b5-b9d4-4d35-8885-7f121c532664"),r=await Te(s,{method:"GET",headers:t});return Array.isArray(r?.Items)?(r?.Items).map(Ys):[]},async getAlertStatusList(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts/StatusList"),r=await Te(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertsReport(s){const r=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetAlertsReport"),i=Pt(r,s),a=await Te(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=Ce(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 Te(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getAdminSettings(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetAdminSettings"),r=await Te(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=Ce(e.baseUrl,"/api/detectionpolicy/alerts/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??""};return Te(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetPreferenceSettings"),r=await Te(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=Ce(e.baseUrl,"/api/detectionpolicy/alerts/SetPreferenceSettings"),i=h=>{const{hours:d,minutes:A,seconds:m}=Xt(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 Te(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=Ce(e.baseUrl,"/api/detectionpolicy/alerts/GetNotifications"),i=Pt(r,{alertId:s}),a=await Te(i,{method:"GET",headers:t});return Array.isArray(a)?a:a&&typeof a=="object"&&Array.isArray(a.data)?a.data:[]}}}function Zs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Re(e,t){const s={...t.headers,...Zs()},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 Vs(e){const t={"Content-Type":"application/json",...e.headers||{}},s=new URL("/api/detectionpolicy/rules",e.baseUrl).toString();return{async getRules(){const r=await Re(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async setEscalationSettings(r){return Re(s,{method:"POST",headers:t,body:JSON.stringify(r??{})})},async getLookups(){const r=E=>new URL(E,e.baseUrl).toString(),i=[Re(r("/api/detectionpolicy/lookups/actiontypes"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/anomalies"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/thirdparty"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/severity"),{method:"GET",headers:t}),Re(r("/api/detectionpolicy/lookups/scheduletypes"),{method:"GET",headers:t})],[a,o,l,f,h]=await Promise.allSettled(i),d=E=>E.status==="fulfilled"&&Array.isArray(E.value)?E.value:[],A=d(a),m=d(o),I=d(l),w=d(f),p=d(h),S=A.map(E=>({actionTypeId:Number(E?.ActionTypeId),name:E?.DisplayName??E?.Name??""})),$=m.map(E=>({recordId:E?.AnomalyId,anomalyName:E?.DisplayName??E?.Name??""})),F=I.map(E=>({thirdPartyId:Number(E?.ThirdPartyId),thirdPartyName:E?.ThirdPartyName??E?.Name??""})),L={actionTypes:S,anomalies:$,thirdParties:F};return w.length&&(L.severities=w),p.length&&(L.scheduleTypes=p),L},async updateRule(r,i){const a=`${s}/${r}`;return Re(a,{method:"PUT",headers:t,body:JSON.stringify(i??{})})}}}const es=u.createContext(null);function ts({tenant:e="snl",override:t,children:s}){const r=u.useMemo(()=>{const a=t?.alertsBaseUrl?.trim()||kt[e]?.alerts||"";let o=t?.rulesBaseUrl?.trim()||kt[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"?zs({baseUrl:r.alertsBaseUrl,headers:r.headers}):Bs({baseUrl:r.alertsBaseUrl,headers:r.headers}),o=r.tenant==="schools"?Vs({baseUrl:r.rulesBaseUrl,headers:r.headers}):_s({baseUrl:r.alertsBaseUrl,headers:r.headers});return{config:r,alerts:a,rules:o}},[r]);return n.jsx(es.Provider,{value:i,children:s})}function ve(){const e=u.useContext(es);if(!e)throw new Error("useApi must be used inside ApiProvider");return e}const Js={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Xs={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},ft=6,mt=7;function Dt(e,t,s){const r=e===ft,i=e===mt,a=t.isEmailSent??!1,o=t.isSMSSent??!1,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 er(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 tr(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 rt(e,t){return`${e}-${t?"email":"sms"}`}function He(e){return e===ft||e===mt}function Ve({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 sr=[{label:"All levels",value:"All"},{label:"Critical",value:"Critical"},{label:"High",value:"High"},{label:"Medium",value:"Medium"},{label:"Low",value:"Low"}];function rr({value:e,onChange:t,options:s}){return n.jsx(Ve,{className:"w-[140px]",value:e,onChange:t,options:s||sr})}const nr=[{label:"All Types",value:"All"},{label:"Weapon Detection",value:"Weapon"},{label:"Unauthorized Access",value:"Unauthorized"},{label:"Aggressive Behavior",value:"Aggressive"}];function ir({value:e,onChange:t,options:s}){return n.jsx(Ve,{className:"w-[220px]",dropdownWidth:280,value:e,onChange:t,options:s||nr})}function ar({value:e,onChange:t,options:s}){return n.jsx(Ve,{className:"w-[100px]",value:e,onChange:t,options:s||[]})}const or=[{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 lr({value:e,onChange:t,options:s}){return n.jsx(Ve,{className:"w-[130px]",value:e,onChange:t,options:s||or})}function ss({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 pt({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,$]=u.useState("All"),[F,L]=u.useState(""),[E,z]=u.useState([{label:"All",value:"All"}]),[H,W]=u.useState(new Set),{rules:Y,alerts:T}=ve(),C={6:{title:"Email",kind:"icon",icon:n.jsx(Me.MailOutlined,{})},7:{title:"SMS",kind:"icon",icon:n.jsx(Me.MessageOutlined,{})}},R=u.useMemo(()=>er(e),[e]),K=u.useMemo(()=>tr(e),[e]);u.useEffect(()=>{let b=!0;return(async()=>{try{const v=await Y.getLookups(),D=(Array.isArray(v.thirdParties)?v.thirdParties:[]).map(U=>({label:U.thirdPartyName,value:String(U.thirdPartyId)}));b&&z([{label:"All",value:"All"},...D])}catch(v){console.error("Error loading third party options",v)}})(),()=>{b=!1}},[Y]);const X=u.useMemo(()=>(e||[]).some(b=>Rt(b).length>0),[e]),k=u.useMemo(()=>(e||[]).filter(b=>{const v=d==="All"||b.priority===d,M=`${b.id} ${b.description} ${b.statusType}`.toLowerCase(),D=!F||M.includes(F.toLowerCase()),U=m==="All"||(b.anomalyName||"").toLowerCase()===m.toLowerCase(),B=w==="All"||(b.spaceName||"").toLowerCase()===w.toLowerCase(),q=!X||S==="All"||Rt(b).includes(Number(S)),se=!h||!["completed","false positive"].includes(String(b.statusType||"").toLowerCase());return v&&D&&U&&B&&q&&se}),[e,d,F,m,w,S,X,h]),x=R,y=a&&a.length?a:K,j=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:b=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${Xs[b]}`,backgroundColor:Js[b]},children:b})},{title:"Tracker",key:"tracker",width:140,render:(b,v)=>n.jsx("a",{onClick:M=>{M.preventDefault(),l?.(v,{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:(b,v)=>{if(o)return n.jsx(n.Fragment,{children:o(v)});const M=async(xe,ye)=>{const De=rt(v.id,xe);W(ce=>new Set(ce).add(De));try{const ce=await T.sendSMSorEmailNotifications?.(v.id,xe,ye);ce?.responseStatus?(pe.toast.success(ce.data||(xe?"Email sent successfully":"SMS sent successfully")),f?.()):pe.toast.error(ce?.data||ce?.errorMessage||"Failed to send notification")}catch(ce){pe.toast.error(ce?.message||"Failed to send notification")}finally{W(ce=>{const we=new Set(ce);return we.delete(De),we})}},D=ft,U=mt,B=C[D],q=C[U],se=Dt(D,v,B?.title),ie=Dt(U,v,q?.title),ae=rt(v.id,!0),he=rt(v.id,!1),ee=He(D)&&H.has(ae),oe=He(U)&&H.has(he);return n.jsxs(c.Space,{size:"middle",children:[n.jsx(c.Tooltip,{title:se.tooltipTitle,children:n.jsx(c.Button,{size:"small",disabled:se.isDisabled,loading:ee,onClick:He(D)?()=>M(!0,!1):void 0,icon:!ee&&B?.icon,className:"flex flex-col items-center justify-center gap-1",style:{height:"fit-content"},children:se.buttonText})},String(D)),n.jsx(c.Tooltip,{title:ie.tooltipTitle,children:n.jsx(c.Button,{size:"small",disabled:ie.isDisabled,loading:oe,onClick:He(U)?()=>M(!1,!0):void 0,icon:!oe&&q?.icon,className:"flex flex-col items-center justify-center gap-1",style:{height:"fit-content"},children:ie.buttonText})},String(U))]})}},{title:"Alert Timestamp",dataIndex:"timestamp",key:"timestamp",width:220,render:(b,v)=>{const M=v?.timeElapsed,D=v?.timeRemaining,U=M?It(M):0,B=D?It(D):0,q=Math.round(U/(U+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:M??"-"})]}),n.jsx(c.Progress,{percent:q,showInfo:!1,size:"small",strokeColor:Ds(v.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:D??"-"})]})]})}},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(b,v)=>n.jsxs("div",{children:[n.jsx("a",{onClick:M=>{M.preventDefault(),l?.(v,{sourceTab:"active"})},className:"inline-block mb-1 text-blue-600",children:v.alertNumber}),n.jsx("div",{className:"text-black/65",children:b})]})}],g=r&&r.length?r:j;return n.jsx("div",{children:n.jsx(ss,{rowKey:"id",data:k,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(rr,{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(ir,{value:m,onChange:I,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(ar,{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(lr,{value:S,onChange:$,options:E})]})}),n.jsx(c.Col,{flex:"auto"}),n.jsx(c.Col,{flex:"none",children:n.jsx(c.Input.Search,{allowClear:!0,placeholder:"Search",onSearch:L,onChange:b=>L(b.target.value),className:"w-[260px] ",enterButton:!0})})]})})})}var Ue=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(){}},cr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ur=class{#e=cr;#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 ur;function dr(e){setTimeout(e,0)}var Oe=typeof window>"u"||"Deno"in globalThis;function me(){}function hr(e,t){return typeof e=="function"?e(t):e}function it(e){return typeof e=="number"&&e>=0&&e!==1/0}function rs(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ke(e,t){return typeof e=="function"?e(t):e}function Ae(e,t){return typeof e=="function"?e(t):e}function Ft(e,t){const{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:l}=e;if(o){if(r){if(t.queryHash!==yt(o,t.options))return!1}else if(!Be(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 Ut(e,t){const{exact:s,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(s){if(Pe(t.options.mutationKey)!==Pe(a))return!1}else if(!Be(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function yt(e,t){return(t?.queryKeyHashFn||Pe)(e)}function Pe(e){return JSON.stringify(e,(t,s)=>ot(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}function Be(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>Be(e[s],t[s])):!1}var fr=Object.prototype.hasOwnProperty;function at(e,t,s=0){if(e===t)return e;if(s>500)return t;const r=Lt(e)&&Lt(t);if(!r&&!(ot(e)&&ot(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:fr.call(e,A))&&h++;continue}if(m===null||I===null||typeof m!="object"||typeof I!="object"){f[A]=I;continue}const w=at(m,I,s+1);f[A]=w,w===m&&h++}return a===l&&h===a?e:f}function Ye(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 Lt(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ot(e){if(!$t(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!$t(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function $t(e){return Object.prototype.toString.call(e)==="[object Object]"}function mr(e){return new Promise(t=>{Ee.setTimeout(t,e)})}function lt(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 at(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 at(e,t)}return t}function pr(e,t,s=0){const r=[...e,t];return s&&r.length>s?r.slice(1):r}function yr(e,t,s=0){const r=[t,...e];return s&&r.length>s?r.slice(0,-1):r}var ze=Symbol();function ns(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===ze&&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===ze?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function gt(e,t){return typeof e=="function"?e(...t):!!e}function gr(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 vr=class extends Ue{#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"}},vt=new vr;function ct(){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 xr=dr;function br(){let e=[],t=0,s=l=>{l()},r=l=>{l()},i=xr;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 le=br(),Sr=class extends Ue{#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}},Ze=new Sr;function Ar(e){return Math.min(1e3*2**e,3e4)}function is(e){return(e??"online")==="online"?Ze.isOnline():!0}var ut=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function as(e){let t=!1,s=0,r;const i=ct(),a=()=>i.status!=="pending",o=p=>{if(!a()){const S=new ut(p);m(S),e.onCancel?.(S)}},l=()=>{t=!0},f=()=>{t=!1},h=()=>vt.isFocused()&&(e.networkMode==="always"||Ze.isOnline())&&e.canRun(),d=()=>is(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($){p=Promise.reject($)}Promise.resolve(p).then(A).catch($=>{if(a())return;const F=e.retry??(Oe?0:3),L=e.retryDelay??Ar,E=typeof L=="function"?L(s,$):L,z=F===!0||typeof F=="number"&&s<F||typeof F=="function"&&F(s,$);if(t||!z){m($);return}s++,e.onFail?.(s,$),mr(E).then(()=>h()?void 0:I()).then(()=>{t?m($):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 os=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),it(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)}},wr=class extends os{#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=qt(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=qt(this.options);t.data!==void 0&&(this.setState(Bt(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const s=lt(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(me).catch(me):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>Ae(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ze||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>ke(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:!rs(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=ns(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=as({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof ut&&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 ut){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,...ls(s.data,this.options),fetchMeta:e.meta??null};case"success":const r={...s,...Bt(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),le.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function ls(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:is(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Bt(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function qt(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 jr=class extends Ue{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=ct(),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),_t(this.#t,this.options)?this.#d():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return dt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return dt(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 Ae(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&&!Ye(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&Qt(this.#t,s,this.options,t)&&this.#d(),this.updateResult(),r&&(this.#t!==s||Ae(this.options.enabled,this.#t)!==Ae(t.enabled,this.#t)||ke(this.options.staleTime,this.#t)!==ke(t.staleTime,this.#t))&&this.#y();const i=this.#g();r&&(this.#t!==s||Ae(this.options.enabled,this.#t)!==Ae(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 Cr(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(me)),t}#y(){this.#b();const e=ke(this.options.staleTime,this.#t);if(Oe||this.#n.isStale||!it(e))return;const s=rs(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||Ae(this.options.enabled,this.#t)===!1||!it(this.#l)||this.#l===0)&&(this.#u=Ee.setInterval(()=>{(this.options.refetchIntervalInBackground||vt.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 Y=this.hasListeners(),T=!Y&&_t(e,t),C=Y&&Qt(e,s,t,r);(T||C)&&(d={...d,...ls(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 Y;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(Y=i.data,S=!0):Y=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,Y!==void 0&&(p="success",m=lt(i?.data,Y,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=lt(i?.data,m,t),this.#h=m,this.#i=null}catch(Y){this.#i=Y}this.#i&&(I=this.#i,m=this.#h,w=Date.now(),p="error");const $=d.fetchStatus==="fetching",F=p==="pending",L=p==="error",E=F&&$,z=m!==void 0,W={status:p,fetchStatus:d.fetchStatus,isPending:F,isSuccess:p==="success",isError:L,isInitialLoading:E,isLoading:E,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:$,isRefetching:$&&!F,isLoadingError:L&&!z,isPaused:d.fetchStatus==="paused",isPlaceholderData:A,isRefetchError:L&&z,isStale:xt(e,t),refetch:this.refetch,promise:this.#o,isEnabled:Ae(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const Y=W.data!==void 0,T=W.status==="error"&&!Y,C=X=>{T?X.reject(W.error):Y&&X.resolve(W.data)},R=()=>{const X=this.#o=W.promise=ct();C(X)},K=this.#o;switch(K.status){case"pending":e.queryHash===s.queryHash&&C(K);break;case"fulfilled":(T||W.data!==K.value)&&R();break;case"rejected":(!T||W.error!==K.reason)&&R();break}}return W}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),Ye(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){le.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Nr(e,t){return Ae(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function _t(e,t){return Nr(e,t)||e.state.data!==void 0&&dt(e,t,t.refetchOnMount)}function dt(e,t,s){if(Ae(t.enabled,e)!==!1&&ke(t.staleTime,e)!=="static"){const r=typeof s=="function"?s(e):s;return r==="always"||r!==!1&&xt(e,t)}return!1}function Qt(e,t,s,r){return(e!==t||Ae(r.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&xt(e,s)}function xt(e,t){return Ae(t.enabled,e)!==!1&&e.isStaleByTime(ke(t.staleTime,e))}function Cr(e,t){return!Ye(e.getCurrentResult(),t)}function Ht(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=>{gr(w,()=>t.signal,()=>d=!0)},m=ns(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 H={client:t.client,queryKey:t.queryKey,pageParam:p,direction:S?"backward":"forward",meta:t.options.meta};return A(H),H})(),L=await m(F),{maxPages:E}=t.options,z=S?yr:pr;return{pages:z(w.pages,L,E),pageParams:z(w.pageParams,p,E)}};if(i&&a.length){const w=i==="backward",p=w?Tr:Gt,S={pages:a,pageParams:o},$=p(r,S);l=await I(S,$,w)}else{const w=e??a.length;do{const p=f===0?o[0]??r.initialPageParam:Gt(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 Gt(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 Tr(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}var Ir=class extends os{#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||cs(),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=as({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),le.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function cs(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Rr=class extends Ue{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 Ir({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=Ge(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=Ge(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=Ge(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=Ge(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){le.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=>Ut(t,s))}findAll(e={}){return this.getAll().filter(t=>Ut(e,t))}notify(e){le.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return le.batch(()=>Promise.all(e.map(t=>t.continue().catch(me))))}};function Ge(e){return e.options.scope?.id}var kr=class extends Ue{#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),Ye(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&Pe(t.mutationKey)!==Pe(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??cs();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){le.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)})})}},Er=class extends Ue{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,s){const r=t.queryKey,i=t.queryHash??yt(r,t);let a=this.get(i);return a||(a=new wr({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(){le.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=>Ft(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Ft(e,s)):t}notify(e){le.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){le.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){le.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Mr=class{#e;#t;#s;#n;#r;#a;#o;#i;constructor(e={}){this.#e=e.queryCache||new Er,this.#t=e.mutationCache||new Rr,this.#s=e.defaultOptions||{},this.#n=new Map,this.#r=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=vt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=Ze.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(ke(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=hr(t,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return le.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;le.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#e;return le.batch(()=>(s.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},r=le.batch(()=>this.#e.findAll(e).map(i=>i.cancel(s)));return Promise.all(r).then(me).catch(me)}invalidateQueries(e,t={}){return le.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=le.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(me)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(me)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#e.build(this,t);return s.isStaleByTime(ke(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(me).catch(me)}fetchInfiniteQuery(e){return e.behavior=Ht(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(me).catch(me)}ensureInfiniteQueryData(e){return e.behavior=Ht(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ze.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(Pe(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(r=>{Be(e,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(e,t){this.#r.set(Pe(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],s={};return t.forEach(r=>{Be(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=yt(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===ze&&(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()}},us=de.createContext(void 0),bt=e=>{const t=de.useContext(us);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Or=({client:e,children:t})=>(de.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),n.jsx(us.Provider,{value:e,children:t})),ds=de.createContext(!1),Pr=()=>de.useContext(ds);ds.Provider;function Dr(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Fr=de.createContext(Dr()),Ur=()=>de.useContext(Fr),Lr=(e,t,s)=>{const r=s?.state.error&&typeof e.throwOnError=="function"?gt(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},$r=e=>{de.useEffect(()=>{e.clearReset()},[e])},Br=({result:e,errorResetBoundary:t,throwOnError:s,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||gt(s,[e.error,r])),qr=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))}},_r=(e,t)=>e.isLoading&&e.isFetching&&!t,Qr=(e,t)=>e?.suspense&&t.isPending,Wt=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function Hr(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=Pr(),i=Ur(),a=bt(),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",qr(o),Lr(o,i,l),$r(i);const f=!a.getQueryCache().get(o.queryHash),[h]=de.useState(()=>new t(a,o)),d=h.getOptimisticResult(o),A=!r&&e.subscribed!==!1;if(de.useSyncExternalStore(de.useCallback(m=>{const I=A?h.subscribe(le.batchCalls(m)):me;return h.updateResult(),I},[h,A]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),de.useEffect(()=>{h.setOptions(o)},[o,h]),Qr(o,d))throw Wt(o,h,i);if(Br({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&&_r(d,r)&&(f?Wt(o,h,i):l?.promise)?.catch(me).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?d:h.trackResult(d)}function Je(e,t){return Hr(e,jr)}function Gr(e,t){const s=bt(),[r]=de.useState(()=>new kr(s,e));de.useEffect(()=>{r.setOptions(e)},[r,e]);const i=de.useSyncExternalStore(de.useCallback(o=>r.subscribe(le.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=de.useCallback((o,l)=>{r.mutate(o,l).catch(me)},[r]);if(i.error&>(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function St(){const{alerts:e}=ve(),t=bt();return Gr({mutationFn:s=>e.updateAlertStatus(s),onSuccess:()=>{t.invalidateQueries({queryKey:["alerts","list"]}),t.invalidateQueries({queryKey:["alerts","report"]})}})}function Wr(e,t){return e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZone:t})}function Kr(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 Yr(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 ht(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 zr={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},Zr={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"};function hs({alerts:e,loading:t=!1,pageSize:s=10,severityOptions:r,anomalyOptions:i,spaceOptions:a,onAlertIdClick:o}){const l=St(),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.";pe.toast.success(w)}else{const w=I?.errorMessage||"Failed to reopen alert";pe.toast.error(w)}}catch{pe.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 ${zr[m]}`,backgroundColor:Zr[String(m)]},children:m})},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:200,render:m=>Yr(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(Me.MoreOutlined,{})})})}],A=(e||[]).filter(m=>f.includes((m.statusType||"").toLowerCase()));return n.jsx(pt,{data:A,loading:t,pageSize:s,columns:d,severityOptions:r,anomalyOptions:i,spaceOptions:a,renderActions:void 0,onAlertIdClick:o,excludeCompleted:!1})}function Vr({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),$=h+p*Math.cos(S),F=h+p*Math.sin(S),L=h+w*Math.cos(S),E=h+w*Math.sin(S);return n.jsx("svg",{className:"absolute inset-0",width:e,height:e,children:n.jsx("line",{x1:$,y1:F,x2:L,y2:E,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 fs({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(()=>Wr(i,t),[i,t]),{abbr:l,offset:f}=u.useMemo(()=>Kr(i,t),[i,t]);return n.jsxs("div",{className:`flex items-center gap-3 ${r||""}`,children:[n.jsx(Vr,{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 Jr=[{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}],Xr=[{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"}],en=[{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"}],Fe={severities:Jr,rules:Xr,userRoles:en},{Text:tn}=c.Typography;function sn({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(tn,{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:Ie}=c.Typography;function rn(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:$,actions:F,setActions:L,thirdPartyIds:E,setThirdPartyIds:z,humanLoop:H,setHumanLoop:W,isAutoExpire:Y,setAutoExpire:T,onClear:C,onSave:R,saving:K,onActionTypesLoaded:X}=e,{rules:k}=ve(),[x,y]=u.useState([]),[j,g]=u.useState([]),[b,v]=u.useState(!1);u.useEffect(()=>{let B=!1;return(async()=>{try{v(!0);const q=await k.getLookups();if(B||!q||!Array.isArray(q.actionTypes))return;const se=q.actionTypes.map(ae=>({label:ae.name,value:String(ae.actionTypeId)}));y(se),X&&X(q.actionTypes);const ie=Array.isArray(q.thirdParties)?q.thirdParties.map(ae=>({label:ae.thirdPartyName,value:ae.thirdPartyId})):[];g(ie)}catch(q){console.error("Error loading lookups",q)}finally{B||v(!1)}})(),()=>{B=!0}},[]);const M=B=>n.jsxs(c.Tag,{children:[n.jsx(Me.PlusOutlined,{})," ",B.length," more"]}),D=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(E)&&E.length>0||!!H||!!Y,U=!!t&&D&&!K;return n.jsxs(c.Spin,{spinning:!!K||b,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(Ie,{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(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Level 1 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ie,{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(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Level 2 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ie,{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(Ie,{className:"text-gray-700 font-medium block mb-1",children:"Level 3 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(Ie,{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:$,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ie,{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:L,options:x,maxTagCount:1,maxTagPlaceholder:M})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsx(Ie,{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:E,onChange:z,options:j})]})})]}),n.jsxs(c.Row,{gutter:[16,16],align:"bottom",className:"mt-4 items-center",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:7,children:n.jsxs("div",{className:"flex items-center h-full gap-8",children:[n.jsx(c.Checkbox,{checked:H,onChange:B=>W(B.target.checked),className:"w-full",children:"Human-In-The-Loop"}),n.jsx(c.Checkbox,{checked:Y,onChange:B=>T(B.target.checked),className:"w-full",children:"Auto-expire in 5 minutes"})]})}),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:C,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:R,loading:!!K,disabled:!U,children:"Save"})]})})]})]})}function nn({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?.length?l.actions.join(", "):"-"},{title:"Notify",key:"notify",render:(o,l)=>l.notify?.length?l.notify.join(", "):"-"},{title:"Human-In-The-Loop",key:"humanLoop",render:(o,l)=>l.humanLoop?"Yes":"No"},{title:"Auto Expire",key:"isAutoExpire",render:(o,l)=>l.isAutoExpire?"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:an}=c.Typography;function ms({userRoles:e,rules:t,rawRules:s}){const{rules:r}=ve(),[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 $=o.find(L=>L?.ruleId===S.key||L?.ruleName===S.key||L?.RuleId===S.key||L?.ruleName===S.ruleName||L?.Name===S.ruleName),F=Array.isArray($?.userRoleIds)?$.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){pe.toast.info("No changes to save");return}a(!0);const p=Object.entries(f).map(async([S,$])=>{const F=o.find(W=>W?.ruleId===S||W?.ruleName===S||W?.RuleId===S),L=typeof F?.recordId=="number"?F.recordId:void 0;if(!F||typeof L!="number")throw new Error(`Unable to find recordId for rule ${S}`);const E=Array.isArray($)?$:[],z=E.map(W=>{const Y=e.find(T=>T.userRoleId===W);return{id:W,name:Y?.userRoleName??String(W)}}),H={...F,ruleId:S,userRoleIds:E,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(L,H)});await Promise.all(p),pe.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(an,{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:$=>h(F=>({...F,[S.key]:$})),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:Kt}=c.Typography;function ps({severities:e,rules:t,userRoles:s,rawRules:r,onSave:i}){const{rules:a,alerts:o}=ve(),[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),[$,F]=u.useState(!1),[L,E]=u.useState(null),[z,H]=u.useState("rules"),[W,Y]=u.useState(),[T,C]=u.useState(),[R,K]=u.useState(),[X,k]=u.useState(),[x,y]=u.useState(),[j,g]=u.useState(),[b,v]=u.useState(),[M,D]=u.useState(),[U,B]=u.useState([]),[q,se]=u.useState([]),[ie,ae]=u.useState(!1),[he,ee]=u.useState(!1),[oe,xe]=u.useState({}),[ye,De]=u.useState({}),[ce,we]=u.useState(s||[]),[Le,N]=u.useState([]),[G,re]=u.useState(!1),[je,V]=u.useState(!1),[ue,$e]=u.useState(r||[]);u.useEffect(()=>{r&&r.length&&$e(r)},[r]),u.useEffect(()=>{if(!ue||!ue.length)return;const O=Object.keys(oe).length>0||Object.keys(ye).length>0;if(Le.length&&!O)return;const J=ue.map((_,P)=>{const Z=t.find(fe=>fe.RuleId===(_.ruleId||_.ruleName))?.Name||_.ruleName||_.Name||"-",Q=_.escalationSettings||{},te=typeof Q.level1UserRoleId=="number"&&Q.level1UserRoleId>0?[Q.level1UserRoleId]:[],Ne=typeof Q.level2UserRoleId=="number"&&Q.level2UserRoleId>0?[Q.level2UserRoleId]:[],et=typeof Q.level3UserRoleId=="number"&&Q.level3UserRoleId>0?[Q.level3UserRoleId]:[],jt=(Array.isArray(Q.escalationSettingsActionTypeIds)?Q.escalationSettingsActionTypeIds:[]).map(fe=>oe[fe]||String(fe)),Ct=(Array.isArray(Q.thirdPartyId)?Q.thirdPartyId:[]).map(fe=>ye[fe]||String(fe)),tt=typeof Q.humanLoop=="boolean"?Q.humanLoop:null,st=typeof Q.isAutoExpire=="boolean"?Q.isAutoExpire:null;return{id:String(_.ruleId||_.ruleName||P),ruleOrSeverityLabel:Z,l1:{minutes:Q.level1PostAssistTime??void 0,roles:te},l2:{minutes:Q.level2PostAssistTime??void 0,roles:Ne},l3:{minutes:Q.level3PostAssistTime??void 0,roles:et},actions:jt,notify:Ct,humanLoop:tt,isAutoExpire:st}});N(J)},[ue,t,oe,ye]);const ge=u.useMemo(()=>e.map(O=>({label:O.DisplayName,value:O.SeverityId})),[e]),Xe=u.useMemo(()=>t.map(O=>({label:O.Name,value:O.RuleId})),[t]),ws=u.useMemo(()=>ce.map(O=>({label:O.userRoleName,value:O.userRoleId})),[ce]),js=u.useMemo(()=>[1,3,5,10,15,20,30,45,60].map(O=>({label:`${O}`,value:O})),[]);u.useEffect(()=>{let O=!1;async function J(){try{F(!0),E(null);const _=await o.getAdminSettings();if(!O&&_){const P=Jt(_.sortBy);f(P),m(P),w(!1)}}catch(_){if(!O){const P=_ instanceof Error?_.message:"Failed to load admin settings";E(P)}}finally{O||F(!1)}}return J(),()=>{O=!0}},[]),u.useEffect(()=>{if(!T)return;const O=Z=>{const Q=Number(Z);return!isNaN(Q)&&Q>0?Q:void 0},J=Z=>{const Q=Number(Z);return!isNaN(Q)&&Q>0?Q:void 0},P=(ue||[]).find(Z=>Z?.ruleId===T||Z?.ruleName===T||Z?.RuleId===T)?.escalationSettings;if(P&&typeof P=="object"){K(J(P.level1PostAssistTime)),k(O(P.level1UserRoleId)),y(J(P.level2PostAssistTime)),g(O(P.level2UserRoleId)),v(J(P.level3PostAssistTime)),D(O(P.level3UserRoleId));const Z=Array.isArray(P.escalationSettingsActionTypeIds)?P.escalationSettingsActionTypeIds:[];B(Z.map(Q=>String(Q))),se(Array.isArray(P.thirdPartyId)?P.thirdPartyId:[]),ae(!!P.humanLoop),ee(!!P.isAutoExpire)}},[z,T,ue]);const Ns=async()=>{try{V(!0);const O=await a.getRules(),J=Array.isArray(O)?O:Array.isArray(O?.data)?O.data:[];$e(J);const _=J.map((P,Z)=>{const Q=t.find(fe=>fe.RuleId===(P.ruleId||P.ruleName))?.Name||P.ruleName||P.Name||"-",te=P.escalationSettings||{},Ne=typeof te.level1UserRoleId=="number"&&te.level1UserRoleId>0?[te.level1UserRoleId]:[],et=typeof te.level2UserRoleId=="number"&&te.level2UserRoleId>0?[te.level2UserRoleId]:[],wt=typeof te.level3UserRoleId=="number"&&te.level3UserRoleId>0?[te.level3UserRoleId]:[],Nt=(Array.isArray(te.escalationSettingsActionTypeIds)?te.escalationSettingsActionTypeIds:[]).map(fe=>oe[fe]||String(fe)),tt=(Array.isArray(te.thirdPartyId)?te.thirdPartyId:[]).map(fe=>ye[fe]||String(fe)),st=typeof te.humanLoop=="boolean"?te.humanLoop:null;return{id:String(P.ruleId||P.ruleName||Z),ruleOrSeverityLabel:Q,l1:{minutes:te.level1PostAssistTime??void 0,roles:Ne},l2:{minutes:te.level2PostAssistTime??void 0,roles:et},l3:{minutes:te.level3PostAssistTime??void 0,roles:wt},actions:Nt,notify:tt,humanLoop:st}});N(_)}catch(O){console.error("Failed to refetch entries",O)}finally{V(!1)}};u.useEffect(()=>{let O=!1;return(async()=>{try{const J=await a.getLookups();if(O||!J)return;const _={};if(Array.isArray(J.thirdParties))for(const Z of J.thirdParties)typeof Z.thirdPartyId=="number"&&(_[Z.thirdPartyId]=Z.thirdPartyName);De(_);const P=Array.isArray(J.userRoles)?J.userRoles.map(Z=>({userRoleId:Z.userRoleId??Z.id,userRoleName:Z.userRoleName??Z.name})):[];O||we(P.length?P:s||[])}catch(J){console.error("Error loading lookups",J)}})(),()=>{O=!0}},[]);const Cs=async()=>{S(!0);try{const O=await o.setAdminSettings({sortBy:l,groupBy:"string"});O?.responseStatus&&O?.data&&pe.toast.success(O.data),m(l),w(!1)}catch(O){console.error("Error saving admin settings",O)}finally{S(!1)}},Ts=()=>{f(A),w(!1)},Is=async()=>{re(!0),i?.({ruleId:T,levels:[{minutes:R,role:X},{minutes:x,role:j},{minutes:b,role:M}],actions:U,thirdPartyIds:q,humanLoop:ie,isAutoExpire:he});try{if(T){const _=Array.isArray(U)?U.map(Ne=>Number(Ne)):[],P=(ue||[]).find(Ne=>Ne?.ruleId===T||Ne?.ruleName===T||Ne?.RuleId===T),Z=typeof P?.recordId=="number"?P.recordId:void 0;if(!P||typeof Z!="number"){pe.toast.error("Unable to find rule recordId for update");return}const Q={...P,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:X??0,level1PostAssistTime:R??0,level2UserRoleId:j??0,level2PostAssistTime:x??0,level3UserRoleId:M??0,level3PostAssistTime:b??0,escalationSettingsActionTypeIds:_,thirdPartyId:Array.isArray(q)?q:[],humanLoop:ie,isAutoExpire:he}},te=await a.updateRule(Z,Q);if(te?.responseStatus||te?.ok||te){pe.toast.success("Escalation settings saved"),await Ns(),C(void 0),K(void 0),k(void 0),y(void 0),g(void 0),v(void 0),D(void 0),B([]),se([]),ae(!1),ee(!1);return}}}catch(_){console.error("Error saving escalation settings",_)}finally{re(!1)}const J=t.find(_=>_.RuleId===T)?.Name||"-";N(_=>[..._,{id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ruleOrSeverityLabel:J,l1:{minutes:R,roles:X?[X]:[]},l2:{minutes:x,roles:j?[j]:[]},l3:{minutes:b,roles:M?[M]:[]},actions:(Array.isArray(U)?U:[]).map(P=>{const Z=Number(P);return oe[Z]||String(P)}),notify:(Array.isArray(q)?q:[]).map(P=>ye[P]||String(P)),humanLoop:!!ie,isAutoExpire:!!he}])},Rs=()=>{f("By Severity"),d("By severity"),H("rules"),Y(void 0),C(void 0),K(void 0),k(void 0),y(void 0),g(void 0),v(void 0),D(void 0),B([]),se([]),ae(!1),ee(!1)};return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"mb-6",children:[n.jsx(Kt,{level:4,className:"!mb-2",children:"Admin Settings"}),n.jsxs(c.Spin,{spinning:$,children:[L?n.jsxs("div",{className:"text-sm text-red-600 mb-2",children:["Failed to load settings: ",L]}):null,n.jsx(sn,{sortBy:l,groupBy:h,onChange:O=>{O.sortBy&&(f(O.sortBy),w(!0)),O.groupBy&&(d(O.groupBy),w(!0))},showActions:I,onSave:Cs,onClear:Ts,saving:p})]})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsxs("div",{children:[n.jsx(Kt,{level:4,className:"!mb-4",children:"Escalation Settings"}),n.jsx(rn,{escBasis:z,setEscBasis:H,selectedSeverity:W,setSelectedSeverity:Y,selectedRule:T,setSelectedRule:C,severityOptions:ge,ruleOptions:Xe,minsOptions:js,roleOptions:ws,l1mins:R,setL1mins:K,l1role:X,setL1role:k,l2mins:x,setL2mins:y,l2role:j,setL2role:g,l3mins:b,setL3mins:v,l3role:M,setL3role:D,actions:U,setActions:B,thirdPartyIds:q,setThirdPartyIds:se,humanLoop:ie,setHumanLoop:ae,onClear:Rs,onSave:Is,saving:G,onActionTypesLoaded:O=>{const J={};for(const _ of O)typeof _.actionTypeId=="number"&&(J[_.actionTypeId]=_.name);xe(J)},isAutoExpire:he,setAutoExpire:ee})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(nn,{entries:Le,userRoles:ce,loading:je,onEdit:O=>{H("rules");const J=Le.find(P=>P.id===O),_=t.find(P=>P.RuleId===O)||(J?t.find(P=>P.Name===J.ruleOrSeverityLabel):void 0);C(_?_.RuleId:O)}}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(ms,{userRoles:ce,rules:t,rawRules:r}),n.jsx(c.Divider,{})]})}const{Title:Yt,Text:We}=c.Typography;function ys({severities:e,rules:t,onSave:s,onCancel:r}){const{rules:i,alerts:a}=ve(),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}),[$,F]=u.useState([]),[L,E]=u.useState(!0),[z,H]=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(Ot(C.doNotDisturbStart)),w(Ot(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{E(!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||E(!1)}})(),()=>{T=!0}},[]);const W=T=>{d(C=>{const R=new Set(C);return R.has(T)?R.delete(T):R.add(T),R})},Y=async()=>{s?.({sortBy:l,subscribedRuleIds:Array.from(h),dnd:{from:A,to:I},channels:p});try{H(!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(X=>Number(X)).filter(X=>Number.isFinite(X)),K=await a.setPreferenceSettings({anomalyIds:R,doNotDisturbStart:T,doNotDisturbEnd:C,inApp:!!p.inApp,sms:!!p.sms,email:!!p.email,sortBy:l});K?.responseStatus&&pe.toast.success(K?.data||"Preferences updated successfully.")}catch(T){console.error("Error in saving my preferences: ",T)}finally{H(!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(We,{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(Yt,{level:5,className:"!mb-2",children:"Anomalies"}),L?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($)?$:[]).map(T=>{const C=String(T.recordId),R=T.anomalyName;return n.jsx(c.Checkbox,{checked:h.has(C),onChange:()=>W(C),children:R},C)})})]}),n.jsxs("div",{className:"mb-4",children:[n.jsx(Yt,{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(We,{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(We,{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(We,{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:z,children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:Y,loading:z,children:"Save"})]})]})}function gs({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(ps,{severities:e,rules:t,userRoles:s,rawRules:r}):n.jsx(ys,{severities:e,rules:t})]})}const on="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=",ln="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 cn(e){const t=(e.status||"").toLowerCase()==="completed"?n.jsx("img",{src:on,alt:"completed",style:{width:20,height:20}}):n.jsx("img",{src:ln,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 un({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(cn)})})]})]})},{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 dn=({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?ht(d.createdDate):d?.timestamp?ht(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(un,{data:h})};const hn=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),fn=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,s,r)=>r?r.toUpperCase():s.toLowerCase()),zt=e=>{const t=fn(e);return t.charAt(0).toUpperCase()+t.slice(1)},vs=(...e)=>e.filter((t,s,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===s).join(" ").trim(),mn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var pn={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 yn=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,...pn,width:t,height:t,stroke:e,strokeWidth:r?Number(s)*24/Number(t):s,className:vs("lucide",i),...!a&&!mn(l)&&{"aria-hidden":"true"},...l},[...o.map(([h,d])=>u.createElement(h,d)),...Array.isArray(a)?a:[a]]));const xs=(e,t)=>{const s=u.forwardRef(({className:r,...i},a)=>u.createElement(yn,{ref:a,iconNode:t,className:vs(`lucide-${hn(zt(e))}`,`lucide-${e}`,r),...i}));return s.displayName=zt(e),s};const gn=[["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"}]],bs=xs("maximize-2",gn);const vn=[["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"}]],xn=xs("minimize-2",vn),bn=({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(xn,{size:20}):n.jsx(bs,{size:20})})]})}):null};function Sn(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 nt(e){const t=(e?.mediaType||e?.type||"").toString().toLowerCase();return t==="video"||t==="mp4"?!0:Sn(e?.mediaUrl||e)}function An(e){const t=e;return t?Array.isArray(t)?t:[t]:[]}const wn={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},jn={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Nn=({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"),[$,F]=u.useState(void 0),L=St(),{alerts:E}=ve(),[z,H]=u.useState(!1),[W,Y]=u.useState(void 0),[T,C]=u.useState(void 0),[R,K]=u.useState({}),X=s?.originalData||{},{eventName:k,alertId:x,timestamp:y,description:j,spaceName:g,assignTeam:b,priority:v,statusType:M,id:D,alertDetails:U,statusHistory:B,mediaDetails:q,alertNumber:se}=X,ie=N=>{const G=String(N||"").toLowerCase();return G==="delivered"||G==="sent"?"Delivered":G==="failed"?"Failed":"Queued"},ae=N=>({name:N?.receipientName||N?.recipientName||"-",role:N?.receipientRoleName||"",phone:N?.receipentPhoneNumber||N?.recipientPhoneNumber||N?.receipientEmail||N?.recipientEmail||"",status:ie(N?.messageStatus),notificationReceipientType:N?.notificationReceipientType||""}),he=(N,G)=>{const re=G.map(ae),je=re.filter(ge=>ge.status==="Delivered").length,V=G.map(ge=>ge?.sentAt).filter(Boolean).sort((ge,Xe)=>new Date(Xe).getTime()-new Date(ge).getTime())[0],ue=G[0]||{},$e=[ue?.severityName,ue?.anomalyName].filter(Boolean).join(" - ")||`${N} Notification`;return{channelLabel:`${N} Notification`,sentAt:V||"",messageTitle:$e,messageBody:"",total:re.length,delivered:je,recipients:re}},ee=N=>{const G=new Map;return(N||[]).forEach(re=>{const je=String(re?.notificationType||"Unknown"),V=G.get(je)||[];V.push(re),G.set(je,V)}),Array.from(G.entries()).map(([re,je])=>he(re,je))},oe=async N=>{try{const G=await E.getAlertNotifications(N),re=ee(G);F(re)}catch{F(void 0)}};u.useEffect(()=>{if(p!=="track"||!D)return;let N=!1;return oe(D).then(()=>{N&&F(void 0)}),()=>{N=!0}},[p,D]),u.useEffect(()=>{e&&S(o)},[e,o]);const ye=l==="archived"||["completed","false positive"].includes(String(M||"").toLowerCase()),De=N=>{const G=String(N?.value||"").toLowerCase(),re=String(N?.statusName||"").toLowerCase();return G.includes("reopen")||re.includes("reopen")},ce=(i||[]).filter(N=>{const G=De(N);return typeof l<"u"?l==="archived"?G:!G:ye?G:!G}).map(N=>({value:N.value,label:N.statusName})),we=u.useMemo(()=>An(q),[q]);u.useEffect(()=>{let N=!1;const G=new AbortController,re=async V=>{if(V){N||K(ue=>({...ue,[V]:!1}));try{const ue=await fetch(V,{method:"HEAD",signal:G.signal});if(ue.ok){N||K(ge=>({...ge,[V]:!0}));return}if(ue.status===404){N||K(ge=>({...ge,[V]:!1}));return}if(!(await fetch(V,{method:"GET",signal:G.signal})).ok)throw new Error("Media not available");N||K(ge=>({...ge,[V]:!0}))}catch{N||K(ue=>({...ue,[V]:!1}))}}};return K({}),we.filter(V=>!nt(V)).map(V=>V?.mediaUrl||V).filter(V=>typeof V=="string"&&V.length>0).forEach(V=>re(V)),()=>{N=!0,G.abort()}},[we]);const Le=async()=>{try{I(!0);const N={alertUniqueId:x,alertId:D,status:f?String(f):void 0,notes:d.trim(),modifiedBy:0},G=await L.mutateAsync(N);if(G?.responseStatus){const re=G?.data||"Alert updated successfully.";pe.toast.success(re,{autoClose:1500,onClose:()=>{r(),t()}}),h(void 0),A("")}else{const re=G?.errorMessage||"Failed to update alert status";pe.toast.error(re)}}catch(N){console.error("Error updating alert status:",N),pe.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:Le,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:k||"Alert Event"}),U?.firstName?n.jsxs("div",{className:"text-sm text-gray-500",children:["Resident ID/Name: ",U?.firstName," ",U?.lastName||""," ",U?.residentId||""]}):null,n.jsxs("div",{className:"text-sm text-gray-500",children:["Timestamp: ",ht(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]}),b&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Assigned to: ",b]}),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 ${wn[String(v)]||"#DFE4EA"}`,backgroundColor:jn[String(v)]},children:["Severity: ",v||"N/A"]}),n.jsxs(c.Tag,{className:"font-sm text-gray-500 rounded-[8px] py-2 px-3",style:String(M||"").toLowerCase()==="completed"?{background:"#E7F6EC",border:"0.68px solid var(--Green, #34C759)"}:{background:"#E0EDFF",border:"1px solid var(--Grays-Gray-4, #D1D1D6)"},children:["Status: ",M||"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:ce,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"}),we.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(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]}),we.length?n.jsx("div",{className:"w-full",children:n.jsx(c.Carousel,{ref:w,dots:!0,className:"w-full",children:we.map((N,G)=>n.jsxs("div",{className:"flex justify-center items-center",children:[nt(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-${G}`,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}),!nt(N)&&R[String(N.mediaUrl||N)]?n.jsx("button",{onClick:()=>{H(!0),Y(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(bs,{size:20})}):null]},G))})}):null]})}),n.jsx(bn,{isOpen:z,onClose:()=>H(!1),src:W||"",type:T||"image"})]})},{key:"track",label:"Track Incident",children:n.jsx(dn,{alertId:x,id:D,priority:v,spaceName:g,alertNumber:se,statusHistory:B,notifGroups:$})}]})})};function Ss(){const{alerts:e}=ve(),t=Je({queryKey:["alerts","statusList"],queryFn:()=>e.getAlertStatusList(),staleTime:5*6e4});return{list:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function Cn(){const{alerts:e}=ve(),t=Je({queryKey:["alerts","timeZoneMasters"],queryFn:()=>e.getTimeZoneMasters?e.getTimeZoneMasters():Promise.resolve([]),staleTime:30*6e4,enabled:typeof e.getTimeZoneMasters=="function"});return{timeZoneMasters:t.data??[],loading:t.isLoading,error:t.error}}function At({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}=Ss(),{timeZoneMasters:m}=Cn(),I=u.useMemo(()=>{const E="America/New_York";if(!e.length||!m.length)return{label:"USA",ianaTimeZoneId:E};const z=e[0].timeZoneUniqueId;if(!z)return{label:"USA",ianaTimeZoneId:E};const H=m.find(W=>W.timeZoneUniqueId===z);return H?{label:H.timeZoneName,ianaTimeZoneId:H.ianaTimeZoneId}:{label:"USA",ianaTimeZoneId:E}},[e,m]);function w(L,E){l(L),h(E?.tab??"details"),$(E?.sourceTab??"active"),a(!0)}function p(){a(!1)}const[S,$]=u.useState("active"),F=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(fs,{label:I.label,timeZone:I.ianaTimeZoneId})]}),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(pt,{data:e,loading:t,pageSize:10,columns:s||[],onAlertIdClick:w,onRefetch:r})},{key:"archived",label:"Archived",children:n.jsx(hs,{alerts:e,loading:t,columns:s||[],onAlertIdClick:w})},{key:"settings",label:"Settings",children:n.jsx(Tn,{})}]}),n.jsx(Nn,{isModalOpen:i,handleModalClose:p,selectedRow:F,fetchAlertLogs:()=>{},alertStatusList:d,alertStatusLoading:A,initialTab:f,sourceTab:S})]})}function Tn(){const[e,t]=u.useState([]),[s,r]=u.useState([]),[i,a]=u.useState([]),{rules:o}=ve();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:Fe.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:Fe.userRoles)}catch{r(Fe.userRoles)}}catch{t(Fe.rules),r(Fe.userRoles)}})(),()=>{l=!1}},[]),n.jsx(gs,{severities:Fe.severities,rules:e,userRoles:s,rawRules:i})}function As(){const{alerts:e}=ve(),t=Je({queryKey:["alerts","list"],queryFn:()=>e.listAlerts(),staleTime:3e4});return{alerts:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function In(e){const{alerts:t,loading:s,refetch:r}=As();return n.jsx(At,{alerts:t,loading:s,columns:e.columns,onRefetch:r})}function Rn({tenant:e,apiDomain:t,rulesDomain:s,headers:r,alerts:i,loading:a,columns:o}){const[l]=u.useState(()=>new Mr),f=u.useMemo(()=>({alertsBaseUrl:t,rulesBaseUrl:s||t,headers:r||void 0}),[t,s,r]);return n.jsx(Or,{client:l,children:n.jsx(ts,{tenant:e,override:f,children:Array.isArray(i)?n.jsx(At,{alerts:i,loading:!!a,columns:o}):n.jsx(In,{columns:o})})})}function kn(e){const{alerts:t}=ve(),s=Je({queryKey:["alerts","report",e],queryFn:()=>t.getAlertsReport(e),staleTime:6e4});return{data:s.data??[],loading:s.isLoading,error:s.error,refetch:s.refetch}}const En=[{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=ms;exports.AlertConsole=At;exports.AlertConsoleWidget=Rn;exports.AlertsTable=pt;exports.ApiProvider=ts;exports.ArchivedTable=hs;exports.Clock=fs;exports.DataTable=ss;exports.MyPreferencesPanel=ys;exports.SettingsPanel=ps;exports.SettingsTabs=gs;exports.exampleAlertColumns=En;exports.useAlertStatusList=Ss;exports.useAlerts=As;exports.useAlertsReport=kn;exports.useApi=ve;exports.useUpdateAlertStatus=St;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|