@ssgc/alert-console 2.2.0 → 2.2.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 +131 -131
- package/dist/index.es.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),h=require("react"),c=require("antd"),ke=require("@ant-design/icons"),ne=require("react-toastify");function As(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const le=As(h),Ns="#FF3B30",js="#FF9500",ws="#FFCC00",Cs="#34C759",De={critical:Ns,high:js,medium:ws,low:Cs},At={Critical:De.critical,High:De.high,Medium:De.medium,Low:De.low};function Is(e){return At[e]||At.Low}function Nt(e){if(!e||typeof e!="string")return 0;const t=e.trim().split(":");if(t.length!==3)return 0;const[s,r,i]=t,a=Number.parseInt(s,10),o=Number.parseInt(r,10),l=Number.parseFloat(i||"0"),f=Number.isFinite(a)?a:0,d=Number.isFinite(o)?o:0,m=Number.isFinite(l)?l:0;return f*3600+d*60+m}function Ve(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 Ht="",Ts=Ht,Rs="",ks="",jt={snl:{alerts:Ht,rules:Ts},schools:{alerts:Rs,rules:ks}};function me(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Os(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function Fe(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 pe(e,t){const s={...t.headers,...Os()},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 Es(e){console.log("baseurl",e);const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=me(e.baseUrl,"/api/Alert"),r=await pe(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertStatusList(){const s=me(e.baseUrl,"/api/Alert/AlertStatusList"),r=await pe(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=me(e.baseUrl,"/Alerts/GetAlertsReport"),i=Fe(r,s),a=await pe(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=me(e.baseUrl,"/api/Alert/status");return pe(r,{method:"PUT",headers:t,body:JSON.stringify(s??{})})},async getAdminSettings(){const s=me(e.baseUrl,"/api/Alert/GetAdminSettings"),r=await pe(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=me(e.baseUrl,"/api/Alert/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??"",groupBy:s?.groupBy??null};return pe(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=me(e.baseUrl,"/api/Alert/GetPreferenceSettings"),r=await pe(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=me(e.baseUrl,"/api/Alert/SetPreferenceSettings"),i=await pe(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=me(e.baseUrl,"/api/Alert/GetNotifications"),i=Fe(r,{alertId:s}),a=await pe(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=me(e.baseUrl,"/api/Alert/NotificationToFamilyMembers"),i=Fe(r,{alertId:s});return pe(i,{method:"POST",headers:t})},async sendSMSorEmailNotifications(s,r,i){const a=me(e.baseUrl,"/api/Alert/SendSMSorEmailNotifications"),o=Fe(a,{alertId:s,isEmail:r,isSMS:i});return pe(o,{method:"POST",headers:t})}}}function wt(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Ps(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Ue(e,t){const s={...t.headers,...Ps()},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 Ms(e){const t={"Content-Type":"application/json",...e.headers||{}},s=wt(e.baseUrl,"/api/Rules"),r=wt(e.baseUrl,"/api/Rules/lookups");return{async getRules(){const i=await Ue(s,{method:"GET",headers:t});return Array.isArray(i)?i:[]},async setEscalationSettings(i){return Ue(s,{method:"POST",headers:t,body:JSON.stringify(i??{})})},async getLookups(){return Ue(r,{method:"GET",headers:t})},async updateRule(i,a){const o=`${s}/${i}`;return Ue(o,{method:"PUT",headers:t,body:JSON.stringify(a??{})})}}}function Ds(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Be={exports:{}},Fs=Be.exports,Ct;function Us(){return Ct||(Ct=1,(function(e,t){(function(s,r){e.exports=r()})(Fs,(function(){var s=1e3,r=6e4,i=36e5,a="millisecond",o="second",l="minute",f="hour",d="day",m="week",b="month",y="quarter",C="year",w="date",p="Invalid Date",A=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,U=/\[([^\]]+)]|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,L={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 v=["th","st","nd","rd"],g=k%100;return"["+k+(v[(g-20)%10]||v[g]||v[0])+"]"}},$=function(k,v,g){var S=String(k);return!S||S.length>=v?k:""+Array(v+1-S.length).join(g)+k},D={s:$,z:function(k){var v=-k.utcOffset(),g=Math.abs(v),S=Math.floor(g/60),u=g%60;return(v<=0?"+":"-")+$(S,2,"0")+":"+$(u,2,"0")},m:function k(v,g){if(v.date()<g.date())return-k(g,v);var S=12*(g.year()-v.year())+(g.month()-v.month()),u=v.clone().add(S,b),x=g-u<0,N=v.clone().add(S+(x?-1:1),b);return+(-(S+(g-u)/(x?u-N:N-u))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:b,y:C,w:m,d,D:w,h:f,m:l,s:o,ms:a,Q:y}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},Y="en",z={};z[Y]=L;var _="$isDayjsObject",G=function(k){return k instanceof ee||!(!k||!k[_])},I=function k(v,g,S){var u;if(!v)return Y;if(typeof v=="string"){var x=v.toLowerCase();z[x]&&(u=x),g&&(z[x]=g,u=x);var N=v.split("-");if(!u&&N.length>1)return k(N[0])}else{var E=v.name;z[E]=v,u=E}return!S&&u&&(Y=u),u||!S&&Y},j=function(k,v){if(G(k))return k.clone();var g=typeof v=="object"?v:{};return g.date=k,g.args=arguments,new ee(g)},T=D;T.l=I,T.i=G,T.w=function(k,v){return j(k,{locale:v.$L,utc:v.$u,x:v.$x,$offset:v.$offset})};var ee=(function(){function k(g){this.$L=I(g.locale,null,!0),this.parse(g),this.$x=this.$x||g.x||{},this[_]=!0}var v=k.prototype;return v.parse=function(g){this.$d=(function(S){var u=S.date,x=S.utc;if(u===null)return new Date(NaN);if(T.u(u))return new Date;if(u instanceof Date)return new Date(u);if(typeof u=="string"&&!/Z$/i.test(u)){var N=u.match(A);if(N){var E=N[2]-1||0,R=(N[7]||"0").substring(0,3);return x?new Date(Date.UTC(N[1],E,N[3]||1,N[4]||0,N[5]||0,N[6]||0,R)):new Date(N[1],E,N[3]||1,N[4]||0,N[5]||0,N[6]||0,R)}}return new Date(u)})(g),this.init()},v.init=function(){var g=this.$d;this.$y=g.getFullYear(),this.$M=g.getMonth(),this.$D=g.getDate(),this.$W=g.getDay(),this.$H=g.getHours(),this.$m=g.getMinutes(),this.$s=g.getSeconds(),this.$ms=g.getMilliseconds()},v.$utils=function(){return T},v.isValid=function(){return this.$d.toString()!==p},v.isSame=function(g,S){var u=j(g);return this.startOf(S)<=u&&u<=this.endOf(S)},v.isAfter=function(g,S){return j(g)<this.startOf(S)},v.isBefore=function(g,S){return this.endOf(S)<j(g)},v.$g=function(g,S,u){return T.u(g)?this[S]:this.set(u,g)},v.unix=function(){return Math.floor(this.valueOf()/1e3)},v.valueOf=function(){return this.$d.getTime()},v.startOf=function(g,S){var u=this,x=!!T.u(S)||S,N=T.p(g),E=function(K,te){var se=T.w(u.$u?Date.UTC(u.$y,te,K):new Date(u.$y,te,K),u);return x?se:se.endOf(d)},R=function(K,te){return T.w(u.toDate()[K].apply(u.toDate("s"),(x?[0,0,0,0]:[23,59,59,999]).slice(te)),u)},F=this.$W,q=this.$M,B=this.$D,M="set"+(this.$u?"UTC":"");switch(N){case C:return x?E(1,0):E(31,11);case b:return x?E(1,q):E(0,q+1);case m:var W=this.$locale().weekStart||0,X=(F<W?F+7:F)-W;return E(x?B-X:B+(6-X),q);case d:case w:return R(M+"Hours",0);case f:return R(M+"Minutes",1);case l:return R(M+"Seconds",2);case o:return R(M+"Milliseconds",3);default:return this.clone()}},v.endOf=function(g){return this.startOf(g,!1)},v.$set=function(g,S){var u,x=T.p(g),N="set"+(this.$u?"UTC":""),E=(u={},u[d]=N+"Date",u[w]=N+"Date",u[b]=N+"Month",u[C]=N+"FullYear",u[f]=N+"Hours",u[l]=N+"Minutes",u[o]=N+"Seconds",u[a]=N+"Milliseconds",u)[x],R=x===d?this.$D+(S-this.$W):S;if(x===b||x===C){var F=this.clone().set(w,1);F.$d[E](R),F.init(),this.$d=F.set(w,Math.min(this.$D,F.daysInMonth())).$d}else E&&this.$d[E](R);return this.init(),this},v.set=function(g,S){return this.clone().$set(g,S)},v.get=function(g){return this[T.p(g)]()},v.add=function(g,S){var u,x=this;g=Number(g);var N=T.p(S),E=function(q){var B=j(x);return T.w(B.date(B.date()+Math.round(q*g)),x)};if(N===b)return this.set(b,this.$M+g);if(N===C)return this.set(C,this.$y+g);if(N===d)return E(1);if(N===m)return E(7);var R=(u={},u[l]=r,u[f]=i,u[o]=s,u)[N]||1,F=this.$d.getTime()+g*R;return T.w(F,this)},v.subtract=function(g,S){return this.add(-1*g,S)},v.format=function(g){var S=this,u=this.$locale();if(!this.isValid())return u.invalidDate||p;var x=g||"YYYY-MM-DDTHH:mm:ssZ",N=T.z(this),E=this.$H,R=this.$m,F=this.$M,q=u.weekdays,B=u.months,M=u.meridiem,W=function(te,se,de,ce){return te&&(te[se]||te(S,x))||de[se].slice(0,ce)},X=function(te){return T.s(E%12||12,te,"0")},K=M||function(te,se,de){var ce=te<12?"AM":"PM";return de?ce.toLowerCase():ce};return x.replace(U,(function(te,se){return se||(function(de){switch(de){case"YY":return String(S.$y).slice(-2);case"YYYY":return T.s(S.$y,4,"0");case"M":return F+1;case"MM":return T.s(F+1,2,"0");case"MMM":return W(u.monthsShort,F,B,3);case"MMMM":return W(B,F);case"D":return S.$D;case"DD":return T.s(S.$D,2,"0");case"d":return String(S.$W);case"dd":return W(u.weekdaysMin,S.$W,q,2);case"ddd":return W(u.weekdaysShort,S.$W,q,3);case"dddd":return q[S.$W];case"H":return String(E);case"HH":return T.s(E,2,"0");case"h":return X(1);case"hh":return X(2);case"a":return K(E,R,!0);case"A":return K(E,R,!1);case"m":return String(R);case"mm":return T.s(R,2,"0");case"s":return String(S.$s);case"ss":return T.s(S.$s,2,"0");case"SSS":return T.s(S.$ms,3,"0");case"Z":return N}return null})(te)||N.replace(":","")}))},v.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},v.diff=function(g,S,u){var x,N=this,E=T.p(S),R=j(g),F=(R.utcOffset()-this.utcOffset())*r,q=this-R,B=function(){return T.m(N,R)};switch(E){case C:x=B()/12;break;case b:x=B();break;case y:x=B()/3;break;case m:x=(q-F)/6048e5;break;case d:x=(q-F)/864e5;break;case f:x=q/i;break;case l:x=q/r;break;case o:x=q/s;break;default:x=q}return u?x:T.a(x)},v.daysInMonth=function(){return this.endOf(b).$D},v.$locale=function(){return z[this.$L]},v.locale=function(g,S){if(!g)return this.$L;var u=this.clone(),x=I(g,S,!0);return x&&(u.$L=x),u},v.clone=function(){return T.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},k})(),re=ee.prototype;return j.prototype=re,[["$ms",a],["$s",o],["$m",l],["$H",f],["$W",d],["$M",b],["$y",C],["$D",w]].forEach((function(k){re[k[1]]=function(v){return this.$g(v,k[0],k[1])}})),j.extend=function(k,v){return k.$i||(k(v,ee,j),k.$i=!0),j},j.locale=I,j.isDayjs=G,j.unix=function(k){return j(1e3*k)},j.en=z[Y],j.Ls=z,j.p={},j}))})(Be)),Be.exports}var Ls=Us();const $s=Ds(Ls);function Gt(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 Wt(e){if(!e||typeof e!="string")return{hours:0,minutes:0,seconds:0};const t=e.split(":").map(a=>parseInt(a,10)),s=Number.isFinite(t[0])?t[0]:0,r=Number.isFinite(t[1])?t[1]:0,i=Number.isFinite(t[2])?t[2]:0;return{hours:s,minutes:r,seconds:i}}function It(e){const{hours:t,minutes:s,seconds:r}=Wt(e);return $s().hour(t).minute(s).second(r).millisecond(0)}function ve(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Bs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function Tt(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,...Bs()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.Message||`HTTP ${r.status}`;throw new Error(o)}return a}const ae=(...e)=>e.find(t=>t!=null);function qs(e){return{id:String(ae(e?.AlertId,e?.alertId)??""),priority:ae(e?.Priority,e?.priority,"Low"),timestamp:ae(e?.Timestamp,e?.timestamp,""),statusType:ae(e?.Status,e?.statusType,""),description:ae(e?.Description,e?.description,""),eventName:ae(e?.EventName,e?.eventName),ruleName:ae(e?.RuleName,e?.ruleName),spaceName:ae(e?.SpaceName,e?.spaceName),assignTeam:ae(e?.AssignTeam,e?.assignTeam),cameraName:ae(e?.CameraName,e?.cameraName),type:ae(e?.Type,e?.type),mediaDetails:ae(e?.MediaDetails,e?.mediaDetails),additionalMedia:ae(e?.AdditionalMedia,e?.additionalMedia),timeElapsed:ae(e?.TimeElapsed,e?.timeElapsed),timeRemaining:ae(e?.TimeRemaining,e?.timeRemaining),anomalyName:ae(e?.AnomalyName,e?.anomalyName),alertDetails:ae(e?.AlertDetails,e?.alertDetails),statusHistory:ae(e?.StatusHistory,e?.statusHistory)}}function Qs(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=ve(e.baseUrl,"/api/detectionpolicy/alerts?customerId=99e5c8b5-b9d4-4d35-8885-7f121c532664"),r=await xe(s,{method:"GET",headers:t});return Array.isArray(r?.Items)?(r?.Items).map(qs):[]},async getAlertStatusList(){const s=ve(e.baseUrl,"/api/detectionpolicy/alerts/StatusList"),r=await xe(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertsReport(s){const r=ve(e.baseUrl,"/api/detectionpolicy/alerts/GetAlertsReport"),i=Tt(r,s),a=await xe(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=ve(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 xe(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getAdminSettings(){const s=ve(e.baseUrl,"/api/detectionpolicy/alerts/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/detectionpolicy/alerts/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??""};return xe(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=ve(e.baseUrl,"/api/detectionpolicy/alerts/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/detectionpolicy/alerts/SetPreferenceSettings"),i=d=>{const{hours:m,minutes:b,seconds:y}=Wt(d);return(m*3600+b*60+y)*1e7},a={Settings:{UserId:0,AnomalyIds:Array.isArray(s?.anomalyIds)?s.anomalyIds.map(d=>String(d)):[],DoNotDisturbStart:{Ticks:i(s?.doNotDisturbStart)},DoNotDisturbEnd:{Ticks:i(s?.doNotDisturbEnd)},InApp:!!s?.inApp,SMS:!!s?.sms,Email:!!s?.email,SortBy:s?.sortBy??""}},o=await xe(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=ve(e.baseUrl,"/api/detectionpolicy/alerts/GetNotifications"),i=Tt(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:[]}}}function _s(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}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 Hs(e){const t={"Content-Type":"application/json",...e.headers||{}},s=new URL("/api/detectionpolicy/rules",e.baseUrl).toString();return{async getRules(){const r=await Se(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async setEscalationSettings(r){return Se(s,{method:"POST",headers:t,body:JSON.stringify(r??{})})},async getLookups(){const r=D=>new URL(D,e.baseUrl).toString(),i=[Se(r("/api/detectionpolicy/lookups/actiontypes"),{method:"GET",headers:t}),Se(r("/api/detectionpolicy/lookups/anomalies"),{method:"GET",headers:t}),Se(r("/api/detectionpolicy/lookups/thirdparty"),{method:"GET",headers:t}),Se(r("/api/detectionpolicy/lookups/severity"),{method:"GET",headers:t}),Se(r("/api/detectionpolicy/lookups/scheduletypes"),{method:"GET",headers:t})],[a,o,l,f,d]=await Promise.allSettled(i),m=D=>D.status==="fulfilled"&&Array.isArray(D.value)?D.value:[],b=m(a),y=m(o),C=m(l),w=m(f),p=m(d),A=b.map(D=>({actionTypeId:Number(D?.ActionTypeId),name:D?.DisplayName??D?.Name??""})),U=y.map(D=>({recordId:D?.AnomalyId,anomalyName:D?.DisplayName??D?.Name??""})),L=C.map(D=>({thirdPartyId:Number(D?.ThirdPartyId),thirdPartyName:D?.ThirdPartyName??D?.Name??""})),$={actionTypes:A,anomalies:U,thirdParties:L};return w.length&&($.severities=w),p.length&&($.scheduleTypes=p),$},async updateRule(r,i){const a=`${s}/${r}`;return Se(a,{method:"PUT",headers:t,body:JSON.stringify(i??{})})}}}const Kt=h.createContext(null);function Yt({tenant:e="snl",override:t,children:s}){const r=h.useMemo(()=>{const a=t?.alertsBaseUrl&&t.alertsBaseUrl.trim()||jt[e]?.alerts||"";let o=t?.rulesBaseUrl&&t.rulesBaseUrl.trim()||jt[e]?.rules||"";e==="snl"&&(o=a);const l=t?.headers;return{tenant:e,alertsBaseUrl:a,rulesBaseUrl:o,headers:l}},[e,t?.alertsBaseUrl,t?.rulesBaseUrl,JSON.stringify(t?.headers||{})]),i=h.useMemo(()=>{const a=r.tenant==="schools"?Qs({baseUrl:r.alertsBaseUrl,headers:r.headers}):Es({baseUrl:r.alertsBaseUrl,headers:r.headers}),o=r.tenant==="schools"?Hs({baseUrl:r.rulesBaseUrl,headers:r.headers}):Ms({baseUrl:r.alertsBaseUrl,headers:r.headers});return{config:r,alerts:a,rules:o}},[r]);return n.jsx(Kt.Provider,{value:i,children:s})}function fe(){const e=h.useContext(Kt);if(!e)throw new Error("useApi must be used inside ApiProvider");return e}const Gs={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Ws={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},at=6,ot=7;function Ks(e,t,s){const r=e===at,i=e===ot,a=!t.isEmailSent,o=!t.isSMSSent,l=r&&a||i&&o,f=r?"Send Email":i?"Send SMS":s,d=r&&a?"Email already sent":i&&o?"SMS already sent":`Click to ${f.toLowerCase()}`;return{isDisabled:l,buttonText:f,tooltipTitle:d}}function Ys(e){const t=new Set;(e||[]).forEach(r=>{const i=r.anomalyName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All Types",value:"All"},...s]}function zs(e){const t=new Set;(e||[]).forEach(r=>{const i=r.spaceName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All",value:"All"},...s]}function Rt(e,t){return`${e}-${t?"email":"sms"}`}function kt(e){return e===at||e===ot}function He({value:e,onChange:t,options:s,className:r,dropdownWidth:i}){return n.jsx(c.Select,{className:r,options:s,value:e,onChange:t,dropdownMatchSelectWidth:i??260})}const Vs=[{label:"All levels",value:"All"},{label:"Critical",value:"Critical"},{label:"High",value:"High"},{label:"Medium",value:"Medium"},{label:"Low",value:"Low"}];function Js({value:e,onChange:t,options:s}){return n.jsx(He,{className:"w-[140px]",value:e,onChange:t,options:s||Vs})}const Xs=[{label:"All Types",value:"All"},{label:"Weapon Detection",value:"Weapon"},{label:"Unauthorized Access",value:"Unauthorized"},{label:"Aggressive Behavior",value:"Aggressive"}];function Zs({value:e,onChange:t,options:s}){return n.jsx(He,{className:"w-[220px]",dropdownWidth:280,value:e,onChange:t,options:s||Xs})}function er({value:e,onChange:t,options:s}){return n.jsx(He,{className:"w-[100px]",value:e,onChange:t,options:s||[]})}const tr=[{label:"All",value:"All"},{label:"SOS",value:"SOS"},{label:"911",value:"911"},{label:"Aegix",value:"Aegix"},{label:"Eli",value:"Eli"},{label:"Skydio",value:"Skydio"}];function sr({value:e,onChange:t,options:s}){return n.jsx(He,{className:"w-[130px]",value:e,onChange:t,options:s||tr})}function zt({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 lt({data:e,loading:t=!1,pageSize:s=10,columns:r,severityOptions:i,spaceOptions:a,renderActions:o,onAlertIdClick:l,onRefetch:f}){const[d,m]=h.useState("All"),[b,y]=h.useState("All"),[C,w]=h.useState("All"),[p,A]=h.useState("All"),[U,L]=h.useState(""),[$,D]=h.useState([{label:"All",value:"All"}]),[Y,z]=h.useState(new Set),{rules:_,alerts:G}=fe(),I={6:{title:"Email",kind:"icon",icon:n.jsx(ke.MailOutlined,{})},7:{title:"SMS",kind:"icon",icon:n.jsx(ke.MessageOutlined,{})}},j=h.useMemo(()=>Ys(e),[e]),T=h.useMemo(()=>zs(e),[e]);h.useEffect(()=>{let u=!0;return(async()=>{try{const x=await _.getLookups(),E=(Array.isArray(x.thirdParties)?x.thirdParties:[]).map(R=>({label:R.thirdPartyName,value:String(R.thirdPartyId)}));u&&D([{label:"All",value:"All"},...E])}catch(x){console.error("Error loading third party options",x)}})(),()=>{u=!1}},[_]);const ee=h.useMemo(()=>(e||[]).some(u=>Ve(u).length>0),[e]),re=h.useMemo(()=>(e||[]).filter(u=>{const x=d==="All"||u.priority===d,N=`${u.id} ${u.description} ${u.statusType}`.toLowerCase(),E=!U||N.includes(U.toLowerCase()),R=b==="All"||(u.anomalyName||"").toLowerCase()===b.toLowerCase(),F=C==="All"||(u.spaceName||"").toLowerCase()===C.toLowerCase(),q=!ee||p==="All"||Ve(u).includes(Number(p));return x&&E&&R&&F&&q}),[e,d,U,b,C,p,ee]),k=j,v=a&&a.length?a:T,g=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:u=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${Ws[u]}`,backgroundColor:Gs[u]},children:u})},{title:"Tracker",key:"tracker",width:140,render:(u,x)=>n.jsx("a",{onClick:N=>{N.preventDefault(),l?.(x,{tab:"track"})},className:"text-blue-600 hover:underline",children:"Tracker"})},{title:"Call to action/Human in the loop",key:"actions",width:320,render:(u,x)=>{if(o)return n.jsx(n.Fragment,{children:o(x)});const N=Ve(x);if(!N.length)return null;const E=async(R,F)=>{const q=Rt(x.id,R);z(B=>new Set(B).add(q));try{const B=await G.sendSMSorEmailNotifications?.(x.id,R,F);B?.responseStatus?(ne.toast.success(B.data||(R?"Email sent successfully":"SMS sent successfully")),f?.()):ne.toast.error(B?.data||B?.errorMessage||"Failed to send notification")}catch(B){ne.toast.error(B?.message||"Failed to send notification")}finally{z(B=>{const M=new Set(B);return M.delete(q),M})}};return n.jsx(c.Space,{size:"middle",children:N.map(R=>{const F=I[R];if(!F)return null;const q=R===at,B=R===ot,{isDisabled:M,buttonText:W,tooltipTitle:X}=Ks(R,x,F.title),K=Rt(x.id,q),te=kt(R)&&Y.has(K),se=()=>{E(q,B)};return n.jsx(c.Tooltip,{title:X,children:n.jsx(c.Button,{size:"small",disabled:M,loading:te,onClick:kt(R)?se:void 0,icon:!te&&(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:W})},R)})})}},{title:"Alert Timestamp",dataIndex:"timestamp",key:"timestamp",width:220,render:(u,x)=>{const N=x.timeElapsed?x.timeElapsed:void 0,E=x.timeRemaining?x.timeRemaining:void 0,R=N?Nt(N):0,F=E?Nt(E):0,q=Math.round(R/(R+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:N??"-"})]}),n.jsx(c.Progress,{percent:q,showInfo:!1,size:"small",strokeColor:Is(x.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:E??"-"})]})]})}},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(u,x)=>n.jsxs("div",{children:[n.jsx("a",{onClick:N=>{N.preventDefault(),l?.(x)},className:"inline-block mb-1 text-blue-600",children:x.alertNumber}),n.jsx("div",{className:"text-black/65",children:u})]})}],S=r&&r.length?r:g;return n.jsx("div",{children:n.jsx(zt,{rowKey:"id",data:re,columns:S,loading:t,pageSize:s,toolbar:n.jsxs(c.Row,{gutter:[12,12],className:"mb-3",align:"middle",children:[n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Severity"}),n.jsx(Js,{value:d,onChange:m,options:i})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Anomaly type"}),n.jsx(Zs,{value:b,onChange:y,options:k})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Space"}),n.jsx(er,{value:C,onChange:w,options:v})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Action Taken"}),n.jsx(sr,{value:p,onChange:A,options:$})]})}),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:u=>L(u.target.value),className:"w-[260px] ",enterButton:!0})})]})})})}var Oe=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},rr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nr=class{#e=rr;#t=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#t&&e!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:e}),this.#e=e,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},je=new nr;function ir(e){setTimeout(e,0)}var we=typeof window>"u"||"Deno"in globalThis;function ue(){}function ar(e,t){return typeof e=="function"?e(t):e}function Ze(e){return typeof e=="number"&&e>=0&&e!==1/0}function Vt(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ae(e,t){return typeof e=="function"?e(t):e}function he(e,t){return typeof e=="function"?e(t):e}function Ot(e,t){const{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:l}=e;if(o){if(r){if(t.queryHash!==ct(o,t.options))return!1}else if(!Pe(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 Et(e,t){const{exact:s,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(s){if(Ce(t.options.mutationKey)!==Ce(a))return!1}else if(!Pe(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function ct(e,t){return(t?.queryKeyHashFn||Ce)(e)}function Ce(e){return JSON.stringify(e,(t,s)=>tt(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}function Pe(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>Pe(e[s],t[s])):!1}var or=Object.prototype.hasOwnProperty;function et(e,t){if(e===t)return e;const s=Pt(e)&&Pt(t);if(!s&&!(tt(e)&&tt(t)))return t;const i=(s?e:Object.keys(e)).length,a=s?t:Object.keys(t),o=a.length,l=s?new Array(o):{};let f=0;for(let d=0;d<o;d++){const m=s?d:a[d],b=e[m],y=t[m];if(b===y){l[m]=b,(s?d<i:or.call(e,m))&&f++;continue}if(b===null||y===null||typeof b!="object"||typeof y!="object"){l[m]=y;continue}const C=et(b,y);l[m]=C,C===b&&f++}return i===o&&f===i?e:l}function qe(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 Pt(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function tt(e){if(!Mt(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!Mt(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Mt(e){return Object.prototype.toString.call(e)==="[object Object]"}function lr(e){return new Promise(t=>{je.setTimeout(t,e)})}function st(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 et(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 et(e,t)}return t}function cr(e,t,s=0){const r=[...e,t];return s&&r.length>s?r.slice(1):r}function ur(e,t,s=0){const r=[t,...e];return s&&r.length>s?r.slice(0,-1):r}var Qe=Symbol();function Jt(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===Qe&&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===Qe?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ut(e,t){return typeof e=="function"?e(...t):!!e}function dr(e,t,s){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i)}),e}var hr=class extends Oe{#e;#t;#s;constructor(){super(),this.#s=e=>{if(!we&&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"}},dt=new hr;function rt(){let e,t;const s=new Promise((i,a)=>{e=i,t=a});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return s.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},s.reject=i=>{r({status:"rejected",reason:i}),t(i)},s}var fr=ir;function mr(){let e=[],t=0,s=l=>{l()},r=l=>{l()},i=fr;const a=l=>{t?e.push(l):i(()=>{s(l)})},o=()=>{const l=e;e=[],l.length&&i(()=>{r(()=>{l.forEach(f=>{s(f)})})})};return{batch:l=>{let f;t++;try{f=l()}finally{t--,t||o()}return f},batchCalls:l=>(...f)=>{a(()=>{l(...f)})},schedule:a,setNotifyFunction:l=>{s=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{i=l}}}var ie=mr(),pr=class extends Oe{#e=!0;#t;#s;constructor(){super(),this.#s=e=>{if(!we&&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}},_e=new pr;function yr(e){return Math.min(1e3*2**e,3e4)}function Xt(e){return(e??"online")==="online"?_e.isOnline():!0}var nt=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Zt(e){let t=!1,s=0,r;const i=rt(),a=()=>i.status!=="pending",o=p=>{if(!a()){const A=new nt(p);y(A),e.onCancel?.(A)}},l=()=>{t=!0},f=()=>{t=!1},d=()=>dt.isFocused()&&(e.networkMode==="always"||_e.isOnline())&&e.canRun(),m=()=>Xt(e.networkMode)&&e.canRun(),b=p=>{a()||(r?.(),i.resolve(p))},y=p=>{a()||(r?.(),i.reject(p))},C=()=>new Promise(p=>{r=A=>{(a()||d())&&p(A)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),w=()=>{if(a())return;let p;const A=s===0?e.initialPromise:void 0;try{p=A??e.fn()}catch(U){p=Promise.reject(U)}Promise.resolve(p).then(b).catch(U=>{if(a())return;const L=e.retry??(we?0:3),$=e.retryDelay??yr,D=typeof $=="function"?$(s,U):$,Y=L===!0||typeof L=="number"&&s<L||typeof L=="function"&&L(s,U);if(t||!Y){y(U);return}s++,e.onFail?.(s,U),lr(D).then(()=>d()?void 0:C()).then(()=>{t?y(U):w()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:l,continueRetry:f,canStart:m,start:()=>(m()?w():C().then(w),i)}}var es=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ze(this.gcTime)&&(this.#e=je.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(we?1/0:300*1e3))}clearGcTimeout(){this.#e&&(je.clearTimeout(this.#e),this.#e=void 0)}},gr=class extends es{#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=Ft(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=Ft(this.options);t.data!==void 0&&(this.setState(Dt(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const s=st(this.state.data,e,this.options);return this.#i({data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(ue).catch(ue):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>he(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Qe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ae(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:!Vt(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=Jt(this.options,t),d=(()=>{const m={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(m),m})();return this.#o=!1,this.options.persister?this.options.persister(l,d,this):l(d)},o=(()=>{const l={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(l),l})();this.options.behavior?.onFetch(o,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#i({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=Zt({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof nt&&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 nt){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,...ts(s.data,this.options),fetchMeta:e.meta??null};case"success":const r={...s,...Dt(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),ie.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function ts(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Xt(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Dt(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ft(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,r=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var vr=class extends Oe{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=rt(),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),Ut(this.#t,this.options)?this.#d():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return it(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return it(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 he(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#A(),this.#t.setOptions(this.options),t._defaulted&&!qe(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&Lt(this.#t,s,this.options,t)&&this.#d(),this.updateResult(),r&&(this.#t!==s||he(this.options.enabled,this.#t)!==he(t.enabled,this.#t)||Ae(this.options.staleTime,this.#t)!==Ae(t.staleTime,this.#t))&&this.#y();const i=this.#g();r&&(this.#t!==s||he(this.options.enabled,this.#t)!==he(t.enabled,this.#t)||i!==this.#l)&&this.#v(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),s=this.createResult(t,e);return br(this,s)&&(this.#n=s,this.#a=this.options,this.#r=this.#t.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(s,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),s=this.#e.getQueryCache().build(this.#e,t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#d(e){this.#A();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(ue)),t}#y(){this.#b();const e=Ae(this.options.staleTime,this.#t);if(we||this.#n.isStale||!Ze(e))return;const s=Vt(this.#n.dataUpdatedAt,e)+1;this.#c=je.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,!(we||he(this.options.enabled,this.#t)===!1||!Ze(this.#l)||this.#l===0)&&(this.#u=je.setInterval(()=>{(this.options.refetchIntervalInBackground||dt.isFocused())&&this.#d()},this.#l))}#x(){this.#y(),this.#v(this.#g())}#b(){this.#c&&(je.clearTimeout(this.#c),this.#c=void 0)}#S(){this.#u&&(je.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const s=this.#t,r=this.options,i=this.#n,a=this.#r,o=this.#a,f=e!==s?e.state:this.#s,{state:d}=e;let m={...d},b=!1,y;if(t._optimisticResults){const G=this.hasListeners(),I=!G&&Ut(e,t),j=G&&Lt(e,s,t,r);(I||j)&&(m={...m,...ts(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(m.fetchStatus="idle")}let{error:C,errorUpdatedAt:w,status:p}=m;y=m.data;let A=!1;if(t.placeholderData!==void 0&&y===void 0&&p==="pending"){let G;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(G=i.data,A=!0):G=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,G!==void 0&&(p="success",y=st(i?.data,G,t),b=!0)}if(t.select&&y!==void 0&&!A)if(i&&y===a?.data&&t.select===this.#p)y=this.#h;else try{this.#p=t.select,y=t.select(y),y=st(i?.data,y,t),this.#h=y,this.#i=null}catch(G){this.#i=G}this.#i&&(C=this.#i,y=this.#h,w=Date.now(),p="error");const U=m.fetchStatus==="fetching",L=p==="pending",$=p==="error",D=L&&U,Y=y!==void 0,_={status:p,fetchStatus:m.fetchStatus,isPending:L,isSuccess:p==="success",isError:$,isInitialLoading:D,isLoading:D,data:y,dataUpdatedAt:m.dataUpdatedAt,error:C,errorUpdatedAt:w,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>f.dataUpdateCount||m.errorUpdateCount>f.errorUpdateCount,isFetching:U,isRefetching:U&&!L,isLoadingError:$&&!Y,isPaused:m.fetchStatus==="paused",isPlaceholderData:b,isRefetchError:$&&Y,isStale:ht(e,t),refetch:this.refetch,promise:this.#o,isEnabled:he(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const G=T=>{_.status==="error"?T.reject(_.error):_.data!==void 0&&T.resolve(_.data)},I=()=>{const T=this.#o=_.promise=rt();G(T)},j=this.#o;switch(j.status){case"pending":e.queryHash===s.queryHash&&G(j);break;case"fulfilled":(_.status==="error"||_.data!==j.value)&&I();break;case"rejected":(_.status!=="error"||_.error!==j.reason)&&I();break}}return _}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),qe(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.#N({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()}#N(e){ie.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xr(e,t){return he(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ut(e,t){return xr(e,t)||e.state.data!==void 0&&it(e,t,t.refetchOnMount)}function it(e,t,s){if(he(t.enabled,e)!==!1&&Ae(t.staleTime,e)!=="static"){const r=typeof s=="function"?s(e):s;return r==="always"||r!==!1&&ht(e,t)}return!1}function Lt(e,t,s,r){return(e!==t||he(r.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&ht(e,s)}function ht(e,t){return he(t.enabled,e)!==!1&&e.isStaleByTime(Ae(t.staleTime,e))}function br(e,t){return!qe(e.getCurrentResult(),t)}function $t(e){return{onFetch:(t,s)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},f=0;const d=async()=>{let m=!1;const b=w=>{dr(w,()=>t.signal,()=>m=!0)},y=Jt(t.options,t.fetchOptions),C=async(w,p,A)=>{if(m)return Promise.reject();if(p==null&&w.pages.length)return Promise.resolve(w);const L=(()=>{const z={client:t.client,queryKey:t.queryKey,pageParam:p,direction:A?"backward":"forward",meta:t.options.meta};return b(z),z})(),$=await y(L),{maxPages:D}=t.options,Y=A?ur:cr;return{pages:Y(w.pages,$,D),pageParams:Y(w.pageParams,p,D)}};if(i&&a.length){const w=i==="backward",p=w?Sr:Bt,A={pages:a,pageParams:o},U=p(r,A);l=await C(A,U,w)}else{const w=e??a.length;do{const p=f===0?o[0]??r.initialPageParam:Bt(r,l);if(f>0&&p==null)break;l=await C(l,p),f++}while(f<w)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s):t.fetchFn=d}}}function Bt(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 Sr(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}var Ar=class extends es{#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||ss(),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=Zt({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}),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),ie.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function ss(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Nr=class extends Oe{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(e,t,s){const r=new Ar({client:e,mutationCache:this,mutationId:++this.#s,options:e.defaultMutationOptions(t),state:s});return this.add(r),r}add(e){this.#e.add(e);const t=Le(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=Le(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=Le(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=Le(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){ie.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=>Et(t,s))}findAll(e={}){return this.getAll().filter(t=>Et(e,t))}notify(e){ie.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return ie.batch(()=>Promise.all(e.map(t=>t.continue().catch(ue))))}};function Le(e){return e.options.scope?.id}var jr=class extends Oe{#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),qe(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&Ce(t.mutationKey)!==Ce(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??ss();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){ie.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)})})}},wr=class extends Oe{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,s){const r=t.queryKey,i=t.queryHash??ct(r,t);let a=this.get(i);return a||(a=new gr({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){ie.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=>Ot(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Ot(e,s)):t}notify(e){ie.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ie.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ie.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Cr=class{#e;#t;#s;#n;#r;#a;#o;#i;constructor(e={}){this.#e=e.queryCache||new wr,this.#t=e.mutationCache||new Nr,this.#s=e.defaultOptions||{},this.#n=new Map,this.#r=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=dt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=_e.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(Ae(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:s})=>{const r=s.data;return[t,r]})}setQueryData(e,t,s){const r=this.defaultQueryOptions({queryKey:e}),a=this.#e.get(r.queryHash)?.state.data,o=ar(t,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return ie.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;ie.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#e;return ie.batch(()=>(s.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},r=ie.batch(()=>this.#e.findAll(e).map(i=>i.cancel(s)));return Promise.all(r).then(ue).catch(ue)}invalidateQueries(e,t={}){return ie.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=ie.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,s);return s.throwOnError||(a=a.catch(ue)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(ue)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#e.build(this,t);return s.isStaleByTime(Ae(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(ue).catch(ue)}fetchInfiniteQuery(e){return e.behavior=$t(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(ue).catch(ue)}ensureInfiniteQueryData(e){return e.behavior=$t(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return _e.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(Ce(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(r=>{Pe(e,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(e,t){this.#r.set(Ce(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],s={};return t.forEach(r=>{Pe(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=ct(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===Qe&&(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()}},rs=le.createContext(void 0),ft=e=>{const t=le.useContext(rs);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Ir=({client:e,children:t})=>(le.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),n.jsx(rs.Provider,{value:e,children:t})),ns=le.createContext(!1),Tr=()=>le.useContext(ns);ns.Provider;function Rr(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var kr=le.createContext(Rr()),Or=()=>le.useContext(kr),Er=(e,t,s)=>{const r=s?.state.error&&typeof e.throwOnError=="function"?ut(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Pr=e=>{le.useEffect(()=>{e.clearReset()},[e])},Mr=({result:e,errorResetBoundary:t,throwOnError:s,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ut(s,[e.error,r])),Dr=e=>{if(e.suspense){const s=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Fr=(e,t)=>e.isLoading&&e.isFetching&&!t,Ur=(e,t)=>e?.suspense&&t.isPending,qt=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function Lr(e,t,s){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=Tr(),i=Or(),a=ft(),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=a.getQueryCache().get(o.queryHash);process.env.NODE_ENV!=="production"&&(o.queryFn||console.error(`[${o.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),o._optimisticResults=r?"isRestoring":"optimistic",Dr(o),Er(o,i,l),Pr(i);const f=!a.getQueryCache().get(o.queryHash),[d]=le.useState(()=>new t(a,o)),m=d.getOptimisticResult(o),b=!r&&e.subscribed!==!1;if(le.useSyncExternalStore(le.useCallback(y=>{const C=b?d.subscribe(ie.batchCalls(y)):ue;return d.updateResult(),C},[d,b]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),le.useEffect(()=>{d.setOptions(o)},[o,d]),Ur(o,m))throw qt(o,d,i);if(Mr({result:m,errorResetBoundary:i,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw m.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,m),o.experimental_prefetchInRender&&!we&&Fr(m,r)&&(f?qt(o,d,i):l?.promise)?.catch(ue).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?m:d.trackResult(m)}function mt(e,t){return Lr(e,vr)}function $r(e,t){const s=ft(),[r]=le.useState(()=>new jr(s,e));le.useEffect(()=>{r.setOptions(e)},[r,e]);const i=le.useSyncExternalStore(le.useCallback(o=>r.subscribe(ie.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=le.useCallback((o,l)=>{r.mutate(o,l).catch(ue)},[r]);if(i.error&&ut(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function pt(){const{alerts:e}=fe(),t=ft();return $r({mutationFn:s=>e.updateAlertStatus(s),onSuccess:()=>{t.invalidateQueries({queryKey:["alerts","list"]}),t.invalidateQueries({queryKey:["alerts","report"]})}})}function Br(e,t){return e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZone:t})}function qr(e,t){try{const i=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(e).find(o=>o.type==="timeZoneName")?.value;let a;try{const l=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"shortOffset"}).formatToParts(e).find(f=>f.type==="timeZoneName");l?.value&&l.value.startsWith("GMT")&&(a=l.value.replace("GMT",""))}catch{}return{abbr:i,offset:a}}catch{return{}}}function Qr(e){if(!e)return"-";try{const t=new Date(e),s=d=>String(d).padStart(2,"0"),r=s(t.getMonth()+1),i=s(t.getDate()),a=t.getFullYear(),o=s(t.getHours()),l=s(t.getMinutes()),f=s(t.getSeconds());return`${r}/${i}/${a} ${o}:${l}:${f}`}catch{return"-"}}function Je(e){if(!e)return"-";try{return new Date(e).toLocaleString("en-US",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return"-"}}const _r={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},Hr={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"};function is({alerts:e,loading:t=!1,pageSize:s=10,completedStatus:r="Completed",severityOptions:i,anomalyOptions:a,spaceOptions:o,onAlertIdClick:l}){const f=pt(),d=async y=>{try{const C=await f.mutateAsync({alertUniqueId:y.alertId??y.id,alertId:y.id,status:"Reopen",notes:"Reopened",modifiedBy:0});if(C?.responseStatus){const w=C?.data||"Alert reopened successfully.";ne.toast.success(w)}else{const w=C?.errorMessage||"Failed to reopen alert";ne.toast.error(w)}}catch{ne.toast.error("Failed to reopen alert. Please try again.")}},m=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:y=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${_r[y]}`,backgroundColor:Hr[String(y)]},children:y})},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:200,render:y=>Qr(y)},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(y,C)=>n.jsxs("div",{children:[n.jsx("a",{onClick:w=>{w.preventDefault(),l?.(C)},className:"inline-block mb-1 text-blue-600",children:C.alertNumber}),n.jsx("div",{className:"text-black/65",children:y})]})},{title:"",key:"menu",width:60,align:"right",render:(y,C)=>n.jsx(c.Dropdown,{trigger:["click"],menu:{items:[{key:"reopen",label:"Reopen"}],onClick:({key:w})=>{w==="reopen"&&d(C)}},children:n.jsx(c.Button,{type:"text",icon:n.jsx(ke.MoreOutlined,{})})})}],b=(e||[]).filter(y=>(y.statusType||"").toLowerCase()===r.toLowerCase());return n.jsx(lt,{data:b,loading:t,pageSize:s,columns:m,severityOptions:i,anomalyOptions:a,spaceOptions:o,renderActions:void 0,onAlertIdClick:l})}function Gr({size:e=120,time:t,timeZone:s="America/New_York"}){const{hours:r,minutes:i,seconds:a}=h.useMemo(()=>{const b=new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"numeric",second:"numeric",hour12:!1}).formatToParts(t);return{hours:parseInt(b.find(y=>y.type==="hour")?.value||"0",10),minutes:parseInt(b.find(y=>y.type==="minute")?.value||"0",10),seconds:parseInt(b.find(y=>y.type==="second")?.value||"0",10)}},[t,s]),o=a*6,l=i*6+a*.1,f=r%12*30+i*.5,d=e/2;return n.jsxs("div",{className:"relative rounded-full border border-gray-300 bg-white",style:{width:e,height:e},role:"img","aria-label":"Analog Clock",children:[[...Array(12)].map((m,b)=>{const y=b*30,C=6,w=d-4,p=w-C,A=(y-90)*(Math.PI/180),U=d+p*Math.cos(A),L=d+p*Math.sin(A),$=d+w*Math.cos(A),D=d+w*Math.sin(A);return n.jsx("svg",{className:"absolute inset-0",width:e,height:e,children:n.jsx("line",{x1:U,y1:L,x2:$,y2:D,stroke:"#9CA3AF",strokeWidth:b%3===0?2:1,strokeLinecap:"round"})},b)}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${f}deg)`},children:n.jsx("line",{x1:d,y1:d,x2:d,y2:d-e*.25,stroke:"#1F2937",strokeWidth:4,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${l}deg)`},children:n.jsx("line",{x1:d,y1:d,x2:d,y2:d-e*.35,stroke:"#374151",strokeWidth:3,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${o}deg)`},children:n.jsx("line",{x1:d,y1:d+e*.08,x2:d,y2:d-e*.38,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"})}),n.jsx("div",{className:"absolute bg-gray-900 rounded-full",style:{width:8,height:8,left:d-4,top:d-4}})]})}function as({label:e="USA",timeZone:t="America/New_York",updateIntervalMs:s=1e3,className:r}){const[i,a]=h.useState(new Date);h.useEffect(()=>{const d=setInterval(()=>a(new Date),s);return()=>clearInterval(d)},[s]);const o=h.useMemo(()=>Br(i,t),[i,t]),{abbr:l,offset:f}=h.useMemo(()=>qr(i,t),[i,t]);return n.jsxs("div",{className:`flex items-center gap-3 ${r||""}`,children:[n.jsx(Gr,{time:i,timeZone:t,size:80}),n.jsxs("div",{className:"flex flex-col items-baseline gap-1",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[n.jsx("span",{className:"uppercase",children:e}),l&&n.jsx("span",{className:"px-1.5 py-0.5 rounded-md border text-[10px] leading-none text-gray-600 bg-gray-50",children:l}),f&&n.jsx("span",{className:"text-xs text-gray-500",children:f})]}),n.jsx("div",{className:"text-2xl font-semibold text-gray-700 tracking-wide",children:o})]})]})}const Wr=[{SeverityId:1,Code:"LOW",DisplayName:"Low",SortOrder:10,IsActive:!0},{SeverityId:2,Code:"MEDIUM",DisplayName:"Medium",SortOrder:20,IsActive:!0},{SeverityId:3,Code:"HIGH",DisplayName:"High",SortOrder:30,IsActive:!0},{SeverityId:4,Code:"CRITICAL",DisplayName:"Critical",SortOrder:40,IsActive:!0}],Kr=[{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"}],Yr=[{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"}],Re={severities:Wr,rules:Kr,userRoles:Yr},{Text:zr}=c.Typography;function Vr({sortBy:e,onChange:t,showActions:s,onSave:r,onClear:i,saving:a}){return n.jsxs(c.Row,{gutter:[16,16],align:"middle",children:[n.jsx(c.Col,{xs:24,md:8,lg:5,children:n.jsxs(c.Space,{className:"w-full items-center",direction:"horizontal",size:12,children:[n.jsx(zr,{className:"text-gray-600",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:be}=c.Typography;function Jr(e){const{selectedRule:t,setSelectedRule:s,ruleOptions:r,minsOptions:i,roleOptions:a,l1mins:o,setL1mins:l,l1role:f,setL1role:d,l2mins:m,setL2mins:b,l2role:y,setL2role:C,l3mins:w,setL3mins:p,l3role:A,setL3role:U,actions:L,setActions:$,thirdPartyIds:D,setThirdPartyIds:Y,humanLoop:z,setHumanLoop:_,onClear:G,onSave:I,saving:j,onActionTypesLoaded:T}=e,{rules:ee}=fe(),[re,k]=h.useState([]),[v,g]=h.useState([]),[S,u]=h.useState(!1);h.useEffect(()=>{let E=!1;return(async()=>{try{u(!0);const R=await ee.getLookups();if(E||!R||!Array.isArray(R.actionTypes))return;const F=R.actionTypes.map(B=>({label:B.name,value:String(B.actionTypeId)}));k(F),T&&T(R.actionTypes);const q=Array.isArray(R.thirdParties)?R.thirdParties.map(B=>({label:B.thirdPartyName,value:B.thirdPartyId})):[];g(q)}catch(R){console.error("Error loading lookups",R)}finally{E||u(!1)}})(),()=>{E=!0}},[]);const x=typeof o=="number"||typeof f=="number"||typeof m=="number"||typeof y=="number"||typeof w=="number"||typeof A=="number"||Array.isArray(L)&&L.length>0||Array.isArray(D)&&D.length>0||!!z,N=!!t&&x&&!j;return n.jsxs(c.Spin,{spinning:!!j||S,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(be,{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(be,{className:"text-gray-700 font-medium block mb-1",children:"Level 1 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(be,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:o,onChange:l,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:f,onChange:d,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(be,{className:"text-gray-700 font-medium block mb-1",children:"Level 2 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(be,{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:m,onChange:b,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:y,onChange:C,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(be,{className:"text-gray-700 font-medium block mb-1",children:"Level 3 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(be,{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:A,onChange:U,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:5,children:n.jsxs("div",{children:[n.jsx(be,{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:L,onChange:$,options:re})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:3,children:n.jsx("div",{className:"flex items-end h-full",children:n.jsx(c.Checkbox,{checked:z,onChange:E=>_(E.target.checked),children:"Human-In-The-Loop"})})})]}),n.jsxs(c.Row,{gutter:[16,16],align:"bottom",className:"mt-4",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:5,children:n.jsxs("div",{children:[n.jsx(be,{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:D,onChange:Y,options:v})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(c.Button,{onClick:G,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:I,loading:!!j,disabled:!N,children:"Save"})]})})]})]})}function Xr({entries:e,userRoles:t,onEdit:s,loading:r}){const i=new Map(t.map(o=>[o.userRoleId,o.userRoleName])),a=o=>o.map(l=>i.get(l)||String(l)).join(", ");return n.jsx(c.Table,{rowKey:"id",dataSource:e,pagination:!1,loading:r,columns:[{title:"Rule",dataIndex:"ruleOrSeverityLabel",key:"rule"},{title:"Level 1",key:"l1",render:(o,l)=>n.jsxs("span",{children:[l.l1.minutes?`Action taken in (${l.l1.minutes} Mins)`:"No Action taken in 0 Min",l.l1.roles?.length?`, Escalate to (${a(l.l1.roles)})`:""]})},{title:"Level 2",key:"l2",render:(o,l)=>n.jsxs("span",{children:[l.l2.minutes?`Action taken in (${l.l2.minutes} Mins)`:"No Action taken in 0 Min",l.l2.roles?.length?`, Escalate to (${a(l.l2.roles)})`:""]})},{title:"Level 3",key:"l3",render:(o,l)=>n.jsxs("span",{children:[l.l3.minutes?`Action taken in (${l.l3.minutes} Mins)`:"No Action taken in 0 Min",l.l3.roles?.length?`, Escalate to (${a(l.l3.roles)})`:""]})},{title:"Pick Actions",key:"actionsCol",render:(o,l)=>l.actions&&l.actions.length?l.actions.join(", "):"-"},{title:"Notify",key:"notify",render:(o,l)=>l.notify&&l.notify.length?l.notify.join(", "):"-"},{title:"Human-In-The-Loop",key:"humanLoop",render:(o,l)=>l.humanLoop?"Yes":"No"},{title:"Actions",key:"ops",render:(o,l)=>n.jsx(c.Button,{type:"text",onClick:()=>s(l.id),children:n.jsx(ke.EditOutlined,{})})}]})}const{Title:Zr}=c.Typography;function os({userRoles:e,rules:t,rawRules:s}){const{rules:r}=fe(),[i,a]=h.useState(!1),[o,l]=h.useState(s),[f,d]=h.useState({}),m=h.useMemo(()=>e.map(p=>({label:p.userRoleName,value:p.userRoleId})),[e]),b=h.useMemo(()=>(t||[]).map((p,A)=>({key:p.RuleId||p.Name||String(A),ruleName:p.Name||"-",ruleDesc:p.Description||""})),[t]);h.useEffect(()=>{let p=!1;return(async()=>{try{a(!0);const A=await r.getRules();p||(l(Array.isArray(A)?A:[]),d({}))}catch{!p&&Array.isArray(s)&&l(s)}finally{p||a(!1)}})(),()=>{p=!0}},[]),h.useEffect(()=>{!o&&Array.isArray(s)&&l(s)},[s]);const y=h.useMemo(()=>{if(!Array.isArray(o)||!o.length)return{};const p={};for(const A of b){const U=o.find($=>$?.ruleId===A.key||$?.ruleName===A.key||$?.RuleId===A.key||$?.ruleName===A.ruleName||$?.Name===A.ruleName),L=Array.isArray(U?.userRoleIds)?U.userRoleIds:[];L.length&&(p[A.key]=L)}return p},[o,b]),C=()=>{d({})},w=async()=>{try{if(!o||!Array.isArray(o)||Object.keys(f).length===0){ne.toast.info("No changes to save");return}a(!0);const p=Object.entries(f).map(async([A,U])=>{const L=o.find(_=>_?.ruleId===A||_?.ruleName===A||_?.RuleId===A),$=typeof L?.recordId=="number"?L.recordId:void 0;if(!L||typeof $!="number")throw new Error(`Unable to find recordId for rule ${A}`);const D=Array.isArray(U)?U:[],Y=D.map(_=>{const G=e.find(I=>I.userRoleId===_);return{id:_,name:G?.userRoleName??String(_)}}),z={...L,ruleId:A,userRoleIds:D,userRoles:Y,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($,z)});await Promise.all(p),ne.toast.success("Alert assignment saved");try{const A=await r.getRules();l(Array.isArray(A)?A:[]),d({})}catch(A){console.error("Failed to refresh rules after save",A)}}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(Zr,{level:4,className:"!mb-4",children:"Alert Assignment"})}),n.jsx(c.Table,{rowKey:"key",dataSource:b,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,A)=>n.jsx(c.Select,{mode:"multiple",placeholder:"Dropdown with Multi select",className:"w-full",value:f[A.key]??y[A.key]??[],onChange:U=>d(L=>({...L,[A.key]:U})),options:m})}]}),n.jsxs(c.Space,{className:"mt-4",children:[n.jsx(c.Button,{onClick:C,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:Qt}=c.Typography;function ls({severities:e,rules:t,userRoles:s,rawRules:r,onSave:i}){const{rules:a,alerts:o}=fe(),[l,f]=h.useState("By Severity"),[d,m]=h.useState("By severity"),[b,y]=h.useState("By Severity"),[C,w]=h.useState(!1),[p,A]=h.useState(!1),[U,L]=h.useState(!1),[$,D]=h.useState(null),[Y,z]=h.useState("rules"),[_,G]=h.useState(),[I,j]=h.useState();console.log("usr",s);const[T,ee]=h.useState(),[re,k]=h.useState(),[v,g]=h.useState(),[S,u]=h.useState(),[x,N]=h.useState(),[E,R]=h.useState(),[F,q]=h.useState([]),[B,M]=h.useState([]),[W,X]=h.useState(!1),[K,te]=h.useState({}),[se,de]=h.useState({}),[ce,Ge]=h.useState(s||[]),[Ee,Ie]=h.useState([]),[We,oe]=h.useState(!1),[Te,Me]=h.useState(!1),[Ke,gt]=h.useState(r||[]);h.useEffect(()=>{r&&r.length&>(r)},[r]),h.useEffect(()=>{if(!r||!r.length)return;const O=Object.keys(K).length>0||Object.keys(se).length>0;if(Ee.length&&!O)return;const J=r.map((Q,P)=>{const V=t.find(ge=>ge.RuleId===(Q.ruleId||Q.ruleName))?.Name||Q.ruleName||Q.Name||"-",H=Q.escalationSettings||{},Z=typeof H.level1UserRoleId=="number"&&H.level1UserRoleId>0?[H.level1UserRoleId]:[],ye=typeof H.level2UserRoleId=="number"&&H.level2UserRoleId>0?[H.level2UserRoleId]:[],Ye=typeof H.level3UserRoleId=="number"&&H.level3UserRoleId>0?[H.level3UserRoleId]:[],xt=(Array.isArray(H.escalationSettingsActionTypeIds)?H.escalationSettingsActionTypeIds:[]).map(ge=>K[ge]||String(ge)),St=(Array.isArray(H.thirdPartyId)?H.thirdPartyId:[]).map(ge=>se[ge]||String(ge)),ze=typeof H.humanLoop=="boolean"?H.humanLoop:null;return{id:String(Q.ruleId||Q.ruleName||P),ruleOrSeverityLabel:V,l1:{minutes:H.level1PostAssistTime??void 0,roles:Z},l2:{minutes:H.level2PostAssistTime??void 0,roles:ye},l3:{minutes:H.level3PostAssistTime??void 0,roles:Ye},actions:xt,notify:St,humanLoop:ze}});Ie(J)},[r,t,K,se]);const fs=h.useMemo(()=>e.map(O=>({label:O.DisplayName,value:O.SeverityId})),[e]),ms=h.useMemo(()=>t.map(O=>({label:O.Name,value:O.RuleId})),[t]),ps=h.useMemo(()=>ce.map(O=>({label:O.userRoleName,value:O.userRoleId})),[ce]),ys=h.useMemo(()=>[1,3,5,10,15,20,30,45,60].map(O=>({label:`${O}`,value:O})),[]);h.useEffect(()=>{let O=!1;async function J(){try{L(!0),D(null);const Q=await o.getAdminSettings();if(!O&&Q){const P=Gt(Q.sortBy);f(P),y(P),w(!1)}}catch(Q){if(!O){const P=Q instanceof Error?Q.message:"Failed to load admin settings";D(P)}}finally{O||L(!1)}}return J(),()=>{O=!0}},[]),h.useEffect(()=>{if(!I)return;const O=V=>{const H=Number(V);return!isNaN(H)&&H>0?H:void 0},J=V=>{const H=Number(V);return!isNaN(H)&&H>0?H:void 0},P=(Ke||[]).find(V=>V?.ruleId===I||V?.ruleName===I||V?.RuleId===I)?.escalationSettings;if(P&&typeof P=="object"){ee(J(P.level1PostAssistTime)),k(O(P.level1UserRoleId)),g(J(P.level2PostAssistTime)),u(O(P.level2UserRoleId)),N(J(P.level3PostAssistTime)),R(O(P.level3UserRoleId));const V=Array.isArray(P.escalationSettingsActionTypeIds)?P.escalationSettingsActionTypeIds:[];q(V.map(H=>String(H))),M(Array.isArray(P.thirdPartyId)?P.thirdPartyId:[]),X(!!P.humanLoop)}},[Y,I,Ke]);const gs=async()=>{try{Me(!0);const O=await a.getRules(),J=Array.isArray(O)?O:Array.isArray(O?.data)?O.data:[];gt(J);const Q=J.map((P,V)=>{const H=t.find(Ne=>Ne.RuleId===(P.ruleId||P.ruleName))?.Name||P.ruleName||P.Name||"-",Z=P.escalationSettings||{},ye=typeof Z.level1UserRoleId=="number"&&Z.level1UserRoleId>0?[Z.level1UserRoleId]:[],Ye=typeof Z.level2UserRoleId=="number"&&Z.level2UserRoleId>0?[Z.level2UserRoleId]:[],vt=typeof Z.level3UserRoleId=="number"&&Z.level3UserRoleId>0?[Z.level3UserRoleId]:[],bt=(Array.isArray(Z.escalationSettingsActionTypeIds)?Z.escalationSettingsActionTypeIds:[]).map(Ne=>K[Ne]||String(Ne)),ze=(Array.isArray(Z.thirdPartyId)?Z.thirdPartyId:[]).map(Ne=>se[Ne]||String(Ne)),ge=typeof Z.humanLoop=="boolean"?Z.humanLoop:null;return{id:String(P.ruleId||P.ruleName||V),ruleOrSeverityLabel:H,l1:{minutes:Z.level1PostAssistTime??void 0,roles:ye},l2:{minutes:Z.level2PostAssistTime??void 0,roles:Ye},l3:{minutes:Z.level3PostAssistTime??void 0,roles:vt},actions:bt,notify:ze,humanLoop:ge}});Ie(Q)}catch(O){console.error("Failed to refetch entries",O)}finally{Me(!1)}};h.useEffect(()=>{let O=!1;return(async()=>{try{const J=await a.getLookups();if(O||!J)return;const Q={};if(Array.isArray(J.thirdParties))for(const V of J.thirdParties)typeof V.thirdPartyId=="number"&&(Q[V.thirdPartyId]=V.thirdPartyName);de(Q);const P=Array.isArray(J.userRoles)?J.userRoles.map(V=>({userRoleId:V.userRoleId??V.id,userRoleName:V.userRoleName??V.name})):[];O||Ge(P.length?P:s||[])}catch(J){console.error("Error loading lookups",J)}})(),()=>{O=!0}},[]);const vs=async()=>{A(!0);try{const O=await o.setAdminSettings({sortBy:l,groupBy:"string"});O?.responseStatus&&O?.data&&ne.toast.success(O.data),y(l),w(!1)}catch(O){console.error("Error saving admin settings",O)}finally{A(!1)}},xs=()=>{f(b),w(!1)},bs=async()=>{oe(!0),i?.({ruleId:I,levels:[{minutes:T,role:re},{minutes:v,role:S},{minutes:x,role:E}],actions:F,thirdPartyIds:B,humanLoop:W});try{if(I){const Q=Array.isArray(F)?F.map(ye=>Number(ye)):[],P=(Ke||[]).find(ye=>ye?.ruleId===I||ye?.ruleName===I||ye?.RuleId===I),V=typeof P?.recordId=="number"?P.recordId:void 0;if(!P||typeof V!="number"){ne.toast.error("Unable to find rule recordId for update");return}const H={...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:re??0,level1PostAssistTime:T??0,level2UserRoleId:S??0,level2PostAssistTime:v??0,level3UserRoleId:E??0,level3PostAssistTime:x??0,escalationSettingsActionTypeIds:Q,thirdPartyId:Array.isArray(B)?B:[],humanLoop:W}},Z=await a.updateRule(V,H);if(Z?.responseStatus||Z?.ok||Z){ne.toast.success("Escalation settings saved"),await gs(),j(void 0),ee(void 0),k(void 0),g(void 0),u(void 0),N(void 0),R(void 0),q([]),M([]),X(!1);return}}}catch(Q){console.error("Error saving escalation settings",Q)}finally{oe(!1)}const J=t.find(Q=>Q.RuleId===I)?.Name||"-";Ie(Q=>[...Q,{id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ruleOrSeverityLabel:J,l1:{minutes:T,roles:re?[re]:[]},l2:{minutes:v,roles:S?[S]:[]},l3:{minutes:x,roles:E?[E]:[]},actions:(Array.isArray(F)?F:[]).map(P=>{const V=Number(P);return K[V]||String(P)}),notify:(Array.isArray(B)?B:[]).map(P=>se[P]||String(P)),humanLoop:!!W}])},Ss=()=>{f("By Severity"),m("By severity"),z("rules"),G(void 0),j(void 0),ee(void 0),k(void 0),g(void 0),u(void 0),N(void 0),R(void 0),q([]),M([]),X(!1)};return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"mb-6",children:[n.jsx(Qt,{level:4,className:"!mb-2",children:"Admin Settings"}),n.jsxs(c.Spin,{spinning:U,children:[$?n.jsxs("div",{className:"text-sm text-red-600 mb-2",children:["Failed to load settings: ",$]}):null,n.jsx(Vr,{sortBy:l,groupBy:d,onChange:O=>{O.sortBy&&(f(O.sortBy),w(!0)),O.groupBy&&(m(O.groupBy),w(!0))},showActions:C,onSave:vs,onClear:xs,saving:p})]})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsxs("div",{children:[n.jsx(Qt,{level:4,className:"!mb-4",children:"Escalation Settings"}),n.jsx(Jr,{escBasis:Y,setEscBasis:z,selectedSeverity:_,setSelectedSeverity:G,selectedRule:I,setSelectedRule:j,severityOptions:fs,ruleOptions:ms,minsOptions:ys,roleOptions:ps,l1mins:T,setL1mins:ee,l1role:re,setL1role:k,l2mins:v,setL2mins:g,l2role:S,setL2role:u,l3mins:x,setL3mins:N,l3role:E,setL3role:R,actions:F,setActions:q,thirdPartyIds:B,setThirdPartyIds:M,humanLoop:W,setHumanLoop:X,onClear:Ss,onSave:bs,saving:We,onActionTypesLoaded:O=>{const J={};for(const Q of O)typeof Q.actionTypeId=="number"&&(J[Q.actionTypeId]=Q.name);te(J)}})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(Xr,{entries:Ee,userRoles:ce,loading:Te,onEdit:O=>{z("rules");const J=Ee.find(P=>P.id===O),Q=t.find(P=>P.RuleId===O)||(J?t.find(P=>P.Name===J.ruleOrSeverityLabel):void 0);j(Q?Q.RuleId:O)}}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(os,{userRoles:ce,rules:t,rawRules:r}),n.jsx(c.Divider,{})]})}const{Title:_t,Text:$e}=c.Typography;function cs({severities:e,rules:t,onSave:s,onCancel:r}){const{rules:i,alerts:a}=fe(),o=[{label:"By Severity",value:"By Severity"},{label:"By Created Date",value:"By Created Date"}],[l,f]=h.useState("By Severity"),[d,m]=h.useState(new Set),[b,y]=h.useState(null),[C,w]=h.useState(null),[p,A]=h.useState({inApp:!1,sms:!1,email:!1}),[U,L]=h.useState([]),[$,D]=h.useState(!0),[Y,z]=h.useState(!1);h.useEffect(()=>{let I=!1;return(async()=>{try{const j=await a.getPreferenceSettings();if(I||!j)return;A({inApp:!!j.inApp,sms:!!j.sms,email:!!j.email});const T=Gt(j.sortBy);f(T==="By Created Date"?"By Created Date":"By Severity"),y(It(j.doNotDisturbStart)),w(It(j.doNotDisturbEnd)),Array.isArray(j.anomalyIds)&&m(new Set(j.anomalyIds.map(ee=>String(ee))))}catch(j){console.error("Error in loading my preferences: ",j)}})(),()=>{I=!0}},[]),h.useEffect(()=>{let I=!1;return(async()=>{try{D(!0);const j=await i.getLookups();if(I||!j)return;const T=Array.isArray(j.anomalies)?j.anomalies:[];L(T)}catch(j){console.error("Failed to load anomalies lookups",j)}finally{I||D(!1)}})(),()=>{I=!0}},[]);const _=I=>{m(j=>{const T=new Set(j);return T.has(I)?T.delete(I):T.add(I),T})},G=async()=>{s?.({sortBy:l,subscribedRuleIds:Array.from(d),dnd:{from:b,to:C},channels:p});try{z(!0);const I=b?b.format?.("HH:mm:ss")??"00:00:00":"00:00:00",j=C?C.format?.("HH:mm:ss")??"00:00:00":"00:00:00",T=Array.from(d).map(re=>Number(re)).filter(re=>Number.isFinite(re)),ee=await a.setPreferenceSettings({anomalyIds:T,doNotDisturbStart:I,doNotDisturbEnd:j,inApp:!!p.inApp,sms:!!p.sms,email:!!p.email,sortBy:l});console.log("resp",ee),ee?.responseStatus&&ne.toast.success(ee?.data||"Preferences updated successfully.")}catch(I){console.error("Error in saving my preferences: ",I)}finally{z(!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($e,{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(_t,{level:5,className:"!mb-2",children:"Anomalies"}),$?n.jsx("div",{className:"py-4",children:n.jsx(c.Spin,{})}):n.jsx(c.Space,{direction:"vertical",size:10,className:"w-full",children:(Array.isArray(U)?U:[]).map(I=>{const j=String(I.recordId),T=I.anomalyName;return n.jsx(c.Checkbox,{checked:d.has(j),onChange:()=>_(j),children:T},j)})})]}),n.jsxs("div",{className:"mb-4",children:[n.jsx(_t,{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($e,{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($e,{children:"From"}),n.jsx(c.TimePicker,{value:b,onChange:I=>y(I),format:"HH:mm"})]}),n.jsxs(c.Space,{direction:"horizontal",size:8,className:"items-center",children:[n.jsx($e,{children:"To"}),n.jsx(c.TimePicker,{value:C,onChange:I=>w(I),format:"HH:mm"})]})]})]})})}),n.jsxs(c.Row,{gutter:[24,12],children:[n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.inApp,onChange:I=>A({...p,inApp:I.target.checked}),children:"In-app"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.sms,onChange:I=>A({...p,sms:I.target.checked}),children:"SMS"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.email,onChange:I=>A({...p,email:I.target.checked}),children:"Email"})})]})]}),n.jsx(c.Divider,{}),n.jsxs(c.Space,{className:"gap-3",children:[n.jsx(c.Button,{onClick:r,disabled:Y,children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:G,loading:Y,children:"Save"})]})]})}function us({severities:e,rules:t,userRoles:s,rawRules:r}){const[i,a]=h.useState("global");return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"inline-flex rounded-xl overflow-hidden border border-gray-200 mb-4",children:[n.jsx("button",{onClick:()=>a("global"),className:`px-5 py-2 text-base font-medium outline-none ${i==="global"?" bg-black text-white":" bg-white text-black"}`,style:{border:"0"},children:"Global Settings"}),n.jsx("button",{onClick:()=>a("prefs"),className:`px-5 py-2 text-base font-medium outline-none ${i==="prefs"?"bg-black text-white":"bg-white"}`,children:"My Preferences"})]}),i==="global"?n.jsx(ls,{severities:e,rules:t,userRoles:s,rawRules:r}):n.jsx(cs,{severities:e,rules:t})]})}const en="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAIZSURBVHgBnZW/b9NAFMe/z3H6i1ZNJUBFQsL/QQkLCFBtRhhKF1ibhBmpXbtgFlYqsTG0gRGWwgAjMb8EYmjYGN0pCCrVVaX+SBxf37PiqHWcOu5Xsux79+6j77vz3RH66IbdsDTQPCFngmBwqMCPBwVXoe204Fd/2ZfrSWMpHrDshtGCvsY9FlKkFNYD+Es/7EtuX+itp1sLnLrScTWoPMYsfnty/lUPtAOs4syiUgQOoWHJpG9kdBiX11Z+UaZCk1YT+vOzACuzYxgf7hZbyBGvhTi9af+7SkQbyKi7M8N4ZJ5D+eU2dg9UN07KvyNOS8io6UkNFXMMj1/vnACKAuTmNXZpIqME+LF+iIbX7ukjkClODWTQw+ujuGYMYfXzXnICbxSBDrxAUvYDhkrZp6ggUC8+sDI7mpj9YmESb3/uJ5Z9TJ5A3eORvzsBpgs6lufGT2TKPNY3fbxh6Knis0FTSjnx+LP3u5DJicDi/t7MCFadPaRJQTl02/5vKcKnpITluYkwrWjksebs48Pvg3SoUkXtq32hxt+1pITI8Zc/zcGACN59ty/WdWnklV5ukZ+49wU8MUJIF3mBGlqUr3Dv1+wpl20v9UuP75pElyrgc3XK7UJFbLvK4DJiv9ggDmWcjO9G4imWvW00yV/hjvtpOFnpQOVLkcO+0EhyevGrROG1ol1hREFc8ZGxyddIje+v9c4i9+gI5z7MozLxclgAAAAASUVORK5CYII=",tn="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAKeSURBVHgBjVVdbtpAEJ5ZmygPfTBSaVWpUt0bwFuURgJOUG5QeoLACbw+QeAEwA3SGxgJokh9CDeI+xSpTRU/Imw8nbFZx6QQGAl5d2fm229+dkDYI2f6oaUAOwhWExBcPnL4FwFBSLCexpCMf+qPi12++PKgpR/cGOwRa1pwQIjgOoWkf6s/hOVzVd588R+/xWjf5YAY8Y0+ErQrZFfnXg3lK3uGm7A+RISOxfbit5NprqBxxgBoeEIVHehqtI9lSz+5McaaITaA2J17bycFaBayMOS8IaT+zHuv4Ui58P9oAvB4Ga0paUgqbFGswL5idIcIx3P9DCiXrQB7iJawcTiCkMMIUlj7Jo8zr6Yv/EfRXXIqRnzUxnP9u46Id8Q5Sslq3+pqWErHAPKqvxROC/ZMuJwKJ8bkPouUkrYUqgt5IgMDKAxfAYT8nAZnmR2A5J47YSjrFKyOYpZN2SiIJ8YjRqVfASyAFVg9s2F2gXwRsClMXdnYcFpq5PyiQ8KEilaywc79+aEow2i7fdCF46SIpuTvCGi2kWSXjCM4QqS4Zl3yjwQ0UySwrBfGRJNjQKW4ZrmEpL45CxUDTGWdgmoZgxOoDA6zxYgr7ZudhWk3x6Sp4kl0nZmgujQhcH5Cvqy/Hxi5hdL+dgsWxR2rma4FkLeDw+PMM243+t2YB0jDDI9nMBquyWqI3tjmLYguQfqDzxebty/DIcnePr9jfePVfDhSzv2/Hs8LAY3kMmFfTCl+rl3uu1GWF6Jx+X3vkpa+58jeeNyXvY3Pd8N+a0hvgK9ge3hMTmG5CPTnSICWcFpXaDfZUcAck99yOnZM/id3hcmAFV/hgEilU6p0TcH2gpZYS98xc/kXUJ8YImPFzfeLh0cgXbMp8n/yD3ySPZSK0MWKAAAAAElFTkSuQmCC";function sn(e){const t=(e.status||"").toLowerCase()==="completed"?n.jsx("img",{src:en,alt:"completed",style:{width:20,height:20}}):n.jsx("img",{src:tn,alt:"pending",style:{width:20,height:20}});return{title:n.jsxs("div",{className:"flex flex-col gap-0 min-w-0",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("span",{className:"block text-sm break-words mb-1 overflow-visible whitespace-normal",children:n.jsx("b",{children:e.title})}),e.description?n.jsx("span",{className:"text-gray-500 text-xs",children:e.description}):null]}),e.timestamp?n.jsx("span",{className:"text-gray-500 text-xs",children:e.timestamp}):null]}),icon:t,description:null}}function rn({data:e}){return n.jsx("div",{className:"w-full",children:n.jsx(c.Tabs,{type:"card",items:[{key:"action",label:"Action Taken",children:n.jsxs("div",{className:"w-full",children:[n.jsx(c.Card,{className:"mb-4 rounded-md",bordered:!0,children:n.jsxs("div",{className:"grid grid-cols-4 gap-6 text-xs",children:[n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Alert ID"}),n.jsx("span",{className:"text-black",children:e.summary.alertNumber})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Incident ID"}),n.jsx("span",{className:"text-black",children:e.summary.incidentId})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Severity"}),n.jsx("span",{className:"text-black",children:e.summary.severity})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Location"}),n.jsx("span",{className:"text-black",children:e.summary.location})]})]})}),n.jsxs(c.Card,{className:"rounded-md",bordered:!0,children:[n.jsx("div",{className:"flex items-center justify-between",children:n.jsx("h4",{className:"text-sm text-black font-medium",children:"Response Timeline/ Audit trail/log"})}),n.jsx("div",{className:"mt-2",children:n.jsx(c.Steps,{direction:"vertical",size:"small",current:1,items:(e.timeline||[]).map(sn)})})]})]})},{key:"notification",label:"Notification Sent",children:n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(e.notifications||[]).map((t,s)=>n.jsxs(c.Card,{className:"rounded-md p-4",bordered:!0,children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("h4",{className:"text-sm text-black font-medium",children:t.channelLabel}),n.jsx("span",{className:"text-xs text-gray-500 mt-1",children:t.sentAt})]}),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)=>n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("span",{className:"text-black",children:r.name}),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."})]})}]})})}function nn(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 an(e){const t=(e?.mediaType||e?.type||"").toString().toLowerCase();return t==="video"||t==="mp4"?!0:nn(e?.mediaUrl||e)}function Xe(e){const t=e;return t?Array.isArray(t)?t:[t]:[]}const on={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},ln={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},cn=({isModalOpen:e,handleModalClose:t,selectedRow:s,fetchAlertLogs:r,alertStatusList:i=[],alertStatusLoading:a=!1,initialTab:o="details"})=>{const[l,f]=h.useState(),[d,m]=h.useState(""),[b,y]=h.useState(!1),C=h.useRef(null),[w,p]=h.useState("details"),[A,U]=h.useState(void 0),[L,$]=h.useState(!1),D=pt(),{alerts:Y,config:z}=fe(),_=z?.tenant==="schools",G=s?.originalData||{},{eventName:I,alertId:j,timestamp:T,description:ee,spaceName:re,assignTeam:k,priority:v,statusType:g,id:S,alertDetails:u,statusHistory:x,mediaDetails:N,alertNumber:E}=G,R=!_&&typeof G?.anomalyName=="string"&&String(G?.anomalyName||"").toLowerCase().includes("elopement");h.useEffect(()=>{const M=S;if(w!=="track"||!M)return;let W=!1;return(async()=>{try{const X=await Y.getAlertNotifications(M);if(W)return;const K=new Map;(X||[]).forEach(se=>{const de=String(se?.notificationType||"Unknown"),ce=K.get(de)||[];ce.push(se),K.set(de,ce)});const te=Array.from(K.entries()).map(([se,de])=>{const ce=de.map(oe=>{const Te=String(oe?.messageStatus||"").toLowerCase(),Me=Te==="delivered"?"Delivered":Te==="failed"?"Failed":"Queued";return{name:oe?.receipientName||oe?.recipientName||"-",role:oe?.receipientRoleName||"",phone:oe?.receipentPhoneNumber||oe?.recipientPhoneNumber||oe?.receipientEmail||oe?.recipientEmail||"",status:Me}}),Ge=ce.filter(oe=>oe.status==="Delivered").length,Ee=de.map(oe=>oe?.sentAt).filter(Boolean).sort((oe,Te)=>new Date(Te).getTime()-new Date(oe).getTime())[0],Ie=de[0]||{},We=[Ie?.severityName,Ie?.anomalyName].filter(Boolean).join(" - ")||`${se} Notification`;return{channelLabel:`${se} Notification`,sentAt:Ee||"",messageTitle:We,messageBody:"",total:ce.length,delivered:Ge,recipients:ce}});U(te)}catch{U(void 0)}})(),()=>{W=!0}},[w,S]),h.useEffect(()=>{e&&p(o)},[e,o]);const F=(i||[]).map(M=>({value:M.value,label:M.statusName})),q=async()=>{try{y(!0);const M={alertUniqueId:j,alertId:S,status:l!==void 0?String(l):void 0,notes:d.trim(),modifiedBy:0},W=await D.mutateAsync(M);if(W?.responseStatus){const X=W?.data||"Alert updated successfully.";ne.toast.success(X,{autoClose:1500,onClose:()=>{r(),t()}}),f(void 0),m("")}else{const X=W?.errorMessage||"Failed to update alert status";ne.toast.error(X)}}catch(M){console.error("Error updating alert status:",M),ne.toast.error("Failed to update alert status. Please try again.")}finally{y(!1)}},B=async()=>{try{if(!S){ne.toast.error("Alert ID is missing.");return}$(!0);const M=S;if(!Y.notifyFamilyMembers){ne.toast.error("Notify Family is not supported.");return}const W=await Y.notifyFamilyMembers(M);if(W?.responseStatus){const X=W?.data||"Alert Notifications sent to Family Members.";ne.toast.success(X)}else{const X=W?.errorMessage||"Failed to send notifications.";ne.toast.error(X)}}catch(M){console.error("Error notifying family members:",M),ne.toast.error("Failed to send notifications. Please try again.")}finally{$(!1)}};return n.jsx(c.Modal,{open:e,onCancel:t,width:1e3,footer:w==="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:q,loading:b,children:b?"Saving...":"Save Changes"})]}):null,children:s&&n.jsx(c.Tabs,{activeKey:w,onChange:M=>p(M),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:I||"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: ",Je(T)]}),n.jsxs("div",{className:"font-sm text-gray-500",children:[n.jsx("b",{className:"text-black text-sm/6",children:"Description:"})," ",ee||"No description available"]}),re&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Space: ",re]}),k&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Assigned to: ",k]}),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 ${on[String(v)]||"#DFE4EA"}`,backgroundColor:ln[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(g||"").toLowerCase()==="completed"?{background:"#E7F6EC",border:"0.68px solid var(--Green, #34C759)"}:{background:"#E0EDFF",border:"1px solid var(--Grays-Gray-4, #D1D1D6)"},children:["Status: ",g||"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:M=>f(M),value:l,options:F,loading:a})}),n.jsxs("div",{className:"flex flex-col gap-2 mt-3",children:[n.jsx("label",{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:M=>m(M.target.value)})]}),R&&n.jsxs("div",{className:"border border-[#DFE4EA] rounded-md px-4 py-2 flex flex-row justify-between items-center mt-4 mb-8",children:[n.jsx("label",{className:"text-xs font-medium",children:"Alert notification will be sent to all Family Members."}),n.jsx(c.Button,{loading:L,onClick:B,disabled:L,className:"bg-black text-white rounded-md px-4 py-2 text-xs disabled:opacity-60 disabled:cursor-not-allowed",children:"Notify Family"})]})]})})]}),n.jsx("div",{className:"flex flex-col gap-4",children:n.jsxs("div",{className:"w-full mt-1",children:[n.jsxs("div",{className:"w-full flex items-center justify-between",children:[n.jsx("h3",{className:"text-black font-bold text-sm",children:"Camera Footage"}),Xe(N).length?n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>C.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(ke.LeftOutlined,{style:{fontSize:12}})}),n.jsx("button",{type:"button",onClick:()=>C.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(ke.RightOutlined,{style:{fontSize:12}})})]}):null]}),Xe(N).length?n.jsx("div",{className:"w-full",children:n.jsx(c.Carousel,{ref:C,dots:!0,className:"w-full",children:Xe(N).map((M,W)=>n.jsxs("div",{className:"flex justify-center items-center",children:[an(M)?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:M.mediaUrl||M}),"Your browser does not support the video tag."]}):n.jsx("img",{src:M.mediaUrl||M,alt:M.caption||`media-${W}`,className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg"}),M.caption&&n.jsx("p",{className:"text-xs text-gray-500 mt-1",children:M.caption})]},W))})}):null]})})]})},{key:"track",label:"Track Incident",children:(()=>{const M={alertId:j??S??"",incidentId:"-",severity:v||"",location:re||"",alertNumber:E??""},W=x&&x.length?x.map(K=>({status:(K?.status||K?.eventStatus||"").toLowerCase()==="completed"?"Completed":"Inprogress",title:K?.status||K?.eventStatus||"Status Update",description:K?.description||K?.actionNotes||"",timestamp:K?.createdDate?`${Je(K?.createdDate)}`:K?.timestamp?`${Je(K?.timestamp)}`:""})):[],X={summary:M,timeline:W,notifications:A??[]};return n.jsx(rn,{data:X})})()}]})})};function ds(){const{alerts:e}=fe(),t=mt({queryKey:["alerts","statusList"],queryFn:()=>e.getAlertStatusList(),staleTime:5*6e4});return{list:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function yt({alerts:e,loading:t=!1,columns:s,onRefetch:r}){const[i,a]=h.useState(!1),[o,l]=h.useState(null),[f,d]=h.useState("details"),{list:m,loading:b}=ds();function y(p,A){l(p),d(A?.tab??"details"),a(!0)}function C(){a(!1)}const w=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(as,{label:"USA",timeZone:"America/New_York"})]}),n.jsx(c.Tabs,{defaultActiveKey:"active",className:"w-full",tabBarStyle:{fontSize:"medium"},onChange:p=>{p==="active"&&r?.()},items:[{key:"active",label:"Active",children:n.jsx(lt,{data:e,loading:t,pageSize:10,columns:s||[],onAlertIdClick:y,onRefetch:r})},{key:"archived",label:"Archived",children:n.jsx(is,{alerts:e,loading:t,columns:s||[],onAlertIdClick:y})},{key:"settings",label:"Settings",children:n.jsx(un,{})}]}),n.jsx(cn,{isModalOpen:i,handleModalClose:C,selectedRow:w,fetchAlertLogs:()=>{},alertStatusList:m,alertStatusLoading:b,initialTab:f})]})}function un(){const[e,t]=h.useState([]),[s,r]=h.useState([]),[i,a]=h.useState([]),{rules:o}=fe();return h.useEffect(()=>{let l=!0;return(async()=>{try{const f=await o.getRules();if(!l)return;a(Array.isArray(f)?f:[]);const d=(f||[]).map((m,b)=>({RuleId:m.ruleId||m.ruleName||String(b),Name:m.ruleName||m.Name||"-",Description:m.ruleDesc||m.Description||"",SeverityId:0}));t(d.length?d:Re.rules);try{const m=await o.getLookups(),b=Array.isArray(m?.userRoles)?m.userRoles.map(y=>({userRoleId:y.userRoleId??y.id,userRoleName:y.userRoleName??y.name})):[];r(b.length?b:Re.userRoles)}catch{r(Re.userRoles)}}catch{t(Re.rules),r(Re.userRoles)}})(),()=>{l=!1}},[]),n.jsx(us,{severities:Re.severities,rules:e,userRoles:s,rawRules:i})}function hs(){const{alerts:e}=fe(),t=mt({queryKey:["alerts","list"],queryFn:()=>e.listAlerts(),staleTime:3e4});return{alerts:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function dn(e){const{alerts:t,loading:s,refetch:r}=hs();return n.jsx(yt,{alerts:t,loading:s,columns:e.columns,onRefetch:r})}function hn({tenant:e,apiDomain:t,rulesDomain:s,headers:r,alerts:i,loading:a,columns:o}){const[l]=h.useState(()=>new Cr),f=h.useMemo(()=>({alertsBaseUrl:t,rulesBaseUrl:s||t,headers:r||void 0}),[t,s,r]);return n.jsx(Ir,{client:l,children:n.jsx(Yt,{tenant:e,override:f,children:Array.isArray(i)?n.jsx(yt,{alerts:i,loading:!!a,columns:o}):n.jsx(dn,{columns:o})})})}function fn(e){const{alerts:t}=fe(),s=mt({queryKey:["alerts","report",e],queryFn:()=>t.getAlertsReport(e),staleTime:6e4});return{data:s.data??[],loading:s.isLoading,error:s.error,refetch:s.refetch}}const mn=[{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=os;exports.AlertConsole=yt;exports.AlertConsoleWidget=hn;exports.AlertsTable=lt;exports.ApiProvider=Yt;exports.ArchivedTable=is;exports.Clock=as;exports.DataTable=zt;exports.MyPreferencesPanel=cs;exports.SettingsPanel=ls;exports.SettingsTabs=us;exports.exampleAlertColumns=mn;exports.useAlertStatusList=ds;exports.useAlerts=hs;exports.useAlertsReport=fn;exports.useApi=fe;exports.useUpdateAlertStatus=pt;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),h=require("react"),c=require("antd"),Oe=require("@ant-design/icons"),ne=require("react-toastify");function As(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const s in e)if(s!=="default"){const r=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,r.get?r:{enumerable:!0,get:()=>e[s]})}}return t.default=e,Object.freeze(t)}const le=As(h),Ns="#FF3B30",ws="#FF9500",js="#FFCC00",Cs="#34C759",Fe={critical:Ns,high:ws,medium:js,low:Cs},At={Critical:Fe.critical,High:Fe.high,Medium:Fe.medium,Low:Fe.low};function Is(e){return At[e]||At.Low}function Nt(e){if(!e||typeof e!="string")return 0;const t=e.trim().split(":");if(t.length!==3)return 0;const[s,r,i]=t,a=Number.parseInt(s,10),o=Number.parseInt(r,10),l=Number.parseFloat(i||"0"),f=Number.isFinite(a)?a:0,d=Number.isFinite(o)?o:0,m=Number.isFinite(l)?l:0;return f*3600+d*60+m}function Ve(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 Ht="",Ts=Ht,Rs="",ks="",wt={snl:{alerts:Ht,rules:Ts},schools:{alerts:Rs,rules:ks}};function me(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Os(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function Ue(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 pe(e,t){const s={...t.headers,...Os()},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 Es(e){console.log("baseurl",e);const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=me(e.baseUrl,"/api/Alert"),r=await pe(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertStatusList(){const s=me(e.baseUrl,"/api/Alert/AlertStatusList"),r=await pe(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=me(e.baseUrl,"/Alerts/GetAlertsReport"),i=Ue(r,s),a=await pe(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=me(e.baseUrl,"/api/Alert/status");return pe(r,{method:"PUT",headers:t,body:JSON.stringify(s??{})})},async getAdminSettings(){const s=me(e.baseUrl,"/api/Alert/GetAdminSettings"),r=await pe(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=me(e.baseUrl,"/api/Alert/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??"",groupBy:s?.groupBy??null};return pe(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=me(e.baseUrl,"/api/Alert/GetPreferenceSettings"),r=await pe(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=me(e.baseUrl,"/api/Alert/SetPreferenceSettings"),i=await pe(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=me(e.baseUrl,"/api/Alert/GetNotifications"),i=Ue(r,{alertId:s}),a=await pe(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=me(e.baseUrl,"/api/Alert/NotificationToFamilyMembers"),i=Ue(r,{alertId:s});return pe(i,{method:"POST",headers:t})},async sendSMSorEmailNotifications(s,r,i){const a=me(e.baseUrl,"/api/Alert/SendSMSorEmailNotifications"),o=Ue(a,{alertId:s,isEmail:r,isSMS:i});return pe(o,{method:"POST",headers:t})}}}function jt(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Ps(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}async function Le(e,t){const s={...t.headers,...Ps()},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 Ms(e){const t={"Content-Type":"application/json",...e.headers||{}},s=jt(e.baseUrl,"/api/Rules"),r=jt(e.baseUrl,"/api/Rules/lookups");return{async getRules(){const i=await Le(s,{method:"GET",headers:t});return Array.isArray(i)?i:[]},async setEscalationSettings(i){return Le(s,{method:"POST",headers:t,body:JSON.stringify(i??{})})},async getLookups(){return Le(r,{method:"GET",headers:t})},async updateRule(i,a){const o=`${s}/${i}`;return Le(o,{method:"PUT",headers:t,body:JSON.stringify(a??{})})}}}function Ds(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qe={exports:{}},Fs=qe.exports,Ct;function Us(){return Ct||(Ct=1,(function(e,t){(function(s,r){e.exports=r()})(Fs,(function(){var s=1e3,r=6e4,i=36e5,a="millisecond",o="second",l="minute",f="hour",d="day",m="week",b="month",y="quarter",C="year",j="date",p="Invalid Date",A=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,U=/\[([^\]]+)]|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,L={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 v=["th","st","nd","rd"],g=k%100;return"["+k+(v[(g-20)%10]||v[g]||v[0])+"]"}},$=function(k,v,g){var S=String(k);return!S||S.length>=v?k:""+Array(v+1-S.length).join(g)+k},D={s:$,z:function(k){var v=-k.utcOffset(),g=Math.abs(v),S=Math.floor(g/60),u=g%60;return(v<=0?"+":"-")+$(S,2,"0")+":"+$(u,2,"0")},m:function k(v,g){if(v.date()<g.date())return-k(g,v);var S=12*(g.year()-v.year())+(g.month()-v.month()),u=v.clone().add(S,b),x=g-u<0,N=v.clone().add(S+(x?-1:1),b);return+(-(S+(g-u)/(x?u-N:N-u))||0)},a:function(k){return k<0?Math.ceil(k)||0:Math.floor(k)},p:function(k){return{M:b,y:C,w:m,d,D:j,h:f,m:l,s:o,ms:a,Q:y}[k]||String(k||"").toLowerCase().replace(/s$/,"")},u:function(k){return k===void 0}},Y="en",z={};z[Y]=L;var _="$isDayjsObject",G=function(k){return k instanceof ee||!(!k||!k[_])},I=function k(v,g,S){var u;if(!v)return Y;if(typeof v=="string"){var x=v.toLowerCase();z[x]&&(u=x),g&&(z[x]=g,u=x);var N=v.split("-");if(!u&&N.length>1)return k(N[0])}else{var E=v.name;z[E]=v,u=E}return!S&&u&&(Y=u),u||!S&&Y},w=function(k,v){if(G(k))return k.clone();var g=typeof v=="object"?v:{};return g.date=k,g.args=arguments,new ee(g)},T=D;T.l=I,T.i=G,T.w=function(k,v){return w(k,{locale:v.$L,utc:v.$u,x:v.$x,$offset:v.$offset})};var ee=(function(){function k(g){this.$L=I(g.locale,null,!0),this.parse(g),this.$x=this.$x||g.x||{},this[_]=!0}var v=k.prototype;return v.parse=function(g){this.$d=(function(S){var u=S.date,x=S.utc;if(u===null)return new Date(NaN);if(T.u(u))return new Date;if(u instanceof Date)return new Date(u);if(typeof u=="string"&&!/Z$/i.test(u)){var N=u.match(A);if(N){var E=N[2]-1||0,R=(N[7]||"0").substring(0,3);return x?new Date(Date.UTC(N[1],E,N[3]||1,N[4]||0,N[5]||0,N[6]||0,R)):new Date(N[1],E,N[3]||1,N[4]||0,N[5]||0,N[6]||0,R)}}return new Date(u)})(g),this.init()},v.init=function(){var g=this.$d;this.$y=g.getFullYear(),this.$M=g.getMonth(),this.$D=g.getDate(),this.$W=g.getDay(),this.$H=g.getHours(),this.$m=g.getMinutes(),this.$s=g.getSeconds(),this.$ms=g.getMilliseconds()},v.$utils=function(){return T},v.isValid=function(){return this.$d.toString()!==p},v.isSame=function(g,S){var u=w(g);return this.startOf(S)<=u&&u<=this.endOf(S)},v.isAfter=function(g,S){return w(g)<this.startOf(S)},v.isBefore=function(g,S){return this.endOf(S)<w(g)},v.$g=function(g,S,u){return T.u(g)?this[S]:this.set(u,g)},v.unix=function(){return Math.floor(this.valueOf()/1e3)},v.valueOf=function(){return this.$d.getTime()},v.startOf=function(g,S){var u=this,x=!!T.u(S)||S,N=T.p(g),E=function(K,te){var se=T.w(u.$u?Date.UTC(u.$y,te,K):new Date(u.$y,te,K),u);return x?se:se.endOf(d)},R=function(K,te){return T.w(u.toDate()[K].apply(u.toDate("s"),(x?[0,0,0,0]:[23,59,59,999]).slice(te)),u)},F=this.$W,q=this.$M,B=this.$D,M="set"+(this.$u?"UTC":"");switch(N){case C:return x?E(1,0):E(31,11);case b:return x?E(1,q):E(0,q+1);case m:var W=this.$locale().weekStart||0,X=(F<W?F+7:F)-W;return E(x?B-X:B+(6-X),q);case d:case j:return R(M+"Hours",0);case f:return R(M+"Minutes",1);case l:return R(M+"Seconds",2);case o:return R(M+"Milliseconds",3);default:return this.clone()}},v.endOf=function(g){return this.startOf(g,!1)},v.$set=function(g,S){var u,x=T.p(g),N="set"+(this.$u?"UTC":""),E=(u={},u[d]=N+"Date",u[j]=N+"Date",u[b]=N+"Month",u[C]=N+"FullYear",u[f]=N+"Hours",u[l]=N+"Minutes",u[o]=N+"Seconds",u[a]=N+"Milliseconds",u)[x],R=x===d?this.$D+(S-this.$W):S;if(x===b||x===C){var F=this.clone().set(j,1);F.$d[E](R),F.init(),this.$d=F.set(j,Math.min(this.$D,F.daysInMonth())).$d}else E&&this.$d[E](R);return this.init(),this},v.set=function(g,S){return this.clone().$set(g,S)},v.get=function(g){return this[T.p(g)]()},v.add=function(g,S){var u,x=this;g=Number(g);var N=T.p(S),E=function(q){var B=w(x);return T.w(B.date(B.date()+Math.round(q*g)),x)};if(N===b)return this.set(b,this.$M+g);if(N===C)return this.set(C,this.$y+g);if(N===d)return E(1);if(N===m)return E(7);var R=(u={},u[l]=r,u[f]=i,u[o]=s,u)[N]||1,F=this.$d.getTime()+g*R;return T.w(F,this)},v.subtract=function(g,S){return this.add(-1*g,S)},v.format=function(g){var S=this,u=this.$locale();if(!this.isValid())return u.invalidDate||p;var x=g||"YYYY-MM-DDTHH:mm:ssZ",N=T.z(this),E=this.$H,R=this.$m,F=this.$M,q=u.weekdays,B=u.months,M=u.meridiem,W=function(te,se,de,ce){return te&&(te[se]||te(S,x))||de[se].slice(0,ce)},X=function(te){return T.s(E%12||12,te,"0")},K=M||function(te,se,de){var ce=te<12?"AM":"PM";return de?ce.toLowerCase():ce};return x.replace(U,(function(te,se){return se||(function(de){switch(de){case"YY":return String(S.$y).slice(-2);case"YYYY":return T.s(S.$y,4,"0");case"M":return F+1;case"MM":return T.s(F+1,2,"0");case"MMM":return W(u.monthsShort,F,B,3);case"MMMM":return W(B,F);case"D":return S.$D;case"DD":return T.s(S.$D,2,"0");case"d":return String(S.$W);case"dd":return W(u.weekdaysMin,S.$W,q,2);case"ddd":return W(u.weekdaysShort,S.$W,q,3);case"dddd":return q[S.$W];case"H":return String(E);case"HH":return T.s(E,2,"0");case"h":return X(1);case"hh":return X(2);case"a":return K(E,R,!0);case"A":return K(E,R,!1);case"m":return String(R);case"mm":return T.s(R,2,"0");case"s":return String(S.$s);case"ss":return T.s(S.$s,2,"0");case"SSS":return T.s(S.$ms,3,"0");case"Z":return N}return null})(te)||N.replace(":","")}))},v.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},v.diff=function(g,S,u){var x,N=this,E=T.p(S),R=w(g),F=(R.utcOffset()-this.utcOffset())*r,q=this-R,B=function(){return T.m(N,R)};switch(E){case C:x=B()/12;break;case b:x=B();break;case y:x=B()/3;break;case m:x=(q-F)/6048e5;break;case d:x=(q-F)/864e5;break;case f:x=q/i;break;case l:x=q/r;break;case o:x=q/s;break;default:x=q}return u?x:T.a(x)},v.daysInMonth=function(){return this.endOf(b).$D},v.$locale=function(){return z[this.$L]},v.locale=function(g,S){if(!g)return this.$L;var u=this.clone(),x=I(g,S,!0);return x&&(u.$L=x),u},v.clone=function(){return T.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},k})(),re=ee.prototype;return w.prototype=re,[["$ms",a],["$s",o],["$m",l],["$H",f],["$W",d],["$M",b],["$y",C],["$D",j]].forEach((function(k){re[k[1]]=function(v){return this.$g(v,k[0],k[1])}})),w.extend=function(k,v){return k.$i||(k(v,ee,w),k.$i=!0),w},w.locale=I,w.isDayjs=G,w.unix=function(k){return w(1e3*k)},w.en=z[Y],w.Ls=z,w.p={},w}))})(qe)),qe.exports}var Ls=Us();const $s=Ds(Ls);function Gt(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 Wt(e){if(!e||typeof e!="string")return{hours:0,minutes:0,seconds:0};const t=e.split(":").map(a=>parseInt(a,10)),s=Number.isFinite(t[0])?t[0]:0,r=Number.isFinite(t[1])?t[1]:0,i=Number.isFinite(t[2])?t[2]:0;return{hours:s,minutes:r,seconds:i}}function It(e){const{hours:t,minutes:s,seconds:r}=Wt(e);return $s().hour(t).minute(s).second(r).millisecond(0)}function ve(e,t){const s=(e||"").replace(/\/+$/,""),r=t.startsWith("/")?t:`/${t}`;return`${s}${r}`}function Bs(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}function Tt(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,...Bs()},r=await fetch(e,{...t,headers:s});if(r.status===401)throw window.location.href="/login",new Error("Unauthorized");if(r.status===204)return{};const i=await r.text();let a={};if(i)try{a=JSON.parse(i)}catch{a={ok:r.ok,status:r.status,raw:i}}if(!r.ok){const o=a?.Message||`HTTP ${r.status}`;throw new Error(o)}return a}const ae=(...e)=>e.find(t=>t!=null);function qs(e){return{id:String(ae(e?.AlertId,e?.alertId)??""),priority:ae(e?.Priority,e?.priority,"Low"),timestamp:ae(e?.Timestamp,e?.timestamp,""),statusType:ae(e?.Status,e?.statusType,""),description:ae(e?.Description,e?.description,""),eventName:ae(e?.EventName,e?.eventName),ruleName:ae(e?.RuleName,e?.ruleName),spaceName:ae(e?.SpaceName,e?.spaceName),assignTeam:ae(e?.AssignTeam,e?.assignTeam),cameraName:ae(e?.CameraName,e?.cameraName),type:ae(e?.Type,e?.type),mediaDetails:ae(e?.MediaDetails,e?.mediaDetails),additionalMedia:ae(e?.AdditionalMedia,e?.additionalMedia),timeElapsed:ae(e?.TimeElapsed,e?.timeElapsed),timeRemaining:ae(e?.TimeRemaining,e?.timeRemaining),anomalyName:ae(e?.AnomalyName,e?.anomalyName),alertDetails:ae(e?.AlertDetails,e?.alertDetails),statusHistory:ae(e?.StatusHistory,e?.statusHistory)}}function Qs(e){const t={"Content-Type":"application/json",...e.headers||{}};return{async listAlerts(){const s=ve(e.baseUrl,"/api/detectionpolicy/alerts?customerId=99e5c8b5-b9d4-4d35-8885-7f121c532664"),r=await xe(s,{method:"GET",headers:t});return Array.isArray(r?.Items)?(r?.Items).map(qs):[]},async getAlertStatusList(){const s=ve(e.baseUrl,"/api/detectionpolicy/alerts/StatusList"),r=await xe(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async getAlertsReport(s){const r=ve(e.baseUrl,"/api/detectionpolicy/alerts/GetAlertsReport"),i=Tt(r,s),a=await xe(i,{method:"GET",headers:t});return Array.isArray(a)?a:[]},async updateAlertStatus(s){const r=ve(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 xe(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getAdminSettings(){const s=ve(e.baseUrl,"/api/detectionpolicy/alerts/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/detectionpolicy/alerts/SetAdminSettings"),i={userId:0,isAdminSetting:!0,sortBy:s?.sortBy??""};return xe(r,{method:"POST",headers:t,body:JSON.stringify(i)})},async getPreferenceSettings(){const s=ve(e.baseUrl,"/api/detectionpolicy/alerts/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/detectionpolicy/alerts/SetPreferenceSettings"),i=d=>{const{hours:m,minutes:b,seconds:y}=Wt(d);return(m*3600+b*60+y)*1e7},a={Settings:{UserId:0,AnomalyIds:Array.isArray(s?.anomalyIds)?s.anomalyIds.map(d=>String(d)):[],DoNotDisturbStart:{Ticks:i(s?.doNotDisturbStart)},DoNotDisturbEnd:{Ticks:i(s?.doNotDisturbEnd)},InApp:!!s?.inApp,SMS:!!s?.sms,Email:!!s?.email,SortBy:s?.sortBy??""}},o=await xe(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=ve(e.baseUrl,"/api/detectionpolicy/alerts/GetNotifications"),i=Tt(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:[]}}}function _s(){try{const e=localStorage.getItem("authToken");return e?{Authorization:`Bearer ${e}`}:{}}catch{return{}}}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 Hs(e){const t={"Content-Type":"application/json",...e.headers||{}},s=new URL("/api/detectionpolicy/rules",e.baseUrl).toString();return{async getRules(){const r=await Se(s,{method:"GET",headers:t});return Array.isArray(r)?r:[]},async setEscalationSettings(r){return Se(s,{method:"POST",headers:t,body:JSON.stringify(r??{})})},async getLookups(){const r=D=>new URL(D,e.baseUrl).toString(),i=[Se(r("/api/detectionpolicy/lookups/actiontypes"),{method:"GET",headers:t}),Se(r("/api/detectionpolicy/lookups/anomalies"),{method:"GET",headers:t}),Se(r("/api/detectionpolicy/lookups/thirdparty"),{method:"GET",headers:t}),Se(r("/api/detectionpolicy/lookups/severity"),{method:"GET",headers:t}),Se(r("/api/detectionpolicy/lookups/scheduletypes"),{method:"GET",headers:t})],[a,o,l,f,d]=await Promise.allSettled(i),m=D=>D.status==="fulfilled"&&Array.isArray(D.value)?D.value:[],b=m(a),y=m(o),C=m(l),j=m(f),p=m(d),A=b.map(D=>({actionTypeId:Number(D?.ActionTypeId),name:D?.DisplayName??D?.Name??""})),U=y.map(D=>({recordId:D?.AnomalyId,anomalyName:D?.DisplayName??D?.Name??""})),L=C.map(D=>({thirdPartyId:Number(D?.ThirdPartyId),thirdPartyName:D?.ThirdPartyName??D?.Name??""})),$={actionTypes:A,anomalies:U,thirdParties:L};return j.length&&($.severities=j),p.length&&($.scheduleTypes=p),$},async updateRule(r,i){const a=`${s}/${r}`;return Se(a,{method:"PUT",headers:t,body:JSON.stringify(i??{})})}}}const Kt=h.createContext(null);function Yt({tenant:e="snl",override:t,children:s}){const r=h.useMemo(()=>{const a=t?.alertsBaseUrl&&t.alertsBaseUrl.trim()||wt[e]?.alerts||"";let o=t?.rulesBaseUrl&&t.rulesBaseUrl.trim()||wt[e]?.rules||"";e==="snl"&&(o=a);const l=t?.headers;return{tenant:e,alertsBaseUrl:a,rulesBaseUrl:o,headers:l}},[e,t?.alertsBaseUrl,t?.rulesBaseUrl,JSON.stringify(t?.headers||{})]),i=h.useMemo(()=>{const a=r.tenant==="schools"?Qs({baseUrl:r.alertsBaseUrl,headers:r.headers}):Es({baseUrl:r.alertsBaseUrl,headers:r.headers}),o=r.tenant==="schools"?Hs({baseUrl:r.rulesBaseUrl,headers:r.headers}):Ms({baseUrl:r.alertsBaseUrl,headers:r.headers});return{config:r,alerts:a,rules:o}},[r]);return n.jsx(Kt.Provider,{value:i,children:s})}function fe(){const e=h.useContext(Kt);if(!e)throw new Error("useApi must be used inside ApiProvider");return e}const Gs={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},Ws={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},at=6,ot=7;function Ks(e,t,s){const r=e===at,i=e===ot,a=!t.isEmailSent,o=!t.isSMSSent,l=r&&a||i&&o,f=r?"Send Email":i?"Send SMS":s,d=r&&a?"Email already sent":i&&o?"SMS already sent":`Click to ${f.toLowerCase()}`;return{isDisabled:l,buttonText:f,tooltipTitle:d}}function Ys(e){const t=new Set;(e||[]).forEach(r=>{const i=r.anomalyName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All Types",value:"All"},...s]}function zs(e){const t=new Set;(e||[]).forEach(r=>{const i=r.spaceName;typeof i=="string"&&i.trim().length>0&&t.add(i.trim())});const s=Array.from(t).map(r=>({label:r,value:r}));return[{label:"All",value:"All"},...s]}function Rt(e,t){return`${e}-${t?"email":"sms"}`}function kt(e){return e===at||e===ot}function Ge({value:e,onChange:t,options:s,className:r,dropdownWidth:i}){return n.jsx(c.Select,{className:r,options:s,value:e,onChange:t,dropdownMatchSelectWidth:i??260})}const Vs=[{label:"All levels",value:"All"},{label:"Critical",value:"Critical"},{label:"High",value:"High"},{label:"Medium",value:"Medium"},{label:"Low",value:"Low"}];function Js({value:e,onChange:t,options:s}){return n.jsx(Ge,{className:"w-[140px]",value:e,onChange:t,options:s||Vs})}const Xs=[{label:"All Types",value:"All"},{label:"Weapon Detection",value:"Weapon"},{label:"Unauthorized Access",value:"Unauthorized"},{label:"Aggressive Behavior",value:"Aggressive"}];function Zs({value:e,onChange:t,options:s}){return n.jsx(Ge,{className:"w-[220px]",dropdownWidth:280,value:e,onChange:t,options:s||Xs})}function er({value:e,onChange:t,options:s}){return n.jsx(Ge,{className:"w-[100px]",value:e,onChange:t,options:s||[]})}const tr=[{label:"All",value:"All"},{label:"SOS",value:"SOS"},{label:"911",value:"911"},{label:"Aegix",value:"Aegix"},{label:"Eli",value:"Eli"},{label:"Skydio",value:"Skydio"}];function sr({value:e,onChange:t,options:s}){return n.jsx(Ge,{className:"w-[130px]",value:e,onChange:t,options:s||tr})}function zt({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 lt({data:e,loading:t=!1,pageSize:s=10,columns:r,severityOptions:i,spaceOptions:a,renderActions:o,onAlertIdClick:l,onRefetch:f}){const[d,m]=h.useState("All"),[b,y]=h.useState("All"),[C,j]=h.useState("All"),[p,A]=h.useState("All"),[U,L]=h.useState(""),[$,D]=h.useState([{label:"All",value:"All"}]),[Y,z]=h.useState(new Set),{rules:_,alerts:G}=fe(),I={6:{title:"Email",kind:"icon",icon:n.jsx(Oe.MailOutlined,{})},7:{title:"SMS",kind:"icon",icon:n.jsx(Oe.MessageOutlined,{})}},w=h.useMemo(()=>Ys(e),[e]),T=h.useMemo(()=>zs(e),[e]);h.useEffect(()=>{let u=!0;return(async()=>{try{const x=await _.getLookups(),E=(Array.isArray(x.thirdParties)?x.thirdParties:[]).map(R=>({label:R.thirdPartyName,value:String(R.thirdPartyId)}));u&&D([{label:"All",value:"All"},...E])}catch(x){console.error("Error loading third party options",x)}})(),()=>{u=!1}},[_]);const ee=h.useMemo(()=>(e||[]).some(u=>Ve(u).length>0),[e]),re=h.useMemo(()=>(e||[]).filter(u=>{const x=d==="All"||u.priority===d,N=`${u.id} ${u.description} ${u.statusType}`.toLowerCase(),E=!U||N.includes(U.toLowerCase()),R=b==="All"||(u.anomalyName||"").toLowerCase()===b.toLowerCase(),F=C==="All"||(u.spaceName||"").toLowerCase()===C.toLowerCase(),q=!ee||p==="All"||Ve(u).includes(Number(p));return x&&E&&R&&F&&q}),[e,d,U,b,C,p,ee]),k=w,v=a&&a.length?a:T,g=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:u=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${Ws[u]}`,backgroundColor:Gs[u]},children:u})},{title:"Tracker",key:"tracker",width:140,render:(u,x)=>n.jsx("a",{onClick:N=>{N.preventDefault(),l?.(x,{tab:"track"})},className:"text-blue-600 hover:underline",children:"Tracker"})},{title:"Call to action/Human in the loop",key:"actions",width:320,render:(u,x)=>{if(o)return n.jsx(n.Fragment,{children:o(x)});const N=Ve(x);if(!N.length)return null;const E=async(R,F)=>{const q=Rt(x.id,R);z(B=>new Set(B).add(q));try{const B=await G.sendSMSorEmailNotifications?.(x.id,R,F);B?.responseStatus?(ne.toast.success(B.data||(R?"Email sent successfully":"SMS sent successfully")),f?.()):ne.toast.error(B?.data||B?.errorMessage||"Failed to send notification")}catch(B){ne.toast.error(B?.message||"Failed to send notification")}finally{z(B=>{const M=new Set(B);return M.delete(q),M})}};return n.jsx(c.Space,{size:"middle",children:N.map(R=>{const F=I[R];if(!F)return null;const q=R===at,B=R===ot,{isDisabled:M,buttonText:W,tooltipTitle:X}=Ks(R,x,F.title),K=Rt(x.id,q),te=kt(R)&&Y.has(K),se=()=>{E(q,B)};return n.jsx(c.Tooltip,{title:X,children:n.jsx(c.Button,{size:"small",disabled:M,loading:te,onClick:kt(R)?se:void 0,icon:!te&&(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:W})},R)})})}},{title:"Alert Timestamp",dataIndex:"timestamp",key:"timestamp",width:220,render:(u,x)=>{const N=x.timeElapsed?x.timeElapsed:void 0,E=x.timeRemaining?x.timeRemaining:void 0,R=N?Nt(N):0,F=E?Nt(E):0,q=Math.round(R/(R+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:N??"-"})]}),n.jsx(c.Progress,{percent:q,showInfo:!1,size:"small",strokeColor:Is(x.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:E??"-"})]})]})}},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(u,x)=>n.jsxs("div",{children:[n.jsx("a",{onClick:N=>{N.preventDefault(),l?.(x)},className:"inline-block mb-1 text-blue-600",children:x.alertNumber}),n.jsx("div",{className:"text-black/65",children:u})]})}],S=r&&r.length?r:g;return n.jsx("div",{children:n.jsx(zt,{rowKey:"id",data:re,columns:S,loading:t,pageSize:s,toolbar:n.jsxs(c.Row,{gutter:[12,12],className:"mb-3",align:"middle",children:[n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Severity"}),n.jsx(Js,{value:d,onChange:m,options:i})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Anomaly type"}),n.jsx(Zs,{value:b,onChange:y,options:k})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Space"}),n.jsx(er,{value:C,onChange:j,options:v})]})}),n.jsx(c.Col,{flex:"none",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{children:"Action Taken"}),n.jsx(sr,{value:p,onChange:A,options:$})]})}),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:u=>L(u.target.value),className:"w-[260px] ",enterButton:!0})})]})})})}var Ee=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},rr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},nr=class{#e=rr;#t=!1;setTimeoutProvider(e){process.env.NODE_ENV!=="production"&&this.#t&&e!==this.#e&&console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#e,provider:e}),this.#e=e,process.env.NODE_ENV!=="production"&&(this.#t=!1)}setTimeout(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return process.env.NODE_ENV!=="production"&&(this.#t=!0),this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}},je=new nr;function ir(e){setTimeout(e,0)}var Ce=typeof window>"u"||"Deno"in globalThis;function ue(){}function ar(e,t){return typeof e=="function"?e(t):e}function Ze(e){return typeof e=="number"&&e>=0&&e!==1/0}function Vt(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ae(e,t){return typeof e=="function"?e(t):e}function he(e,t){return typeof e=="function"?e(t):e}function Ot(e,t){const{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:l}=e;if(o){if(r){if(t.queryHash!==ct(o,t.options))return!1}else if(!Me(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 Et(e,t){const{exact:s,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(s){if(Ie(t.options.mutationKey)!==Ie(a))return!1}else if(!Me(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function ct(e,t){return(t?.queryKeyHashFn||Ie)(e)}function Ie(e){return JSON.stringify(e,(t,s)=>tt(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}function Me(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(s=>Me(e[s],t[s])):!1}var or=Object.prototype.hasOwnProperty;function et(e,t){if(e===t)return e;const s=Pt(e)&&Pt(t);if(!s&&!(tt(e)&&tt(t)))return t;const i=(s?e:Object.keys(e)).length,a=s?t:Object.keys(t),o=a.length,l=s?new Array(o):{};let f=0;for(let d=0;d<o;d++){const m=s?d:a[d],b=e[m],y=t[m];if(b===y){l[m]=b,(s?d<i:or.call(e,m))&&f++;continue}if(b===null||y===null||typeof b!="object"||typeof y!="object"){l[m]=y;continue}const C=et(b,y);l[m]=C,C===b&&f++}return i===o&&f===i?e:l}function Qe(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 Pt(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function tt(e){if(!Mt(e))return!1;const t=e.constructor;if(t===void 0)return!0;const s=t.prototype;return!(!Mt(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Mt(e){return Object.prototype.toString.call(e)==="[object Object]"}function lr(e){return new Promise(t=>{je.setTimeout(t,e)})}function st(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 et(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 et(e,t)}return t}function cr(e,t,s=0){const r=[...e,t];return s&&r.length>s?r.slice(1):r}function ur(e,t,s=0){const r=[t,...e];return s&&r.length>s?r.slice(0,-1):r}var _e=Symbol();function Jt(e,t){return process.env.NODE_ENV!=="production"&&e.queryFn===_e&&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===_e?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ut(e,t){return typeof e=="function"?e(...t):!!e}function dr(e,t,s){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i)}),e}var hr=class extends Ee{#e;#t;#s;constructor(){super(),this.#s=e=>{if(!Ce&&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"}},dt=new hr;function rt(){let e,t;const s=new Promise((i,a)=>{e=i,t=a});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return s.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},s.reject=i=>{r({status:"rejected",reason:i}),t(i)},s}var fr=ir;function mr(){let e=[],t=0,s=l=>{l()},r=l=>{l()},i=fr;const a=l=>{t?e.push(l):i(()=>{s(l)})},o=()=>{const l=e;e=[],l.length&&i(()=>{r(()=>{l.forEach(f=>{s(f)})})})};return{batch:l=>{let f;t++;try{f=l()}finally{t--,t||o()}return f},batchCalls:l=>(...f)=>{a(()=>{l(...f)})},schedule:a,setNotifyFunction:l=>{s=l},setBatchNotifyFunction:l=>{r=l},setScheduler:l=>{i=l}}}var ie=mr(),pr=class extends Ee{#e=!0;#t;#s;constructor(){super(),this.#s=e=>{if(!Ce&&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}},He=new pr;function yr(e){return Math.min(1e3*2**e,3e4)}function Xt(e){return(e??"online")==="online"?He.isOnline():!0}var nt=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Zt(e){let t=!1,s=0,r;const i=rt(),a=()=>i.status!=="pending",o=p=>{if(!a()){const A=new nt(p);y(A),e.onCancel?.(A)}},l=()=>{t=!0},f=()=>{t=!1},d=()=>dt.isFocused()&&(e.networkMode==="always"||He.isOnline())&&e.canRun(),m=()=>Xt(e.networkMode)&&e.canRun(),b=p=>{a()||(r?.(),i.resolve(p))},y=p=>{a()||(r?.(),i.reject(p))},C=()=>new Promise(p=>{r=A=>{(a()||d())&&p(A)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),j=()=>{if(a())return;let p;const A=s===0?e.initialPromise:void 0;try{p=A??e.fn()}catch(U){p=Promise.reject(U)}Promise.resolve(p).then(b).catch(U=>{if(a())return;const L=e.retry??(Ce?0:3),$=e.retryDelay??yr,D=typeof $=="function"?$(s,U):$,Y=L===!0||typeof L=="number"&&s<L||typeof L=="function"&&L(s,U);if(t||!Y){y(U);return}s++,e.onFail?.(s,U),lr(D).then(()=>d()?void 0:C()).then(()=>{t?y(U):j()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:l,continueRetry:f,canStart:m,start:()=>(m()?j():C().then(j),i)}}var es=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ze(this.gcTime)&&(this.#e=je.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ce?1/0:300*1e3))}clearGcTimeout(){this.#e&&(je.clearTimeout(this.#e),this.#e=void 0)}},gr=class extends es{#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=Ft(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=Ft(this.options);t.data!==void 0&&(this.setState(Dt(t.data,t.dataUpdatedAt)),this.#e=t)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(e,t){const s=st(this.state.data,e,this.options);return this.#i({data:s,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),s}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){const t=this.#r?.promise;return this.#r?.cancel(e),t?t.then(ue).catch(ue):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>he(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===_e||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>Ae(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:!Vt(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=Jt(this.options,t),d=(()=>{const m={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(m),m})();return this.#o=!1,this.options.persister?this.options.persister(l,d,this):l(d)},o=(()=>{const l={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(l),l})();this.options.behavior?.onFetch(o,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#i({type:"fetch",meta:o.fetchOptions?.meta}),this.#r=Zt({initialPromise:t?.initialPromise,fn:o.fetchFn,onCancel:l=>{l instanceof nt&&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 nt){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,...ts(s.data,this.options),fetchMeta:e.meta??null};case"success":const r={...s,...Dt(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),ie.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:e})})}};function ts(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Xt(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Dt(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ft(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,s=t!==void 0,r=s?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}var vr=class extends Ee{constructor(e,t){super(),this.options=t,this.#e=e,this.#i=null,this.#o=rt(),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),Ut(this.#t,this.options)?this.#d():this.updateResult(),this.#x())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return it(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return it(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 he(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#A(),this.#t.setOptions(this.options),t._defaulted&&!Qe(this.options,t)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});const r=this.hasListeners();r&&Lt(this.#t,s,this.options,t)&&this.#d(),this.updateResult(),r&&(this.#t!==s||he(this.options.enabled,this.#t)!==he(t.enabled,this.#t)||Ae(this.options.staleTime,this.#t)!==Ae(t.staleTime,this.#t))&&this.#y();const i=this.#g();r&&(this.#t!==s||he(this.options.enabled,this.#t)!==he(t.enabled,this.#t)||i!==this.#l)&&this.#v(i)}getOptimisticResult(e){const t=this.#e.getQueryCache().build(this.#e,e),s=this.createResult(t,e);return br(this,s)&&(this.#n=s,this.#a=this.options,this.#r=this.#t.state),s}getCurrentResult(){return this.#n}trackResult(e,t){return new Proxy(e,{get:(s,r)=>(this.trackProp(r),t?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){const t=this.#e.defaultQueryOptions(e),s=this.#e.getQueryCache().build(this.#e,t);return s.fetch().then(()=>this.createResult(s,t))}fetch(e){return this.#d({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#n))}#d(e){this.#A();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(ue)),t}#y(){this.#b();const e=Ae(this.options.staleTime,this.#t);if(Ce||this.#n.isStale||!Ze(e))return;const s=Vt(this.#n.dataUpdatedAt,e)+1;this.#c=je.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,!(Ce||he(this.options.enabled,this.#t)===!1||!Ze(this.#l)||this.#l===0)&&(this.#u=je.setInterval(()=>{(this.options.refetchIntervalInBackground||dt.isFocused())&&this.#d()},this.#l))}#x(){this.#y(),this.#v(this.#g())}#b(){this.#c&&(je.clearTimeout(this.#c),this.#c=void 0)}#S(){this.#u&&(je.clearInterval(this.#u),this.#u=void 0)}createResult(e,t){const s=this.#t,r=this.options,i=this.#n,a=this.#r,o=this.#a,f=e!==s?e.state:this.#s,{state:d}=e;let m={...d},b=!1,y;if(t._optimisticResults){const G=this.hasListeners(),I=!G&&Ut(e,t),w=G&&Lt(e,s,t,r);(I||w)&&(m={...m,...ts(d.data,e.options)}),t._optimisticResults==="isRestoring"&&(m.fetchStatus="idle")}let{error:C,errorUpdatedAt:j,status:p}=m;y=m.data;let A=!1;if(t.placeholderData!==void 0&&y===void 0&&p==="pending"){let G;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(G=i.data,A=!0):G=typeof t.placeholderData=="function"?t.placeholderData(this.#f?.state.data,this.#f):t.placeholderData,G!==void 0&&(p="success",y=st(i?.data,G,t),b=!0)}if(t.select&&y!==void 0&&!A)if(i&&y===a?.data&&t.select===this.#p)y=this.#h;else try{this.#p=t.select,y=t.select(y),y=st(i?.data,y,t),this.#h=y,this.#i=null}catch(G){this.#i=G}this.#i&&(C=this.#i,y=this.#h,j=Date.now(),p="error");const U=m.fetchStatus==="fetching",L=p==="pending",$=p==="error",D=L&&U,Y=y!==void 0,_={status:p,fetchStatus:m.fetchStatus,isPending:L,isSuccess:p==="success",isError:$,isInitialLoading:D,isLoading:D,data:y,dataUpdatedAt:m.dataUpdatedAt,error:C,errorUpdatedAt:j,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>f.dataUpdateCount||m.errorUpdateCount>f.errorUpdateCount,isFetching:U,isRefetching:U&&!L,isLoadingError:$&&!Y,isPaused:m.fetchStatus==="paused",isPlaceholderData:b,isRefetchError:$&&Y,isStale:ht(e,t),refetch:this.refetch,promise:this.#o,isEnabled:he(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){const G=T=>{_.status==="error"?T.reject(_.error):_.data!==void 0&&T.resolve(_.data)},I=()=>{const T=this.#o=_.promise=rt();G(T)},w=this.#o;switch(w.status){case"pending":e.queryHash===s.queryHash&&G(w);break;case"fulfilled":(_.status==="error"||_.data!==w.value)&&I();break;case"rejected":(_.status!=="error"||_.error!==w.reason)&&I();break}}return _}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),Qe(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.#N({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()}#N(e){ie.batch(()=>{e.listeners&&this.listeners.forEach(t=>{t(this.#n)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function xr(e,t){return he(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ut(e,t){return xr(e,t)||e.state.data!==void 0&&it(e,t,t.refetchOnMount)}function it(e,t,s){if(he(t.enabled,e)!==!1&&Ae(t.staleTime,e)!=="static"){const r=typeof s=="function"?s(e):s;return r==="always"||r!==!1&&ht(e,t)}return!1}function Lt(e,t,s,r){return(e!==t||he(r.enabled,e)===!1)&&(!s.suspense||e.state.status!=="error")&&ht(e,s)}function ht(e,t){return he(t.enabled,e)!==!1&&e.isStaleByTime(Ae(t.staleTime,e))}function br(e,t){return!Qe(e.getCurrentResult(),t)}function $t(e){return{onFetch:(t,s)=>{const r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[];let l={pages:[],pageParams:[]},f=0;const d=async()=>{let m=!1;const b=j=>{dr(j,()=>t.signal,()=>m=!0)},y=Jt(t.options,t.fetchOptions),C=async(j,p,A)=>{if(m)return Promise.reject();if(p==null&&j.pages.length)return Promise.resolve(j);const L=(()=>{const z={client:t.client,queryKey:t.queryKey,pageParam:p,direction:A?"backward":"forward",meta:t.options.meta};return b(z),z})(),$=await y(L),{maxPages:D}=t.options,Y=A?ur:cr;return{pages:Y(j.pages,$,D),pageParams:Y(j.pageParams,p,D)}};if(i&&a.length){const j=i==="backward",p=j?Sr:Bt,A={pages:a,pageParams:o},U=p(r,A);l=await C(A,U,j)}else{const j=e??a.length;do{const p=f===0?o[0]??r.initialPageParam:Bt(r,l);if(f>0&&p==null)break;l=await C(l,p),f++}while(f<j)}return l};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},s):t.fetchFn=d}}}function Bt(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 Sr(e,{pages:t,pageParams:s}){return t.length>0?e.getPreviousPageParam?.(t[0],t,s[0],s):void 0}var Ar=class extends es{#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||ss(),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=Zt({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}),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),ie.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(e)}),this.#s.notify({mutation:this,type:"updated",action:e})})}};function ss(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Nr=class extends Ee{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(e,t,s){const r=new Ar({client:e,mutationCache:this,mutationId:++this.#s,options:e.defaultMutationOptions(t),state:s});return this.add(r),r}add(e){this.#e.add(e);const t=$e(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=$e(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=$e(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=$e(e);return typeof t=="string"?this.#t.get(t)?.find(r=>r!==e&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){ie.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=>Et(t,s))}findAll(e={}){return this.getAll().filter(t=>Et(e,t))}notify(e){ie.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){const e=this.getAll().filter(t=>t.state.isPaused);return ie.batch(()=>Promise.all(e.map(t=>t.continue().catch(ue))))}};function $e(e){return e.options.scope?.id}var wr=class extends Ee{#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),Qe(this.options,t)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),t?.mutationKey&&this.options.mutationKey&&Ie(t.mutationKey)!==Ie(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??ss();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){ie.batch(()=>{if(this.#n&&this.hasListeners()){const t=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type==="success"){try{this.#n.onSuccess?.(e.data,t,s,r)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(e.data,null,t,s,r)}catch(i){Promise.reject(i)}}else if(e?.type==="error"){try{this.#n.onError?.(e.error,t,s,r)}catch(i){Promise.reject(i)}try{this.#n.onSettled?.(void 0,e.error,t,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(t=>{t(this.#t)})})}},jr=class extends Ee{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,s){const r=t.queryKey,i=t.queryHash??ct(r,t);let a=this.get(i);return a||(a=new gr({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:s,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){const t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){ie.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=>Ot(t,s))}findAll(e={}){const t=this.getAll();return Object.keys(e).length>0?t.filter(s=>Ot(e,s)):t}notify(e){ie.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ie.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ie.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Cr=class{#e;#t;#s;#n;#r;#a;#o;#i;constructor(e={}){this.#e=e.queryCache||new jr,this.#t=e.mutationCache||new Nr,this.#s=e.defaultOptions||{},this.#n=new Map,this.#r=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=dt.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#i=He.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(Ae(t.staleTime,s))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:s})=>{const r=s.data;return[t,r]})}setQueryData(e,t,s){const r=this.defaultQueryOptions({queryKey:e}),a=this.#e.get(r.queryHash)?.state.data,o=ar(t,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(e,t,s){return ie.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;ie.batch(()=>{t.findAll(e).forEach(s=>{t.remove(s)})})}resetQueries(e,t){const s=this.#e;return ie.batch(()=>(s.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const s={revert:!0,...t},r=ie.batch(()=>this.#e.findAll(e).map(i=>i.cancel(s)));return Promise.all(r).then(ue).catch(ue)}invalidateQueries(e,t={}){return ie.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=ie.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,s);return s.throwOnError||(a=a.catch(ue)),i.state.fetchStatus==="paused"?Promise.resolve():a}));return Promise.all(r).then(ue)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const s=this.#e.build(this,t);return s.isStaleByTime(Ae(t.staleTime,s))?s.fetch(t):Promise.resolve(s.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(ue).catch(ue)}fetchInfiniteQuery(e){return e.behavior=$t(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(ue).catch(ue)}ensureInfiniteQueryData(e){return e.behavior=$t(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return He.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(Ie(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...this.#n.values()],s={};return t.forEach(r=>{Me(e,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(e,t){this.#r.set(Ie(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...this.#r.values()],s={};return t.forEach(r=>{Me(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=ct(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===_e&&(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()}},rs=le.createContext(void 0),ft=e=>{const t=le.useContext(rs);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Ir=({client:e,children:t})=>(le.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),n.jsx(rs.Provider,{value:e,children:t})),ns=le.createContext(!1),Tr=()=>le.useContext(ns);ns.Provider;function Rr(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var kr=le.createContext(Rr()),Or=()=>le.useContext(kr),Er=(e,t,s)=>{const r=s?.state.error&&typeof e.throwOnError=="function"?ut(e.throwOnError,[s.state.error,s]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Pr=e=>{le.useEffect(()=>{e.clearReset()},[e])},Mr=({result:e,errorResetBoundary:t,throwOnError:s,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ut(s,[e.error,r])),Dr=e=>{if(e.suspense){const s=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},Fr=(e,t)=>e.isLoading&&e.isFetching&&!t,Ur=(e,t)=>e?.suspense&&t.isPending,qt=(e,t,s)=>t.fetchOptimistic(e).catch(()=>{s.clearReset()});function Lr(e,t,s){if(process.env.NODE_ENV!=="production"&&(typeof e!="object"||Array.isArray(e)))throw new Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');const r=Tr(),i=Or(),a=ft(),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);const l=a.getQueryCache().get(o.queryHash);process.env.NODE_ENV!=="production"&&(o.queryFn||console.error(`[${o.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`)),o._optimisticResults=r?"isRestoring":"optimistic",Dr(o),Er(o,i,l),Pr(i);const f=!a.getQueryCache().get(o.queryHash),[d]=le.useState(()=>new t(a,o)),m=d.getOptimisticResult(o),b=!r&&e.subscribed!==!1;if(le.useSyncExternalStore(le.useCallback(y=>{const C=b?d.subscribe(ie.batchCalls(y)):ue;return d.updateResult(),C},[d,b]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),le.useEffect(()=>{d.setOptions(o)},[o,d]),Ur(o,m))throw qt(o,d,i);if(Mr({result:m,errorResetBoundary:i,throwOnError:o.throwOnError,query:l,suspense:o.suspense}))throw m.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,m),o.experimental_prefetchInRender&&!Ce&&Fr(m,r)&&(f?qt(o,d,i):l?.promise)?.catch(ue).finally(()=>{d.updateResult()}),o.notifyOnChangeProps?m:d.trackResult(m)}function mt(e,t){return Lr(e,vr)}function $r(e,t){const s=ft(),[r]=le.useState(()=>new wr(s,e));le.useEffect(()=>{r.setOptions(e)},[r,e]);const i=le.useSyncExternalStore(le.useCallback(o=>r.subscribe(ie.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=le.useCallback((o,l)=>{r.mutate(o,l).catch(ue)},[r]);if(i.error&&ut(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function pt(){const{alerts:e}=fe(),t=ft();return $r({mutationFn:s=>e.updateAlertStatus(s),onSuccess:()=>{t.invalidateQueries({queryKey:["alerts","list"]}),t.invalidateQueries({queryKey:["alerts","report"]})}})}function Br(e,t){return e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0,timeZone:t})}function qr(e,t){try{const i=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"short"}).formatToParts(e).find(o=>o.type==="timeZoneName")?.value;let a;try{const l=new Intl.DateTimeFormat("en-US",{timeZone:t,timeZoneName:"shortOffset"}).formatToParts(e).find(f=>f.type==="timeZoneName");l?.value&&l.value.startsWith("GMT")&&(a=l.value.replace("GMT",""))}catch{}return{abbr:i,offset:a}}catch{return{}}}function Qr(e){if(!e)return"-";try{const t=new Date(e),s=d=>String(d).padStart(2,"0"),r=s(t.getMonth()+1),i=s(t.getDate()),a=t.getFullYear(),o=s(t.getHours()),l=s(t.getMinutes()),f=s(t.getSeconds());return`${r}/${i}/${a} ${o}:${l}:${f}`}catch{return"-"}}function Je(e){if(!e)return"-";try{return new Date(e).toLocaleString("en-US",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return"-"}}const _r={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},Hr={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"};function is({alerts:e,loading:t=!1,pageSize:s=10,completedStatus:r="Completed",severityOptions:i,anomalyOptions:a,spaceOptions:o,onAlertIdClick:l}){const f=pt(),d=async y=>{try{const C=await f.mutateAsync({alertUniqueId:y.alertId??y.id,alertId:y.id,status:"Reopen",notes:"Reopened",modifiedBy:0});if(C?.responseStatus){const j=C?.data||"Alert reopened successfully.";ne.toast.success(j)}else{const j=C?.errorMessage||"Failed to reopen alert";ne.toast.error(j)}}catch{ne.toast.error("Failed to reopen alert. Please try again.")}},m=[{title:"Severity",dataIndex:"priority",key:"priority",width:120,render:y=>n.jsx(c.Tag,{className:"px-[10px] py-[2px]",style:{border:`2px solid ${_r[y]}`,backgroundColor:Hr[String(y)]},children:y})},{title:"Timestamp",dataIndex:"timestamp",key:"timestamp",width:200,render:y=>Qr(y)},{title:"Status",dataIndex:"statusType",key:"statusType",width:140},{title:"Description",dataIndex:"description",key:"description",render:(y,C)=>n.jsxs("div",{children:[n.jsx("a",{onClick:j=>{j.preventDefault(),l?.(C)},className:"inline-block mb-1 text-blue-600",children:C.alertNumber}),n.jsx("div",{className:"text-black/65",children:y})]})},{title:"",key:"menu",width:60,align:"right",render:(y,C)=>n.jsx(c.Dropdown,{trigger:["click"],menu:{items:[{key:"reopen",label:"Reopen"}],onClick:({key:j})=>{j==="reopen"&&d(C)}},children:n.jsx(c.Button,{type:"text",icon:n.jsx(Oe.MoreOutlined,{})})})}],b=(e||[]).filter(y=>(y.statusType||"").toLowerCase()===r.toLowerCase());return n.jsx(lt,{data:b,loading:t,pageSize:s,columns:m,severityOptions:i,anomalyOptions:a,spaceOptions:o,renderActions:void 0,onAlertIdClick:l})}function Gr({size:e=120,time:t,timeZone:s="America/New_York"}){const{hours:r,minutes:i,seconds:a}=h.useMemo(()=>{const b=new Intl.DateTimeFormat("en-US",{timeZone:s,hour:"numeric",minute:"numeric",second:"numeric",hour12:!1}).formatToParts(t);return{hours:parseInt(b.find(y=>y.type==="hour")?.value||"0",10),minutes:parseInt(b.find(y=>y.type==="minute")?.value||"0",10),seconds:parseInt(b.find(y=>y.type==="second")?.value||"0",10)}},[t,s]),o=a*6,l=i*6+a*.1,f=r%12*30+i*.5,d=e/2;return n.jsxs("div",{className:"relative rounded-full border border-gray-300 bg-white",style:{width:e,height:e},role:"img","aria-label":"Analog Clock",children:[[...Array(12)].map((m,b)=>{const y=b*30,C=6,j=d-4,p=j-C,A=(y-90)*(Math.PI/180),U=d+p*Math.cos(A),L=d+p*Math.sin(A),$=d+j*Math.cos(A),D=d+j*Math.sin(A);return n.jsx("svg",{className:"absolute inset-0",width:e,height:e,children:n.jsx("line",{x1:U,y1:L,x2:$,y2:D,stroke:"#9CA3AF",strokeWidth:b%3===0?2:1,strokeLinecap:"round"})},b)}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${f}deg)`},children:n.jsx("line",{x1:d,y1:d,x2:d,y2:d-e*.25,stroke:"#1F2937",strokeWidth:4,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${l}deg)`},children:n.jsx("line",{x1:d,y1:d,x2:d,y2:d-e*.35,stroke:"#374151",strokeWidth:3,strokeLinecap:"round"})}),n.jsx("svg",{className:"absolute inset-0",width:e,height:e,style:{transform:`rotate(${o}deg)`},children:n.jsx("line",{x1:d,y1:d+e*.08,x2:d,y2:d-e*.38,stroke:"#EF4444",strokeWidth:1.5,strokeLinecap:"round"})}),n.jsx("div",{className:"absolute bg-gray-900 rounded-full",style:{width:8,height:8,left:d-4,top:d-4}})]})}function as({label:e="USA",timeZone:t="America/New_York",updateIntervalMs:s=1e3,className:r}){const[i,a]=h.useState(new Date);h.useEffect(()=>{const d=setInterval(()=>a(new Date),s);return()=>clearInterval(d)},[s]);const o=h.useMemo(()=>Br(i,t),[i,t]),{abbr:l,offset:f}=h.useMemo(()=>qr(i,t),[i,t]);return n.jsxs("div",{className:`flex items-center gap-3 ${r||""}`,children:[n.jsx(Gr,{time:i,timeZone:t,size:80}),n.jsxs("div",{className:"flex flex-col items-baseline gap-1",children:[n.jsxs("div",{className:"flex items-center gap-2 text-sm text-gray-600",children:[n.jsx("span",{className:"uppercase",children:e}),l&&n.jsx("span",{className:"px-1.5 py-0.5 rounded-md border text-[10px] leading-none text-gray-600 bg-gray-50",children:l}),f&&n.jsx("span",{className:"text-xs text-gray-500",children:f})]}),n.jsx("div",{className:"text-2xl font-semibold text-gray-700 tracking-wide",children:o})]})]})}const Wr=[{SeverityId:1,Code:"LOW",DisplayName:"Low",SortOrder:10,IsActive:!0},{SeverityId:2,Code:"MEDIUM",DisplayName:"Medium",SortOrder:20,IsActive:!0},{SeverityId:3,Code:"HIGH",DisplayName:"High",SortOrder:30,IsActive:!0},{SeverityId:4,Code:"CRITICAL",DisplayName:"Critical",SortOrder:40,IsActive:!0}],Kr=[{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"}],Yr=[{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"}],ke={severities:Wr,rules:Kr,userRoles:Yr},{Text:zr}=c.Typography;function Vr({sortBy:e,onChange:t,showActions:s,onSave:r,onClear:i,saving:a}){return n.jsxs(c.Row,{gutter:[16,16],align:"middle",children:[n.jsx(c.Col,{xs:24,md:8,lg:5,children:n.jsxs(c.Space,{className:"w-full items-center",direction:"horizontal",size:12,children:[n.jsx(zr,{className:"text-gray-600",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:be}=c.Typography;function Jr(e){const{selectedRule:t,setSelectedRule:s,ruleOptions:r,minsOptions:i,roleOptions:a,l1mins:o,setL1mins:l,l1role:f,setL1role:d,l2mins:m,setL2mins:b,l2role:y,setL2role:C,l3mins:j,setL3mins:p,l3role:A,setL3role:U,actions:L,setActions:$,thirdPartyIds:D,setThirdPartyIds:Y,humanLoop:z,setHumanLoop:_,onClear:G,onSave:I,saving:w,onActionTypesLoaded:T}=e,{rules:ee}=fe(),[re,k]=h.useState([]),[v,g]=h.useState([]),[S,u]=h.useState(!1);h.useEffect(()=>{let E=!1;return(async()=>{try{u(!0);const R=await ee.getLookups();if(E||!R||!Array.isArray(R.actionTypes))return;const F=R.actionTypes.map(B=>({label:B.name,value:String(B.actionTypeId)}));k(F),T&&T(R.actionTypes);const q=Array.isArray(R.thirdParties)?R.thirdParties.map(B=>({label:B.thirdPartyName,value:B.thirdPartyId})):[];g(q)}catch(R){console.error("Error loading lookups",R)}finally{E||u(!1)}})(),()=>{E=!0}},[]);const x=typeof o=="number"||typeof f=="number"||typeof m=="number"||typeof y=="number"||typeof j=="number"||typeof A=="number"||Array.isArray(L)&&L.length>0||Array.isArray(D)&&D.length>0||!!z,N=!!t&&x&&!w;return n.jsxs(c.Spin,{spinning:!!w||S,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(be,{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(be,{className:"text-gray-700 font-medium block mb-1",children:"Level 1 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(be,{className:"text-gray-700 font-medium block mb-1",children:"Escalate to"})})]}),n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(c.Select,{className:"w-full",placeholder:"Mins",value:o,onChange:l,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:f,onChange:d,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:4,children:n.jsxs("div",{children:[n.jsxs(c.Row,{gutter:8,children:[n.jsx(c.Col,{span:10,children:n.jsx(be,{className:"text-gray-700 font-medium block mb-1",children:"Level 2 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(be,{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:m,onChange:b,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:y,onChange:C,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(be,{className:"text-gray-700 font-medium block mb-1",children:"Level 3 (mins)"})}),n.jsx(c.Col,{span:14,children:n.jsx(be,{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:j,onChange:p,options:i})}),n.jsx(c.Col,{span:14,children:n.jsx(c.Select,{placeholder:"Escalate to",className:"w-full",value:A,onChange:U,options:a})})]})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:5,children:n.jsxs("div",{children:[n.jsx(be,{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:L,onChange:$,options:re})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,lg:3,children:n.jsx("div",{className:"flex items-end h-full",children:n.jsx(c.Checkbox,{checked:z,onChange:E=>_(E.target.checked),children:"Human-In-The-Loop"})})})]}),n.jsxs(c.Row,{gutter:[16,16],align:"bottom",className:"mt-4",children:[n.jsx(c.Col,{xs:24,sm:12,md:8,lg:5,children:n.jsxs("div",{children:[n.jsx(be,{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:D,onChange:Y,options:v})]})}),n.jsx(c.Col,{xs:24,sm:12,md:8,children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(c.Button,{onClick:G,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:I,loading:!!w,disabled:!N,children:"Save"})]})})]})]})}function Xr({entries:e,userRoles:t,onEdit:s,loading:r}){const i=new Map(t.map(o=>[o.userRoleId,o.userRoleName])),a=o=>o.map(l=>i.get(l)||String(l)).join(", ");return n.jsx(c.Table,{rowKey:"id",dataSource:e,pagination:!1,loading:r,columns:[{title:"Rule",dataIndex:"ruleOrSeverityLabel",key:"rule"},{title:"Level 1",key:"l1",render:(o,l)=>n.jsxs("span",{children:[l.l1.minutes?`Action taken in (${l.l1.minutes} Mins)`:"No Action taken in 0 Min",l.l1.roles?.length?`, Escalate to (${a(l.l1.roles)})`:""]})},{title:"Level 2",key:"l2",render:(o,l)=>n.jsxs("span",{children:[l.l2.minutes?`Action taken in (${l.l2.minutes} Mins)`:"No Action taken in 0 Min",l.l2.roles?.length?`, Escalate to (${a(l.l2.roles)})`:""]})},{title:"Level 3",key:"l3",render:(o,l)=>n.jsxs("span",{children:[l.l3.minutes?`Action taken in (${l.l3.minutes} Mins)`:"No Action taken in 0 Min",l.l3.roles?.length?`, Escalate to (${a(l.l3.roles)})`:""]})},{title:"Pick Actions",key:"actionsCol",render:(o,l)=>l.actions&&l.actions.length?l.actions.join(", "):"-"},{title:"Notify",key:"notify",render:(o,l)=>l.notify&&l.notify.length?l.notify.join(", "):"-"},{title:"Human-In-The-Loop",key:"humanLoop",render:(o,l)=>l.humanLoop?"Yes":"No"},{title:"Actions",key:"ops",render:(o,l)=>n.jsx(c.Button,{type:"text",onClick:()=>s(l.id),children:n.jsx(Oe.EditOutlined,{})})}]})}const{Title:Zr}=c.Typography;function os({userRoles:e,rules:t,rawRules:s}){const{rules:r}=fe(),[i,a]=h.useState(!1),[o,l]=h.useState(s),[f,d]=h.useState({}),m=h.useMemo(()=>e.map(p=>({label:p.userRoleName,value:p.userRoleId})),[e]),b=h.useMemo(()=>(t||[]).map((p,A)=>({key:p.RuleId||p.Name||String(A),ruleName:p.Name||"-",ruleDesc:p.Description||""})),[t]);h.useEffect(()=>{let p=!1;return(async()=>{try{a(!0);const A=await r.getRules();p||(l(Array.isArray(A)?A:[]),d({}))}catch{!p&&Array.isArray(s)&&l(s)}finally{p||a(!1)}})(),()=>{p=!0}},[]),h.useEffect(()=>{!o&&Array.isArray(s)&&l(s)},[s]);const y=h.useMemo(()=>{if(!Array.isArray(o)||!o.length)return{};const p={};for(const A of b){const U=o.find($=>$?.ruleId===A.key||$?.ruleName===A.key||$?.RuleId===A.key||$?.ruleName===A.ruleName||$?.Name===A.ruleName),L=Array.isArray(U?.userRoleIds)?U.userRoleIds:[];L.length&&(p[A.key]=L)}return p},[o,b]),C=()=>{d({})},j=async()=>{try{if(!o||!Array.isArray(o)||Object.keys(f).length===0){ne.toast.info("No changes to save");return}a(!0);const p=Object.entries(f).map(async([A,U])=>{const L=o.find(_=>_?.ruleId===A||_?.ruleName===A||_?.RuleId===A),$=typeof L?.recordId=="number"?L.recordId:void 0;if(!L||typeof $!="number")throw new Error(`Unable to find recordId for rule ${A}`);const D=Array.isArray(U)?U:[],Y=D.map(_=>{const G=e.find(I=>I.userRoleId===_);return{id:_,name:G?.userRoleName??String(_)}}),z={...L,ruleId:A,userRoleIds:D,userRoles:Y,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($,z)});await Promise.all(p),ne.toast.success("Alert assignment saved");try{const A=await r.getRules();l(Array.isArray(A)?A:[]),d({})}catch(A){console.error("Failed to refresh rules after save",A)}}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(Zr,{level:4,className:"!mb-4",children:"Alert Assignment"})}),n.jsx(c.Table,{rowKey:"key",dataSource:b,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,A)=>n.jsx(c.Select,{mode:"multiple",placeholder:"Dropdown with Multi select",className:"w-full",value:f[A.key]??y[A.key]??[],onChange:U=>d(L=>({...L,[A.key]:U})),options:m})}]}),n.jsxs(c.Space,{className:"mt-4",children:[n.jsx(c.Button,{onClick:C,disabled:i,children:"Clear"}),n.jsx(c.Button,{type:"primary",onClick:j,loading:i,disabled:i||Object.keys(f).length===0,children:"Save"})]})]})}const{Title:Qt}=c.Typography;function ls({severities:e,rules:t,userRoles:s,rawRules:r,onSave:i}){const{rules:a,alerts:o}=fe(),[l,f]=h.useState("By Severity"),[d,m]=h.useState("By severity"),[b,y]=h.useState("By Severity"),[C,j]=h.useState(!1),[p,A]=h.useState(!1),[U,L]=h.useState(!1),[$,D]=h.useState(null),[Y,z]=h.useState("rules"),[_,G]=h.useState(),[I,w]=h.useState();console.log("usr",s);const[T,ee]=h.useState(),[re,k]=h.useState(),[v,g]=h.useState(),[S,u]=h.useState(),[x,N]=h.useState(),[E,R]=h.useState(),[F,q]=h.useState([]),[B,M]=h.useState([]),[W,X]=h.useState(!1),[K,te]=h.useState({}),[se,de]=h.useState({}),[ce,We]=h.useState(s||[]),[Pe,Te]=h.useState([]),[Ke,oe]=h.useState(!1),[Re,De]=h.useState(!1),[Ne,gt]=h.useState(r||[]);h.useEffect(()=>{r&&r.length&>(r)},[r]),h.useEffect(()=>{if(!Ne||!Ne.length)return;const O=Object.keys(K).length>0||Object.keys(se).length>0;if(Pe.length&&!O)return;const J=Ne.map((Q,P)=>{const V=t.find(ge=>ge.RuleId===(Q.ruleId||Q.ruleName))?.Name||Q.ruleName||Q.Name||"-",H=Q.escalationSettings||{},Z=typeof H.level1UserRoleId=="number"&&H.level1UserRoleId>0?[H.level1UserRoleId]:[],ye=typeof H.level2UserRoleId=="number"&&H.level2UserRoleId>0?[H.level2UserRoleId]:[],Ye=typeof H.level3UserRoleId=="number"&&H.level3UserRoleId>0?[H.level3UserRoleId]:[],xt=(Array.isArray(H.escalationSettingsActionTypeIds)?H.escalationSettingsActionTypeIds:[]).map(ge=>K[ge]||String(ge)),St=(Array.isArray(H.thirdPartyId)?H.thirdPartyId:[]).map(ge=>se[ge]||String(ge)),ze=typeof H.humanLoop=="boolean"?H.humanLoop:null;return{id:String(Q.ruleId||Q.ruleName||P),ruleOrSeverityLabel:V,l1:{minutes:H.level1PostAssistTime??void 0,roles:Z},l2:{minutes:H.level2PostAssistTime??void 0,roles:ye},l3:{minutes:H.level3PostAssistTime??void 0,roles:Ye},actions:xt,notify:St,humanLoop:ze}});Te(J)},[Ne,t,K,se]);const fs=h.useMemo(()=>e.map(O=>({label:O.DisplayName,value:O.SeverityId})),[e]),ms=h.useMemo(()=>t.map(O=>({label:O.Name,value:O.RuleId})),[t]),ps=h.useMemo(()=>ce.map(O=>({label:O.userRoleName,value:O.userRoleId})),[ce]),ys=h.useMemo(()=>[1,3,5,10,15,20,30,45,60].map(O=>({label:`${O}`,value:O})),[]);h.useEffect(()=>{let O=!1;async function J(){try{L(!0),D(null);const Q=await o.getAdminSettings();if(!O&&Q){const P=Gt(Q.sortBy);f(P),y(P),j(!1)}}catch(Q){if(!O){const P=Q instanceof Error?Q.message:"Failed to load admin settings";D(P)}}finally{O||L(!1)}}return J(),()=>{O=!0}},[]),h.useEffect(()=>{if(!I)return;const O=V=>{const H=Number(V);return!isNaN(H)&&H>0?H:void 0},J=V=>{const H=Number(V);return!isNaN(H)&&H>0?H:void 0},P=(Ne||[]).find(V=>V?.ruleId===I||V?.ruleName===I||V?.RuleId===I)?.escalationSettings;if(P&&typeof P=="object"){ee(J(P.level1PostAssistTime)),k(O(P.level1UserRoleId)),g(J(P.level2PostAssistTime)),u(O(P.level2UserRoleId)),N(J(P.level3PostAssistTime)),R(O(P.level3UserRoleId));const V=Array.isArray(P.escalationSettingsActionTypeIds)?P.escalationSettingsActionTypeIds:[];q(V.map(H=>String(H))),M(Array.isArray(P.thirdPartyId)?P.thirdPartyId:[]),X(!!P.humanLoop)}},[Y,I,Ne]);const gs=async()=>{try{De(!0);const O=await a.getRules(),J=Array.isArray(O)?O:Array.isArray(O?.data)?O.data:[];gt(J);const Q=J.map((P,V)=>{const H=t.find(we=>we.RuleId===(P.ruleId||P.ruleName))?.Name||P.ruleName||P.Name||"-",Z=P.escalationSettings||{},ye=typeof Z.level1UserRoleId=="number"&&Z.level1UserRoleId>0?[Z.level1UserRoleId]:[],Ye=typeof Z.level2UserRoleId=="number"&&Z.level2UserRoleId>0?[Z.level2UserRoleId]:[],vt=typeof Z.level3UserRoleId=="number"&&Z.level3UserRoleId>0?[Z.level3UserRoleId]:[],bt=(Array.isArray(Z.escalationSettingsActionTypeIds)?Z.escalationSettingsActionTypeIds:[]).map(we=>K[we]||String(we)),ze=(Array.isArray(Z.thirdPartyId)?Z.thirdPartyId:[]).map(we=>se[we]||String(we)),ge=typeof Z.humanLoop=="boolean"?Z.humanLoop:null;return{id:String(P.ruleId||P.ruleName||V),ruleOrSeverityLabel:H,l1:{minutes:Z.level1PostAssistTime??void 0,roles:ye},l2:{minutes:Z.level2PostAssistTime??void 0,roles:Ye},l3:{minutes:Z.level3PostAssistTime??void 0,roles:vt},actions:bt,notify:ze,humanLoop:ge}});Te(Q)}catch(O){console.error("Failed to refetch entries",O)}finally{De(!1)}};h.useEffect(()=>{let O=!1;return(async()=>{try{const J=await a.getLookups();if(O||!J)return;const Q={};if(Array.isArray(J.thirdParties))for(const V of J.thirdParties)typeof V.thirdPartyId=="number"&&(Q[V.thirdPartyId]=V.thirdPartyName);de(Q);const P=Array.isArray(J.userRoles)?J.userRoles.map(V=>({userRoleId:V.userRoleId??V.id,userRoleName:V.userRoleName??V.name})):[];O||We(P.length?P:s||[])}catch(J){console.error("Error loading lookups",J)}})(),()=>{O=!0}},[]);const vs=async()=>{A(!0);try{const O=await o.setAdminSettings({sortBy:l,groupBy:"string"});O?.responseStatus&&O?.data&&ne.toast.success(O.data),y(l),j(!1)}catch(O){console.error("Error saving admin settings",O)}finally{A(!1)}},xs=()=>{f(b),j(!1)},bs=async()=>{oe(!0),i?.({ruleId:I,levels:[{minutes:T,role:re},{minutes:v,role:S},{minutes:x,role:E}],actions:F,thirdPartyIds:B,humanLoop:W});try{if(I){const Q=Array.isArray(F)?F.map(ye=>Number(ye)):[],P=(Ne||[]).find(ye=>ye?.ruleId===I||ye?.ruleName===I||ye?.RuleId===I),V=typeof P?.recordId=="number"?P.recordId:void 0;if(!P||typeof V!="number"){ne.toast.error("Unable to find rule recordId for update");return}const H={...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:re??0,level1PostAssistTime:T??0,level2UserRoleId:S??0,level2PostAssistTime:v??0,level3UserRoleId:E??0,level3PostAssistTime:x??0,escalationSettingsActionTypeIds:Q,thirdPartyId:Array.isArray(B)?B:[],humanLoop:W}},Z=await a.updateRule(V,H);if(Z?.responseStatus||Z?.ok||Z){ne.toast.success("Escalation settings saved"),await gs(),w(void 0),ee(void 0),k(void 0),g(void 0),u(void 0),N(void 0),R(void 0),q([]),M([]),X(!1);return}}}catch(Q){console.error("Error saving escalation settings",Q)}finally{oe(!1)}const J=t.find(Q=>Q.RuleId===I)?.Name||"-";Te(Q=>[...Q,{id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,ruleOrSeverityLabel:J,l1:{minutes:T,roles:re?[re]:[]},l2:{minutes:v,roles:S?[S]:[]},l3:{minutes:x,roles:E?[E]:[]},actions:(Array.isArray(F)?F:[]).map(P=>{const V=Number(P);return K[V]||String(P)}),notify:(Array.isArray(B)?B:[]).map(P=>se[P]||String(P)),humanLoop:!!W}])},Ss=()=>{f("By Severity"),m("By severity"),z("rules"),G(void 0),w(void 0),ee(void 0),k(void 0),g(void 0),u(void 0),N(void 0),R(void 0),q([]),M([]),X(!1)};return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"mb-6",children:[n.jsx(Qt,{level:4,className:"!mb-2",children:"Admin Settings"}),n.jsxs(c.Spin,{spinning:U,children:[$?n.jsxs("div",{className:"text-sm text-red-600 mb-2",children:["Failed to load settings: ",$]}):null,n.jsx(Vr,{sortBy:l,groupBy:d,onChange:O=>{O.sortBy&&(f(O.sortBy),j(!0)),O.groupBy&&(m(O.groupBy),j(!0))},showActions:C,onSave:vs,onClear:xs,saving:p})]})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsxs("div",{children:[n.jsx(Qt,{level:4,className:"!mb-4",children:"Escalation Settings"}),n.jsx(Jr,{escBasis:Y,setEscBasis:z,selectedSeverity:_,setSelectedSeverity:G,selectedRule:I,setSelectedRule:w,severityOptions:fs,ruleOptions:ms,minsOptions:ys,roleOptions:ps,l1mins:T,setL1mins:ee,l1role:re,setL1role:k,l2mins:v,setL2mins:g,l2role:S,setL2role:u,l3mins:x,setL3mins:N,l3role:E,setL3role:R,actions:F,setActions:q,thirdPartyIds:B,setThirdPartyIds:M,humanLoop:W,setHumanLoop:X,onClear:Ss,onSave:bs,saving:Ke,onActionTypesLoaded:O=>{const J={};for(const Q of O)typeof Q.actionTypeId=="number"&&(J[Q.actionTypeId]=Q.name);te(J)}})]}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(Xr,{entries:Pe,userRoles:ce,loading:Re,onEdit:O=>{z("rules");const J=Pe.find(P=>P.id===O),Q=t.find(P=>P.RuleId===O)||(J?t.find(P=>P.Name===J.ruleOrSeverityLabel):void 0);w(Q?Q.RuleId:O)}}),n.jsx(c.Divider,{className:"my-6"}),n.jsx(os,{userRoles:ce,rules:t,rawRules:r}),n.jsx(c.Divider,{})]})}const{Title:_t,Text:Be}=c.Typography;function cs({severities:e,rules:t,onSave:s,onCancel:r}){const{rules:i,alerts:a}=fe(),o=[{label:"By Severity",value:"By Severity"},{label:"By Created Date",value:"By Created Date"}],[l,f]=h.useState("By Severity"),[d,m]=h.useState(new Set),[b,y]=h.useState(null),[C,j]=h.useState(null),[p,A]=h.useState({inApp:!1,sms:!1,email:!1}),[U,L]=h.useState([]),[$,D]=h.useState(!0),[Y,z]=h.useState(!1);h.useEffect(()=>{let I=!1;return(async()=>{try{const w=await a.getPreferenceSettings();if(I||!w)return;A({inApp:!!w.inApp,sms:!!w.sms,email:!!w.email});const T=Gt(w.sortBy);f(T==="By Created Date"?"By Created Date":"By Severity"),y(It(w.doNotDisturbStart)),j(It(w.doNotDisturbEnd)),Array.isArray(w.anomalyIds)&&m(new Set(w.anomalyIds.map(ee=>String(ee))))}catch(w){console.error("Error in loading my preferences: ",w)}})(),()=>{I=!0}},[]),h.useEffect(()=>{let I=!1;return(async()=>{try{D(!0);const w=await i.getLookups();if(I||!w)return;const T=Array.isArray(w.anomalies)?w.anomalies:[];L(T)}catch(w){console.error("Failed to load anomalies lookups",w)}finally{I||D(!1)}})(),()=>{I=!0}},[]);const _=I=>{m(w=>{const T=new Set(w);return T.has(I)?T.delete(I):T.add(I),T})},G=async()=>{s?.({sortBy:l,subscribedRuleIds:Array.from(d),dnd:{from:b,to:C},channels:p});try{z(!0);const I=b?b.format?.("HH:mm:ss")??"00:00:00":"00:00:00",w=C?C.format?.("HH:mm:ss")??"00:00:00":"00:00:00",T=Array.from(d).map(re=>Number(re)).filter(re=>Number.isFinite(re)),ee=await a.setPreferenceSettings({anomalyIds:T,doNotDisturbStart:I,doNotDisturbEnd:w,inApp:!!p.inApp,sms:!!p.sms,email:!!p.email,sortBy:l});console.log("resp",ee),ee?.responseStatus&&ne.toast.success(ee?.data||"Preferences updated successfully.")}catch(I){console.error("Error in saving my preferences: ",I)}finally{z(!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(Be,{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(_t,{level:5,className:"!mb-2",children:"Anomalies"}),$?n.jsx("div",{className:"py-4",children:n.jsx(c.Spin,{})}):n.jsx(c.Space,{direction:"vertical",size:10,className:"w-full",children:(Array.isArray(U)?U:[]).map(I=>{const w=String(I.recordId),T=I.anomalyName;return n.jsx(c.Checkbox,{checked:d.has(w),onChange:()=>_(w),children:T},w)})})]}),n.jsxs("div",{className:"mb-4",children:[n.jsx(_t,{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(Be,{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(Be,{children:"From"}),n.jsx(c.TimePicker,{value:b,onChange:I=>y(I),format:"HH:mm"})]}),n.jsxs(c.Space,{direction:"horizontal",size:8,className:"items-center",children:[n.jsx(Be,{children:"To"}),n.jsx(c.TimePicker,{value:C,onChange:I=>j(I),format:"HH:mm"})]})]})]})})}),n.jsxs(c.Row,{gutter:[24,12],children:[n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.inApp,onChange:I=>A({...p,inApp:I.target.checked}),children:"In-app"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.sms,onChange:I=>A({...p,sms:I.target.checked}),children:"SMS"})}),n.jsx(c.Col,{children:n.jsx(c.Checkbox,{checked:p.email,onChange:I=>A({...p,email:I.target.checked}),children:"Email"})})]})]}),n.jsx(c.Divider,{}),n.jsxs(c.Space,{className:"gap-3",children:[n.jsx(c.Button,{onClick:r,disabled:Y,children:"Cancel"}),n.jsx(c.Button,{type:"primary",onClick:G,loading:Y,children:"Save"})]})]})}function us({severities:e,rules:t,userRoles:s,rawRules:r}){const[i,a]=h.useState("global");return n.jsxs("div",{className:"w-full",children:[n.jsxs("div",{className:"inline-flex rounded-xl overflow-hidden border border-gray-200 mb-4",children:[n.jsx("button",{onClick:()=>a("global"),className:`px-5 py-2 text-base font-medium outline-none ${i==="global"?" bg-black text-white":" bg-white text-black"}`,style:{border:"0"},children:"Global Settings"}),n.jsx("button",{onClick:()=>a("prefs"),className:`px-5 py-2 text-base font-medium outline-none ${i==="prefs"?"bg-black text-white":"bg-white"}`,children:"My Preferences"})]}),i==="global"?n.jsx(ls,{severities:e,rules:t,userRoles:s,rawRules:r}):n.jsx(cs,{severities:e,rules:t})]})}const en="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAIZSURBVHgBnZW/b9NAFMe/z3H6i1ZNJUBFQsL/QQkLCFBtRhhKF1ibhBmpXbtgFlYqsTG0gRGWwgAjMb8EYmjYGN0pCCrVVaX+SBxf37PiqHWcOu5Xsux79+6j77vz3RH66IbdsDTQPCFngmBwqMCPBwVXoe204Fd/2ZfrSWMpHrDshtGCvsY9FlKkFNYD+Es/7EtuX+itp1sLnLrScTWoPMYsfnty/lUPtAOs4syiUgQOoWHJpG9kdBiX11Z+UaZCk1YT+vOzACuzYxgf7hZbyBGvhTi9af+7SkQbyKi7M8N4ZJ5D+eU2dg9UN07KvyNOS8io6UkNFXMMj1/vnACKAuTmNXZpIqME+LF+iIbX7ukjkClODWTQw+ujuGYMYfXzXnICbxSBDrxAUvYDhkrZp6ggUC8+sDI7mpj9YmESb3/uJ5Z9TJ5A3eORvzsBpgs6lufGT2TKPNY3fbxh6Knis0FTSjnx+LP3u5DJicDi/t7MCFadPaRJQTl02/5vKcKnpITluYkwrWjksebs48Pvg3SoUkXtq32hxt+1pITI8Zc/zcGACN59ty/WdWnklV5ukZ+49wU8MUJIF3mBGlqUr3Dv1+wpl20v9UuP75pElyrgc3XK7UJFbLvK4DJiv9ggDmWcjO9G4imWvW00yV/hjvtpOFnpQOVLkcO+0EhyevGrROG1ol1hREFc8ZGxyddIje+v9c4i9+gI5z7MozLxclgAAAAASUVORK5CYII=",tn="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAKeSURBVHgBjVVdbtpAEJ5ZmygPfTBSaVWpUt0bwFuURgJOUG5QeoLACbw+QeAEwA3SGxgJokh9CDeI+xSpTRU/Imw8nbFZx6QQGAl5d2fm229+dkDYI2f6oaUAOwhWExBcPnL4FwFBSLCexpCMf+qPi12++PKgpR/cGOwRa1pwQIjgOoWkf6s/hOVzVd588R+/xWjf5YAY8Y0+ErQrZFfnXg3lK3uGm7A+RISOxfbit5NprqBxxgBoeEIVHehqtI9lSz+5McaaITaA2J17bycFaBayMOS8IaT+zHuv4Ui58P9oAvB4Ga0paUgqbFGswL5idIcIx3P9DCiXrQB7iJawcTiCkMMIUlj7Jo8zr6Yv/EfRXXIqRnzUxnP9u46Id8Q5Sslq3+pqWErHAPKqvxROC/ZMuJwKJ8bkPouUkrYUqgt5IgMDKAxfAYT8nAZnmR2A5J47YSjrFKyOYpZN2SiIJ8YjRqVfASyAFVg9s2F2gXwRsClMXdnYcFpq5PyiQ8KEilaywc79+aEow2i7fdCF46SIpuTvCGi2kWSXjCM4QqS4Zl3yjwQ0UySwrBfGRJNjQKW4ZrmEpL45CxUDTGWdgmoZgxOoDA6zxYgr7ZudhWk3x6Sp4kl0nZmgujQhcH5Cvqy/Hxi5hdL+dgsWxR2rma4FkLeDw+PMM243+t2YB0jDDI9nMBquyWqI3tjmLYguQfqDzxebty/DIcnePr9jfePVfDhSzv2/Hs8LAY3kMmFfTCl+rl3uu1GWF6Jx+X3vkpa+58jeeNyXvY3Pd8N+a0hvgK9ge3hMTmG5CPTnSICWcFpXaDfZUcAck99yOnZM/id3hcmAFV/hgEilU6p0TcH2gpZYS98xc/kXUJ8YImPFzfeLh0cgXbMp8n/yD3ySPZSK0MWKAAAAAElFTkSuQmCC";function sn(e){const t=(e.status||"").toLowerCase()==="completed"?n.jsx("img",{src:en,alt:"completed",style:{width:20,height:20}}):n.jsx("img",{src:tn,alt:"pending",style:{width:20,height:20}});return{title:n.jsxs("div",{className:"flex flex-col gap-0 min-w-0",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("span",{className:"block text-sm break-words mb-1 overflow-visible whitespace-normal",children:n.jsx("b",{children:e.title})}),e.description?n.jsx("span",{className:"text-gray-500 text-xs",children:e.description}):null]}),e.timestamp?n.jsx("span",{className:"text-gray-500 text-xs",children:e.timestamp}):null]}),icon:t,description:null}}function rn({data:e}){return n.jsx("div",{className:"w-full",children:n.jsx(c.Tabs,{type:"card",items:[{key:"action",label:"Action Taken",children:n.jsxs("div",{className:"w-full",children:[n.jsx(c.Card,{className:"mb-4 rounded-md",bordered:!0,children:n.jsxs("div",{className:"grid grid-cols-4 gap-6 text-xs",children:[n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Alert ID"}),n.jsx("span",{className:"text-black",children:e.summary.alertNumber})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Incident ID"}),n.jsx("span",{className:"text-black",children:e.summary.incidentId})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Severity"}),n.jsx("span",{className:"text-black",children:e.summary.severity})]}),n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsx("span",{className:"text-gray-500",children:"Location"}),n.jsx("span",{className:"text-black",children:e.summary.location})]})]})}),n.jsxs(c.Card,{className:"rounded-md",bordered:!0,children:[n.jsx("div",{className:"flex items-center justify-between",children:n.jsx("h4",{className:"text-sm text-black font-medium",children:"Response Timeline/ Audit trail/log"})}),n.jsx("div",{className:"mt-2",children:n.jsx(c.Steps,{direction:"vertical",size:"small",current:1,items:(e.timeline||[]).map(sn)})})]})]})},{key:"notification",label:"Notification Sent",children:n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(e.notifications||[]).map((t,s)=>n.jsxs(c.Card,{className:"rounded-md p-4",bordered:!0,children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("h4",{className:"text-sm text-black font-medium",children:t.channelLabel}),n.jsx("span",{className:"text-xs text-gray-500 mt-1",children:t.sentAt})]}),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)=>n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex flex-col",children:[n.jsx("span",{className:"text-black",children:r.name}),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."})]})}]})})}function nn(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 an(e){const t=(e?.mediaType||e?.type||"").toString().toLowerCase();return t==="video"||t==="mp4"?!0:nn(e?.mediaUrl||e)}function Xe(e){const t=e;return t?Array.isArray(t)?t:[t]:[]}const on={Critical:"#FF3B30",High:"#FFB86A",Medium:"#FFCC00",Low:"#007AFF"},ln={Critical:"#FFE2E2",High:"#FF95004D",Medium:"#FEF9C2",Low:"#E0EDFF"},cn=({isModalOpen:e,handleModalClose:t,selectedRow:s,fetchAlertLogs:r,alertStatusList:i=[],alertStatusLoading:a=!1,initialTab:o="details"})=>{const[l,f]=h.useState(),[d,m]=h.useState(""),[b,y]=h.useState(!1),C=h.useRef(null),[j,p]=h.useState("details"),[A,U]=h.useState(void 0),[L,$]=h.useState(!1),D=pt(),{alerts:Y,config:z}=fe(),_=z?.tenant==="schools",G=s?.originalData||{},{eventName:I,alertId:w,timestamp:T,description:ee,spaceName:re,assignTeam:k,priority:v,statusType:g,id:S,alertDetails:u,statusHistory:x,mediaDetails:N,alertNumber:E}=G,R=!_&&typeof G?.anomalyName=="string"&&String(G?.anomalyName||"").toLowerCase().includes("elopement");h.useEffect(()=>{const M=S;if(j!=="track"||!M)return;let W=!1;return(async()=>{try{const X=await Y.getAlertNotifications(M);if(W)return;const K=new Map;(X||[]).forEach(se=>{const de=String(se?.notificationType||"Unknown"),ce=K.get(de)||[];ce.push(se),K.set(de,ce)});const te=Array.from(K.entries()).map(([se,de])=>{const ce=de.map(oe=>{const Re=String(oe?.messageStatus||"").toLowerCase(),De=Re==="delivered"?"Delivered":Re==="failed"?"Failed":"Queued";return{name:oe?.receipientName||oe?.recipientName||"-",role:oe?.receipientRoleName||"",phone:oe?.receipentPhoneNumber||oe?.recipientPhoneNumber||oe?.receipientEmail||oe?.recipientEmail||"",status:De}}),We=ce.filter(oe=>oe.status==="Delivered").length,Pe=de.map(oe=>oe?.sentAt).filter(Boolean).sort((oe,Re)=>new Date(Re).getTime()-new Date(oe).getTime())[0],Te=de[0]||{},Ke=[Te?.severityName,Te?.anomalyName].filter(Boolean).join(" - ")||`${se} Notification`;return{channelLabel:`${se} Notification`,sentAt:Pe||"",messageTitle:Ke,messageBody:"",total:ce.length,delivered:We,recipients:ce}});U(te)}catch{U(void 0)}})(),()=>{W=!0}},[j,S]),h.useEffect(()=>{e&&p(o)},[e,o]);const F=(i||[]).map(M=>({value:M.value,label:M.statusName})),q=async()=>{try{y(!0);const M={alertUniqueId:w,alertId:S,status:l!==void 0?String(l):void 0,notes:d.trim(),modifiedBy:0},W=await D.mutateAsync(M);if(W?.responseStatus){const X=W?.data||"Alert updated successfully.";ne.toast.success(X,{autoClose:1500,onClose:()=>{r(),t()}}),f(void 0),m("")}else{const X=W?.errorMessage||"Failed to update alert status";ne.toast.error(X)}}catch(M){console.error("Error updating alert status:",M),ne.toast.error("Failed to update alert status. Please try again.")}finally{y(!1)}},B=async()=>{try{if(!S){ne.toast.error("Alert ID is missing.");return}$(!0);const M=S;if(!Y.notifyFamilyMembers){ne.toast.error("Notify Family is not supported.");return}const W=await Y.notifyFamilyMembers(M);if(W?.responseStatus){const X=W?.data||"Alert Notifications sent to Family Members.";ne.toast.success(X)}else{const X=W?.errorMessage||"Failed to send notifications.";ne.toast.error(X)}}catch(M){console.error("Error notifying family members:",M),ne.toast.error("Failed to send notifications. Please try again.")}finally{$(!1)}};return n.jsx(c.Modal,{open:e,onCancel:t,width:1e3,footer:j==="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:q,loading:b,children:b?"Saving...":"Save Changes"})]}):null,children:s&&n.jsx(c.Tabs,{activeKey:j,onChange:M=>p(M),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:I||"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: ",Je(T)]}),n.jsxs("div",{className:"font-sm text-gray-500",children:[n.jsx("b",{className:"text-black text-sm/6",children:"Description:"})," ",ee||"No description available"]}),re&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Space: ",re]}),k&&n.jsxs("div",{className:"font-sm text-gray-500",children:["Assigned to: ",k]}),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 ${on[String(v)]||"#DFE4EA"}`,backgroundColor:ln[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(g||"").toLowerCase()==="completed"?{background:"#E7F6EC",border:"0.68px solid var(--Green, #34C759)"}:{background:"#E0EDFF",border:"1px solid var(--Grays-Gray-4, #D1D1D6)"},children:["Status: ",g||"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:M=>f(M),value:l,options:F,loading:a})}),n.jsxs("div",{className:"flex flex-col gap-2 mt-3",children:[n.jsx("label",{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:M=>m(M.target.value)})]}),R&&n.jsxs("div",{className:"border border-[#DFE4EA] rounded-md px-4 py-2 flex flex-row justify-between items-center mt-4 mb-8",children:[n.jsx("label",{className:"text-xs font-medium",children:"Alert notification will be sent to all Family Members."}),n.jsx(c.Button,{loading:L,onClick:B,disabled:L,className:"bg-black text-white rounded-md px-4 py-2 text-xs disabled:opacity-60 disabled:cursor-not-allowed",children:"Notify Family"})]})]})})]}),n.jsx("div",{className:"flex flex-col gap-4",children:n.jsxs("div",{className:"w-full mt-1",children:[n.jsxs("div",{className:"w-full flex items-center justify-between",children:[n.jsx("h3",{className:"text-black font-bold text-sm",children:"Camera Footage"}),Xe(N).length?n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>C.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(Oe.LeftOutlined,{style:{fontSize:12}})}),n.jsx("button",{type:"button",onClick:()=>C.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(Oe.RightOutlined,{style:{fontSize:12}})})]}):null]}),Xe(N).length?n.jsx("div",{className:"w-full",children:n.jsx(c.Carousel,{ref:C,dots:!0,className:"w-full",children:Xe(N).map((M,W)=>n.jsxs("div",{className:"flex justify-center items-center",children:[an(M)?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:M.mediaUrl||M}),"Your browser does not support the video tag."]}):n.jsx("img",{src:M.mediaUrl||M,alt:M.caption||`media-${W}`,className:"max-w-full max-h-[90vh] object-contain rounded-lg shadow-lg"}),M.caption&&n.jsx("p",{className:"text-xs text-gray-500 mt-1",children:M.caption})]},W))})}):null]})})]})},{key:"track",label:"Track Incident",children:(()=>{const M={alertId:w??S??"",incidentId:"-",severity:v||"",location:re||"",alertNumber:E??""},W=x&&x.length?x.map(K=>({status:(K?.status||K?.eventStatus||"").toLowerCase()==="completed"?"Completed":"Inprogress",title:K?.status||K?.eventStatus||"Status Update",description:K?.description||K?.actionNotes||"",timestamp:K?.createdDate?`${Je(K?.createdDate)}`:K?.timestamp?`${Je(K?.timestamp)}`:""})):[],X={summary:M,timeline:W,notifications:A??[]};return n.jsx(rn,{data:X})})()}]})})};function ds(){const{alerts:e}=fe(),t=mt({queryKey:["alerts","statusList"],queryFn:()=>e.getAlertStatusList(),staleTime:5*6e4});return{list:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function yt({alerts:e,loading:t=!1,columns:s,onRefetch:r}){const[i,a]=h.useState(!1),[o,l]=h.useState(null),[f,d]=h.useState("details"),{list:m,loading:b}=ds();function y(p,A){l(p),d(A?.tab??"details"),a(!0)}function C(){a(!1)}const j=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(as,{label:"USA",timeZone:"America/New_York"})]}),n.jsx(c.Tabs,{defaultActiveKey:"active",className:"w-full",tabBarStyle:{fontSize:"medium"},onChange:p=>{p==="active"&&r?.()},items:[{key:"active",label:"Active",children:n.jsx(lt,{data:e,loading:t,pageSize:10,columns:s||[],onAlertIdClick:y,onRefetch:r})},{key:"archived",label:"Archived",children:n.jsx(is,{alerts:e,loading:t,columns:s||[],onAlertIdClick:y})},{key:"settings",label:"Settings",children:n.jsx(un,{})}]}),n.jsx(cn,{isModalOpen:i,handleModalClose:C,selectedRow:j,fetchAlertLogs:()=>{},alertStatusList:m,alertStatusLoading:b,initialTab:f})]})}function un(){const[e,t]=h.useState([]),[s,r]=h.useState([]),[i,a]=h.useState([]),{rules:o}=fe();return h.useEffect(()=>{let l=!0;return(async()=>{try{const f=await o.getRules();if(!l)return;a(Array.isArray(f)?f:[]);const d=(f||[]).map((m,b)=>({RuleId:m.ruleId||m.ruleName||String(b),Name:m.ruleName||m.Name||"-",Description:m.ruleDesc||m.Description||"",SeverityId:0}));t(d.length?d:ke.rules);try{const m=await o.getLookups(),b=Array.isArray(m?.userRoles)?m.userRoles.map(y=>({userRoleId:y.userRoleId??y.id,userRoleName:y.userRoleName??y.name})):[];r(b.length?b:ke.userRoles)}catch{r(ke.userRoles)}}catch{t(ke.rules),r(ke.userRoles)}})(),()=>{l=!1}},[]),n.jsx(us,{severities:ke.severities,rules:e,userRoles:s,rawRules:i})}function hs(){const{alerts:e}=fe(),t=mt({queryKey:["alerts","list"],queryFn:()=>e.listAlerts(),staleTime:3e4});return{alerts:t.data??[],loading:t.isLoading,error:t.error,refetch:t.refetch}}function dn(e){const{alerts:t,loading:s,refetch:r}=hs();return n.jsx(yt,{alerts:t,loading:s,columns:e.columns,onRefetch:r})}function hn({tenant:e,apiDomain:t,rulesDomain:s,headers:r,alerts:i,loading:a,columns:o}){const[l]=h.useState(()=>new Cr),f=h.useMemo(()=>({alertsBaseUrl:t,rulesBaseUrl:s||t,headers:r||void 0}),[t,s,r]);return n.jsx(Ir,{client:l,children:n.jsx(Yt,{tenant:e,override:f,children:Array.isArray(i)?n.jsx(yt,{alerts:i,loading:!!a,columns:o}):n.jsx(dn,{columns:o})})})}function fn(e){const{alerts:t}=fe(),s=mt({queryKey:["alerts","report",e],queryFn:()=>t.getAlertsReport(e),staleTime:6e4});return{data:s.data??[],loading:s.isLoading,error:s.error,refetch:s.refetch}}const mn=[{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=os;exports.AlertConsole=yt;exports.AlertConsoleWidget=hn;exports.AlertsTable=lt;exports.ApiProvider=Yt;exports.ArchivedTable=is;exports.Clock=as;exports.DataTable=zt;exports.MyPreferencesPanel=cs;exports.SettingsPanel=ls;exports.SettingsTabs=us;exports.exampleAlertColumns=mn;exports.useAlertStatusList=ds;exports.useAlerts=hs;exports.useAlertsReport=fn;exports.useApi=fe;exports.useUpdateAlertStatus=pt;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|