@veltdev/sdk-staging 6.0.8 → 6.0.9-beta.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.
Files changed (55) hide show
  1. package/app/models/element/comment-element.model.d.ts +19 -2
  2. package/{chunk-UQI5JFMO.js → chunk-3ORHWUHZ.js} +1 -1
  3. package/{chunk-O64Y7CY5.js → chunk-5R5ZQKPN.js} +1 -1
  4. package/{chunk-JKLS6423.js → chunk-6RWQRJ7Z.js} +1 -1
  5. package/{chunk-QYY5QDZZ.js → chunk-7RRXZUH7.js} +1 -1
  6. package/{chunk-H3AESJRG.js → chunk-AJXYT2YT.js} +1 -1
  7. package/{chunk-PDOET6TG.js → chunk-AOHWVH4J.js} +1 -1
  8. package/{chunk-4BWTKX3J.js → chunk-BJRSXB3P.js} +1 -1
  9. package/{chunk-3T53AUKI.js → chunk-CFLYO4ZJ.js} +1 -1
  10. package/{chunk-MVFPB6P2.js → chunk-CI2SH5RY.js} +1 -1
  11. package/{chunk-GDYKECHB.js → chunk-CQX575C2.js} +1 -1
  12. package/{chunk-SHXQBB7N.js → chunk-EQBACTBQ.js} +1 -1
  13. package/{chunk-OK6SKS5O.js → chunk-F36WWKDQ.js} +1 -1
  14. package/{chunk-FKN5MCLS.js → chunk-F44SU3DK.js} +1 -1
  15. package/{chunk-UUEOTEBS.js → chunk-F4PYCUAT.js} +1 -1
  16. package/{chunk-KPCULYW2.js → chunk-F6CKB7IS.js} +1 -1
  17. package/{chunk-MUZB4ZRW.js → chunk-FUYX2CTL.js} +1 -1
  18. package/{chunk-23YNPJA6.js → chunk-IBGPKEZW.js} +1 -1
  19. package/{chunk-7AHH7XWM.js → chunk-ID3E7CBZ.js} +1 -1
  20. package/{chunk-CQ2PFN5H.js → chunk-IU25BW6T.js} +1 -1
  21. package/{chunk-QHAOMKNT.js → chunk-JHMDMOHO.js} +1 -1
  22. package/{chunk-23Y35Q3J.js → chunk-PSVE75CB.js} +1 -1
  23. package/{chunk-E2Q3RJVJ.js → chunk-QTF4Y24I.js} +1 -1
  24. package/{chunk-3QB54TU3.js → chunk-RLD74EXO.js} +1 -1
  25. package/{chunk-2N7F6RD7.js → chunk-SY46UNW5.js} +1 -1
  26. package/{chunk-6AS4UBOQ.js → chunk-SYSCTHS4.js} +1 -1
  27. package/{chunk-4ZVKEG33.js → chunk-TW7O56QU.js} +1 -1
  28. package/{chunk-PPWVFIE5.js → chunk-UKJTOZK4.js} +1 -1
  29. package/{chunk-4EV2AXDK.js → chunk-VKGZ33MA.js} +1 -1
  30. package/{chunk-ABE26DFY.js → chunk-VMW7PJFD.js} +1 -1
  31. package/{chunk-ZWTASV4Q.js → chunk-VMY3F7K3.js} +1 -1
  32. package/{chunk-TVHRQJC4.js → chunk-WFO2GRDO.js} +1 -1
  33. package/{chunk-S7J3GTUB.js → chunk-XISY42XO.js} +1 -1
  34. package/{chunk-F7UEUUNI.js → chunk-ZJH32HDL.js} +1 -1
  35. package/package.json +1 -1
  36. package/velt-activity-log.js +1 -1
  37. package/velt-area.js +1 -1
  38. package/velt-arrow.js +1 -1
  39. package/velt-comment.js +7 -7
  40. package/velt-crdt.js +1 -1
  41. package/velt-cursor.js +1 -1
  42. package/velt-huddle.js +1 -1
  43. package/velt-live-state-sync.js +1 -1
  44. package/velt-notification.js +1 -1
  45. package/velt-presence.js +1 -1
  46. package/velt-reaction.js +1 -1
  47. package/velt-recorder.js +1 -1
  48. package/velt-rewriter.js +1 -1
  49. package/velt-selection.js +1 -1
  50. package/velt-tag.js +1 -1
  51. package/velt-user-invite.js +1 -1
  52. package/velt-user-request.js +1 -1
  53. package/velt-video-player.js +1 -1
  54. package/velt-views.js +1 -1
  55. package/velt.js +5 -5
@@ -1 +1 @@
1
- import{a as Jt}from"./chunk-TVHRQJC4.js";import{a as kt}from"./chunk-3QB54TU3.js";import{$ as G,$e as W,Ai as Ht,Bf as nt,Bi as tt,Cf as x,Ch as j,Df as yt,Dh as q,E as P,Ed as mt,Ee as z,Ef as at,Fh as $t,Fi as _t,G as L,Gi as it,Hh as Mt,Hi as et,J as _,Ki as ft,L as Y,M as rt,Mi as ot,Ni as Yt,O as dt,Od as St,Oi as Gt,Pi as Wt,Qf as bt,Rf as Dt,Sh as Rt,T as I,Uf as Ct,Uh as wt,Vf as Ut,W as ht,Yf as At,a as y,af as k,b as E,be as vt,bg as Tt,ca as S,cg as ct,da as ut,g as T,hg as J,ii as Q,ji as Ft,ki as X,l as N,li as Pt,oe as pt,oi as zt,p as H,q as st,qh as Et,qi as xt,r as D,si as Bt,ti as Z,uf as Nt,ui as Lt,v,vi as jt,w as V,xh as lt,xi as Vt,yf as It,zf as Ot,zh as K,zi as gt}from"./chunk-4EV2AXDK.js";var Kt=(()=>{let U=class U{constructor(t,i,e,o,s,n,r){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=s,this.notificationResolverService=n,this.serviceBook=r,this.serviceBook.set(Mt,this)}getUserIdsToResolveFromNotifications(t){try{let i=new Set;for(let e of t){let{notification:o}=e;switch(o?.actionUser?.userId&&i.add(o?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.recipientUser?.userId),o?.notificationSource){case"comment":if(o?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let n of s)i.add(n)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.notification?.targetAnnotationId),e=t?.raw?.targetAnnotationData?.commentId,o=i?.comments?.[e]?.commentText,s=i?.comments?.[e]?.commentHtml;return o&&s&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=s),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),t}}mergeLocationWithNotification(t,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let e=t?.notification?.notificationSourceData?.location?.id,o=t?.notification?.notificationSourceData?.metadata?.documentId;if(!e||!o)return t;let s=i?.[o]?.[e];return s&&(t.notification.notificationSourceData.location=s?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=s?.location)),t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",e),t}}mergeNotificationWithUser(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=t;if(i?.actionUser?.userId){let e=this.usersService.getUserById(i?.actionUser?.userId);e&&(i.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);e&&(i.displayHeadlineMessageTemplateData.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);e&&(i.displayHeadlineMessageTemplateData.recipientUser=e)}return i?.notificationSource==="comment"&&i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),t}}formatNotification(t,i){try{switch(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData);break;case"recorder":this.serviceBook.get(Rt)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),t}}getTargetAnnotationIdsFromNotifications(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(t).forEach(e=>{e?.notification?.targetAnnotationId&&e?.raw?.notificationSource==="comment"&&i.push(e.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return T(this,arguments,function*({data:t}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let e="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield Tt(t,e)}catch(e){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",e),t}})}getCustomNotificationIdsToResolve(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let i=new Set,e=Array.isArray(t)?t:Object.values(t||{});for(let o of e)if(o?.raw?.notificationSource==="custom"){let s=o?.notification?.id||o?.notificationId;s&&i.add(s)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",i),[]}}mergeResolvedNotificationData(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||t?.raw?.notificationSource!=="custom")return t;let i=t?.notification?.id||t?.notificationId;if(!i)return t;let e=this.notificationResolverService.getNotificationById(i);if(!e)return t;let o=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let s of o)e[s]!==void 0&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]));return Object.keys(e).forEach(s=>{!o.includes(s)&&s!=="notificationId"&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};U.\u0275fac=function(i){return new(i||U)(S(et),S(X),S(it),S(Z),S(tt),S(ot),S(Q))},U.\u0275prov=G({token:U,factory:U.\u0275fac,providedIn:"root"});let R=U;return R})();function qt(R){if(typeof R!="number"||!Number.isFinite(R))return 25;let t=Math.floor(R);return t<1?25:Math.min(200,t)}var xi=(()=>{let U=class U{constructor(t,i,e,o,s,n,r,a,c,l,g,f,h,d,m,b,A,M,O,C,w){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=s,this.commonDbUtilsService=n,this.commentUtilsService=r,this.commentAnnotationsResolverService=a,this.notificationResolverService=c,this.databaseService=l,this.docService=g,this.domService=f,this.iamService=h,this.loggingService=d,this.notificationUtilsService=m,this.usersService=b,this.functions=A,this.userPermissionService=M,this.coreActionsService=O,this.serviceBook=C,this.realtimeAdapter=w,this.endpointsService=ut(zt),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new N([]),this.rawNotificationsByIdMap$=new N(new Map),this.processedNotifications$=new N([]),this.userNotificationsFromServer$=new N(null),this.readNotificationsOnForYouTab$=new N(!1),this.currentDocumentOnly$=new N(!1),this.notificationViews$=new N({}),this.notificationsByIdMap$=new N(new Map),this.historyPanelVisible$=new N(!1),this.notificationsForYou$=new N(null),this.notificationsByDocumentIdMap$=new N(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new N(null),this.maxNotificationDays$=new N(15),this.tabConfig$=new N({people:{enable:!1}}),this.settingsConfig$=new N(null),this.setSettingsConfigByOrganization$=new N(!1),this.muteAllNotifications$=new N(!1),this.enableSettings$=new N(!1),this.selfNotifications$=new N(!1),this.userScopedNotifications$=new N({enabled:!1,limit:25}),this.settingsInitialConfig$=new N([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.settingsConfigGeneration=0,this.notificationsPanelVisible$=new N(!1),this.crossOrganizationConfig$=new N({enabled:!1}),this.crossOrgNotifications$=new N([]),this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1,this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=0,this.CROSS_ORG_FETCH_WINDOW_MS=500,this.CROSS_ORG_PAGE_SIZE=50,this.crossOrgGeneration=0,this.crossOrgResolveRoundInFlight=!1,this.crossOrgStragglerRetryUsed=!1,this.CROSS_ORG_STRAGGLER_RETRY_MS=3e4;try{this.serviceBook.set($t,this),this.serviceBook.observe(wt).subscribe(u=>{this.commentService=u??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(P(u=>!!u),_(1)).subscribe(u=>{if(u){this.db=u;try{let p=this.configService.getProxyConfig(),$=this.endpointsService.getNotificationsDbUrl();It($)?this.notificationsDb=null:(p?.v1DbHost&&$&&($=Ot($,p.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance($),p?.v1DbHost&&$&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(p){this.loggingService.catch("Error initializing notifications DB, using default: ",p),this.notificationsDb=u}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},u=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",u)}),this.authService.getUser$().subscribe(u=>{u?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(p=>{this.notificationsByDocumentIdSubscription[p]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(u=>{if(u){let p=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(u||{}).forEach($=>{let B=p?.[$]?.notifications;B?.length&&B.forEach(F=>{this.notificationUtilsService.mergeLocationWithNotification({notification:F},u)?.notification})}),this.notificationsByDocumentIdMap$.next(p)}})}catch(u){this.loggingService.catch("Error in NotificationService constructor: ",u)}}setDBConfigDataToInitialConfig(t){try{let i=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(t||{}).forEach(([e,o])=>{i[e]=o}),this.settingsConfig$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",i)}}getInitialConfigFromDB(t){return T(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=x(this.authService.getUser()?.userId??""),o=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:t?.documentId,organizationId:t?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:e}});if(i!==this.settingsConfigGeneration)return;if(o?.notificationsConfig)this.setDBConfigDataToInitialConfig(o?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let s={};this.settingsInitialConfig$.getValue().forEach(r=>{if(r.enable){let a=r?.values?.find(c=>c.id===r.default);s[r.id]=a||r?.values?.[0]||{id:"NONE",name:"None"}}});let n={};Object.keys(s).forEach(r=>{n[r]=s[r].id}),yield this.updateSettingsConfigToDb(n)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=x(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(P(i=>i===!0),I(()=>V([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(P(([i,e,o])=>(e||!!i)&&!!o?.organizationId),I(([i,e,o])=>st(this.getInitialConfigFromDB(i)).pipe(I(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(v(s=>{s?.data?.notificationsConfig&&!J(s?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(s?.data?.notificationsConfig)})))))))).subscribe()}catch(t){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",t)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null),this.resetCrossOrgForUser()}catch(t){this.loggingService.catch("Error in NotificationService resetCacheData: ",t)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",t)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(I(()=>this.getCurrentDocumentOnly$().pipe(I(t=>t?this.docService.getDocumentPaths$().pipe(v(i=>{})):D(void 0)))),ht(()=>{this.notificationsByDocumentIdMap$.next(null)}),I(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(rt(),v(([t,i])=>{let e=t?.map(a=>a.documentId),o=i?.map(a=>a.documentId),s=e?.filter(a=>!o?.includes(a)),n=o?.map(a=>({documentId:a,timestamp:i?.find(c=>c.documentId===a)?.timestamp})).filter(a=>!e?.includes(a.documentId)),r=o?.map(a=>{let c=i?.find(l=>l.documentId===a)?.timestamp;return{documentId:a,timestamp:c}}).filter(a=>{let c=t?.find(l=>l.documentId===a.documentId)?.timestamp;return c&&a.timestamp&&c!==a.timestamp});n?.length&&this.fetchNotificationsForDocumentIds(n),r?.length&&this.fetchNotificationsForDocumentIds(r,1),s?.forEach(a=>{this.removeNotificationsForDocumentId(a)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}getDocumentIdsByLastNotificationTimestamp(t=15){try{return this.authService.getUser$().pipe(I(i=>this.docService.getOrganizationConfig$().pipe(v(e=>{let o=null,s=this.configService.getApiKey(),n=e?.organizationId||i?.organizationId,r=e?.clientOrganizationId||i?.clientOrganizationId||"";return s&&n&&(o=new ft({apiKey:s,organizationId:n})),{user:i,documentPaths:o,clientOrganizationId:r}}))),I(i=>{let{user:e,documentPaths:o,clientOrganizationId:s}=i;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return D(null);if(e&&o?.organizationNotificationsLastNotificationTimestamp){let n=new Date,r=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;n.setDate(n.getDate()-r);let a=n.getTime(),c=[Lt(gt("timestamp",">=",a),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[gt("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];this.getCurrentDocumentOnly()||(c.push(Vt("timestamp","desc")),c.push(jt(t)));let l=e?.userId??"";return st(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:s})??Promise.resolve({})).pipe(I(g=>l&&s&&g?.[l]?.organization?.[s]?.errorCode===Nt.PERMISSION_DENIED?D(null):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:o?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:c}}).pipe(v(f=>f?.data),v(f=>{let h=[];return Object.keys(f||{}).forEach(d=>{let m=this.commonDbService.shouldUseFirestore()?f[d]?.timestamp??0:f[d],b=this.commonDbService.shouldUseFirestore()?f[d]?.deletedNotification??!1:!1;if(b&&b.id&&b?.timestamp===m){let A=b.id,M=f[d]?.metadata?.documentId,O=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),C=O?.[M]??{documentMetadata:null,notifications:[]},w=C.notifications??[],u=w?.findIndex(p=>p.id===A);u!==-1&&(w.splice(u,1),this.notificationsByDocumentIdMap$.next(E(y({},O),{[M]:E(y({},C),{notifications:w})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(A)&&this.notificationResolverService.deleteNotification(A,this.docService.getDocumentPaths()?.clientOrganizationId??"")}h.push({documentId:d,timestamp:m})}),h}),L(f=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",f),D([]))))))}return D(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),D([])}}resolveAndUpdateDocumentNotifications(t,i){try{Object.keys(t).forEach(e=>{let o=t[e]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[e]||{},s;if(i==="user")s=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[e]?.notifications||[]});else if(i==="notification"){let n=t[e]?.notifications?.reduce((a,c)=>(a[c.notificationId]=c,a),{}),r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:n});s=Object.values(r??{})}else{let n=t[e]?.notifications?.reduce((a,c)=>(a[c.notificationId]=c,a),{}),r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:n});s=Object.values(r??{})}s.forEach(n=>{n.notification=this.getClientNotificationObject(n)}),this.setNotificationForDocumentIdInCache(e,o,s)})}catch(e){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",e)}}resolveAndMergeUserNotifications(t,i,e=!1){try{let o=t;if(e&&i==="comment"){let c=this.getUserNotificationsFromServer()??[],l=new Set(t.map(g=>g.notificationId));o=c.filter(g=>l.has(g.notificationId)).concat(t.filter(g=>!c.some(f=>f.notificationId===g.notificationId)))}let s=o.reduce((c,l)=>(c[l.notificationId]=l,c),{}),n;if(i==="user"){let c=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}else if(i==="notification"){let c=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}else{let c=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}n.forEach(c=>{c.notification=this.getClientNotificationObject(c)});let r=this.getUserNotificationsFromServer()??[],a=new Map(r.map(c=>[c.notificationId,c]));n.forEach(c=>{a.set(c.notificationId,c)}),this.setUserNotificationsFromServer(Array.from(a.values()))}catch(o){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",o)}}fetchNotificationsForDocumentIds(t,i=15){return T(this,null,function*(){try{if(t?.length){let e=this.docService.getOrganizationConfig()?.organizationId??"";if(!e)return[];let o=this.getStartAtTimestamp(),s={};if(t.forEach(d=>{if(d?.documentId){let m=this.getAllowedDocumentMetadataByDocumentId(d.documentId);m&&(s[d.documentId]=m)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let d=[];if(t.forEach(O=>{this.docService.getDocumentMetadata(O.documentId)||d.push(O.documentId)}),d.length){let O=this.authService.getUser(),C=q(this.functions,K({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let w=yield lt({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:O?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:d},getSdkProxy:C,userId:O?.userId??""});if(w?.data?.length){let u={};w.data.forEach(p=>{p?.documentId&&(u[p.documentId]=p)}),this.docService.setAllDocumentMetadata(y(y({},this.docService.getAllDocumentMetadataMap()),u))}}catch(w){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",w)}}let m=[],b=[];t.forEach(O=>{let C=this.docService.getDocumentMetadata(O.documentId);C?.clientDocumentId?m.push({userId:this.authService.getUser()?.userId??"",resource:y({id:C.clientDocumentId,type:k.DOCUMENT,source:W.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""},C.folderId&&{parentFolderId:C.folderId})}):b.push(O.documentId)}),b.length&&(t=t.filter(O=>!b.includes(O.documentId)));let A=Ut();this.coreActionsService.triggerAction(vt.PERMISSION_PROVIDER,{event:j.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:W.GET_NOTIFICATIONS,source:"internal",payload:{requests:m}});let M=yield this.userPermissionService?.onResourceAccessRequired({requests:m,uniqueId:A,methodName:W.GET_NOTIFICATIONS});M?.success&&M?.data?.length?M.data.forEach(O=>{!O.hasAccess&&O.resourceId&&(t=t.filter(C=>C.documentId!==yt(O.resourceId)))}):t=[]}catch(d){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",d),t=[]}let n=this.userScopedNotifications$.getValue(),r=!!n?.enabled&&i!==1&&!this.getCurrentDocumentOnly();if(!t.length&&(this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),!r))return[];let a=this.userPermissionService?.getPermissionsCache()?.filter(d=>d.type===k.CONTEXT),c=y({organizationId:e,documentIds:t.filter(d=>!!d.documentId&&!!d.timestamp).map(d=>({documentId:d.documentId,timestamp:d.timestamp??0})),timestamp:o,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:a,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},r&&{getUserNotificationsForOrganization:!0,userNotificationsLimitToLast:qt(n?.limit)}),{notificationsByDocumentId:l,userNotifications:g=[],userNotificationIdsInDocNotifications:f=[],permissionResults:h=[]}=yield this.callGetNotificationsForDocuments(c);if(this.userPermissionService?.getIsContextEnabled()){let d=[...this.userPermissionService?.getPermissionsCache()??[],...h??[]];this.userPermissionService?.setPermissionsCache(d)}if(l&&typeof l=="object"){let d=this.usersService.userDataProviderAvailable(),m=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),b=this.notificationResolverService.notificationDataProviderAvailable(),A=[],M=[],O=[];Object.keys(l).forEach((u,p)=>{let $=l[u].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[u];if($){let F=this.allowedDocumentMetadataMap$.value||{};(!F?.[u]||!J(F?.[u],$))&&this.allowedDocumentMetadataMap$.next(E(y({},F),{[u]:$}))}let B=l[u].notifications||[];B.forEach(F=>{f.includes(F.notificationId)&&!g.find(Qt=>Qt.notificationId===F.notificationId)&&g.push(JSON.parse(JSON.stringify(F))),F.notification=this.getClientNotificationObject(F)}),this.setNotificationForDocumentIdInCache(u,$,B),d&&(A.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:B,shouldAwait:!0,forceResolve:!0})),A.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:g,shouldAwait:!0,forceResolve:!0}))),m&&(M.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:B,shouldCommentAnnotationsResolverAwait:!0})),M.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:g,shouldCommentAnnotationsResolverAwait:!0}))),b&&(O.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:B,shouldNotificationResolverAwait:!0})),O.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:g,shouldNotificationResolverAwait:!0})))});let C=JSON.parse(JSON.stringify(g));if(r){let u=new Map((this.getUserNotificationsFromServer()??[]).map(p=>[p?.notificationId,p]));g.forEach(p=>u.set(p?.notificationId,p)),this.setUserNotificationsFromServer(Array.from(u.values()))}else this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...g]);(b||d||m)&&(()=>{let u=Promise.resolve();if(b&&(u=u.then(()=>Promise.allSettled(O)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"notification"),this.resolveAndMergeUserNotifications(C,"notification")})),d&&(u=u.then(()=>Promise.allSettled(A)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"user"),this.resolveAndMergeUserNotifications(C,"user")})),m){let p=b||d;u=u.then(()=>Promise.allSettled(M)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"comment"),this.resolveAndMergeUserNotifications(C,"comment",p)})}return u})().catch(u=>{this.loggingService.catch("Error in NotificationService resolveChain: ",u)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}callGetNotificationsForDocuments(t){return T(this,null,function*(){let i=q(this.functions,K({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),e=yield this.notificationUtilsService.handleNotificationEncryption({data:t}),o=yield i({veltData:e}),s=o?.data?.data?.veltData||{},n=o?.data?.data?.veltAdditionalData||{},r="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),a=yield ct(s,r),{userNotifications:c,userNotificationIdsInDocNotifications:l,permissionResults:g}=yield ct(n,r);return{notificationsByDocumentId:a,userNotifications:c,userNotificationIdsInDocNotifications:l,permissionResults:g}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,s)=>o===s.findIndex(n=>n.notificationId===e.notificationId)),this.userNotificationsFromServer$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",i)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(t,i,e,o){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",n=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),n||(n=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let r=this.notificationsByDocumentIdMap$.getValue(),a=r?.[t]?.notifications||[],c=this.docService.getLocationMetadatas(),l=e?.map(h=>{let d=h?.notification;return d?(d.metadata&&(d.metadata.documentName=i?.documentName||d.metadata.documentName,d.metadata.organizationMetadata=n||d.metadata.organizationMetadata,d.metadata.documentMetadata=i||d.metadata.documentMetadata),c&&(d=this.notificationUtilsService.mergeLocationWithNotification({notification:d},c)?.notification),d):null})?.filter(h=>!!h)||[],g=new Map(a.map(h=>[h.id,h]));l.forEach(h=>{g.set(h.id,h)});let f=Array.from(g.values()).sort((h,d)=>(d.timestamp||0)-(h.timestamp||0));this.notificationsByDocumentIdMap$.next(E(y({},r),{[t]:{notifications:f,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(t){try{this.notificationsByDocumentIdSubscription[t]&&this.notificationsByDocumentIdSubscription[t].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[t],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getStartAtTimestamp(){try{let t=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return t.setDate(t.getDate()-i),t.getTime()}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(I(t=>D(t).pipe(P(i=>!!i),v(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),s=this.notificationResolverService?.notificationDataProviderAvailable();if(s||e||o){let r=i?.reduce((a,c)=>(a[c.notificationId]=c,a),{});s&&(r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:r||[]})),e&&(r=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:r||[]})),o&&(r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:r||[]})),i=Object.values(r??{})}return i.forEach(r=>{r.notification=this.getClientNotificationObject(r)}),i.sort((r,a)=>a.timestamp-r.timestamp),i.map(r=>r.notification).filter(r=>!!r)}),I(i=>{let e={data:i?.reduce((o,s)=>(o[s.id]={notification:s},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(v(o=>Object.values(o?.data||{}).map(s=>s?.notification)))}))),I(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(v(()=>t))}),I(t=>this.allowedDocumentMetadataMap$.pipe(v(()=>t))),v(t=>(t?.length&&(t=t.map(i=>{if(i?.metadata){let e=this.docService.getOrganizationConfig()?.organizationId??"",o=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(e);o||(o=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=o||i.metadata.documentMetadata}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),D(null)}}getNotificationsForYou(){try{return V([this.getCurrentOrgNotificationsForYou(),this.crossOrgNotifications$.asObservable()]).pipe(v(([t,i])=>{let e=this.mergeCrossOrgForYou(t,i);return e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),e}))}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",t),D({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],s=a=>a?.id??a?.notificationId,n=new Set;o.forEach(a=>{let c=s(a);c!=null&&n.add(c)});let r=[...o];return e.forEach(a=>{let c=s(a);c!=null&&n.has(c)||(c!=null&&n.add(c),r.push(a))}),r.sort((a,c)=>(c?.timestamp||0)-(a?.timestamp||0))}catch(e){return this.loggingService.catch("Error in NotificationService mergeCrossOrgForYou: ",e),t}}enableCrossOrganization(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableCrossOrganization();return}this.setCrossOrganizationConfig(E(y({},t||{}),{enabled:!0})),this.crossOrgUserSubscription?this.crossOrgIndexSubscription&&(this.crossOrgInitialFetchDone=!1,this.scheduleCrossOrgFetch()):this.attachCrossOrgIndexListener()}catch(i){this.loggingService.catch("Error in NotificationService enableCrossOrganization: ",i)}}disableCrossOrganization(){try{this.teardownCrossOrg();let t=this.crossOrganizationConfig$.getValue();this.crossOrganizationConfig$.next(E(y({},t||{}),{enabled:!1}))}catch(t){this.loggingService.catch("Error in NotificationService disableCrossOrganization: ",t)}}setCrossOrganizationConfig(t){try{let i=t||{},e=Array.isArray(i.feeds)&&i.feeds.length?i.feeds:["forYou"];e.includes("all")&&this.loggingService.warn('NotificationService: cross-organization notifications only support the "forYou" feed; ignoring "all".'),e=e.filter(s=>s==="forYou"),e.length||(e=["forYou"]);let o={enabled:i.enabled??!0,organizationIds:i.organizationIds,excludeOrganizationIds:i.excludeOrganizationIds,feeds:e};this.crossOrganizationConfig$.next(o)}catch(i){this.loggingService.catch("Error in NotificationService setCrossOrganizationConfig: ",i)}}getCrossOrganizationConfig(){return this.crossOrganizationConfig$.getValue()}getCrossOrganizationConfig$(){return this.crossOrganizationConfig$.asObservable()}attachCrossOrgIndexListener(){try{this.teardownCrossOrgUserWatcher(),this.crossOrgUserSubscription=this.authService.getUser$().pipe(v(t=>t?.userId),Y(),P(t=>!!t),L(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),H))).subscribe(t=>{try{this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([]),this.bindCrossOrgListenersForUser(t)}catch(i){this.loggingService.catch("Error in NotificationService cross-org user-change handler: ",i)}})}catch(t){this.loggingService.catch("Error in NotificationService attachCrossOrgIndexListener: ",t)}}bindCrossOrgListenersForUser(t){this.crossOrgIndexSubscription=this.commonDbService.dbListener({feature:"userNotificationIndex",properties:{id:x(t),isCollection:!1,useCollectionGroup:!1}}).pipe(L(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),H))).subscribe(i=>{try{let e=this.extractIndexOrgTimestamps(i);this.crossOrgIndexTimestamps=e;let o=Object.keys(e);this.crossOrgIndexOrgs=o,this.pruneCrossOrgBufferToAllowedOrgs(),o.length&&this.scheduleCrossOrgFetch()}catch(e){this.loggingService.catch("Error in NotificationService cross-org index snapshot: ",e)}}),this.crossOrgOrgSwitchSubscription=this.docService.getOrganizationConfig$().pipe(v(i=>i?.organizationId??""),Y(),rt(),P(([i])=>!!i),L(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),H))).subscribe(()=>{this.crossOrgInitialFetchDone=!1,this.crossOrgSeenTimestamps={},this.scheduleCrossOrgFetch()})}extractIndexOrgTimestamps(t){let i={};try{let e=t?.data??t,o=e?.organizationIds??e?.orgs;return Array.isArray(o)?(o.forEach(s=>{typeof s=="string"&&s.length&&(i[s]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(s=>{if(typeof s=="string"&&s.length){let n=Number(o[s]);i[s]=Number.isFinite(n)?n:0}}),i)}catch(e){return this.loggingService.catch("Error in NotificationService extractIndexOrgTimestamps: ",e),i}}scheduleCrossOrgFetch(){try{let t=Date.now();t-this.lastCrossOrgFetchTime>=this.CROSS_ORG_FETCH_WINDOW_MS?(this.lastCrossOrgFetchTime=t,this.crossOrgFetchPending=!1,this.fetchCrossOrgUserNotifications(),this.armCrossOrgTrailingTimer()):this.crossOrgFetchPending=!0}catch(t){this.loggingService.catch("Error in NotificationService scheduleCrossOrgFetch: ",t)}}pruneCrossOrgBufferToAllowedOrgs(){try{let t=this.crossOrgNotifications$.getValue();if(!t.length)return;let i=this.crossOrgIndexOrgs||[];if(!i.length){this.crossOrgNotifications$.next([]);return}let e=t.filter(o=>i.includes(o?.metadata?.organizationId));e.length!==t.length&&this.crossOrgNotifications$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService pruneCrossOrgBufferToAllowedOrgs: ",t)}}armCrossOrgTrailingTimer(){this.crossOrgFetchTimer&&clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=setTimeout(()=>{this.crossOrgFetchPending&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())},this.CROSS_ORG_FETCH_WINDOW_MS)}toCrossOrgClientNotification(t){try{if(!t)return null;if(t.notification){let e=this.getClientNotificationObject(t);if(!e)return null;let o=t?.metadata?.organizationId??e?.metadata?.organizationId;return o!=null&&(e.metadata=E(y({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:E(y({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return T(this,null,function*(){try{if(!t?.length)return t;let i=!!this.notificationResolverService?.notificationDataProviderAvailable?.(),e=!!this.usersService?.userDataProviderAvailable?.(),o=!!this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable?.();if(!i&&!e&&!o)return t;let s=new Map;for(let r of t){let a=r?.metadata?.clientOrganizationId??r?.metadata?.organizationId??"",c=s.get(a);c?c.push(r):s.set(a,[r])}let n=[];for(let[r,a]of s){let c=a.reduce((g,f,h)=>{let d=f?.notificationId??f?.id??`__cross_org_${h}`;return g[d]=f,g},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:c,organizationId:r||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let l=c;i&&(l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l??{}})),e&&(l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l??{}})),o&&(l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l??{}})),n.push(...Object.values(l??{}))}return n}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return T(this,null,function*(){let t=this.crossOrgGeneration;if(this.crossOrgResolveRoundInFlight){this.crossOrgFetchPending=!0;return}this.crossOrgResolveRoundInFlight=!0;try{let i=this.crossOrganizationConfig$.getValue(),e=this.docService.getOrganizationConfig()?.organizationId??"",o=!this.crossOrgInitialFetchDone,s=this.crossOrgIndexTimestamps||{},n=o?[]:Object.keys(s).filter(f=>f!==e&&(s[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!n.length)return;let r=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:n}),a=yield this.callGetCrossOrgUserNotifications(r);if(t!==this.crossOrgGeneration)return;let c=Array.isArray(a?.pendingPermissionQueries)?a.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),g=!c.length||!l;if(yield this.processCrossOrgResponse(a,{fetchGeneration:t,currentOrg:e,isInitial:o,indexTimestamps:s,advanceCursors:g}),t!==this.crossOrgGeneration||g){g&&t===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry();return}yield this.runCrossOrgResolveRound(c,{fetchGeneration:t,config:i,currentOrg:e,isInitial:o,bumpedOrgs:n,indexTimestamps:s})}catch(i){this.loggingService.catch("Error in NotificationService fetchCrossOrgUserNotifications: ",i)}finally{this.crossOrgResolveRoundInFlight=!1,this.crossOrgFetchPending&&t===this.crossOrgGeneration&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())}})}runCrossOrgResolveRound(t,i){return T(this,null,function*(){try{let e=yield this.userPermissionService.resolveClientSidePermissions(t);if(i.fetchGeneration!==this.crossOrgGeneration)return;let o=this.buildCrossOrgRequestData(i.config,i.currentOrg,{isInitial:i.isInitial,bumpedOrgs:i.bumpedOrgs});o.clientResolvedResults=e;let s=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(s,{fetchGeneration:i.fetchGeneration,currentOrg:i.currentOrg,isInitial:i.isInitial,indexTimestamps:i.indexTimestamps,advanceCursors:!0}),i.fetchGeneration===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry()}catch(e){this.loggingService.catch("Error in NotificationService runCrossOrgResolveRound: ",e),this.armCrossOrgStragglerRetry(i.fetchGeneration)}})}processCrossOrgResponse(t,i){return T(this,null,function*(){if(this.userPermissionService?.getIsContextEnabled?.()&&t?.permissionResults?.length){let l=[...this.userPermissionService?.getPermissionsCache?.()??[],...t.permissionResults];this.userPermissionService?.setPermissionsCache?.(l)}let e=Array.isArray(t?.forYou)?t.forYou:[],o=this.crossOrgIndexOrgs||[],s=l=>o.includes(l),n=e.filter(l=>{let g=l?.metadata?.organizationId;if(g===i.currentOrg)return this.loggingService.log("%c[WB] Cross-org: dropping current-org echo: "+g,"color: orange;"),!1;let f=s(g);return f||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),f}),r=yield this.resolveCrossOrgSelfHostedData(n);if(i.fetchGeneration!==this.crossOrgGeneration)return;let a=r.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=a:c=this.mergeCrossOrgForYou(a,this.crossOrgNotifications$.getValue()).filter(l=>s(l?.metadata?.organizationId)),i.advanceCursors&&(Object.keys(i.indexTimestamps).forEach(l=>{this.crossOrgSeenTimestamps[l]=i.indexTimestamps[l]}),this.crossOrgInitialFetchDone=!0),this.crossOrgNotifications$.next(c)})}armCrossOrgStragglerRetry(t){this.crossOrgStragglerRetryUsed||(this.crossOrgStragglerRetryUsed=!0,this.crossOrgStragglerRetryTimer&&clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=setTimeout(()=>{this.crossOrgStragglerRetryTimer=void 0,t===this.crossOrgGeneration&&this.fetchCrossOrgUserNotifications()},this.CROSS_ORG_STRAGGLER_RETRY_MS))}clearCrossOrgStragglerRetry(){this.crossOrgStragglerRetryUsed=!1,this.crossOrgStragglerRetryTimer&&(clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=void 0)}callGetCrossOrgUserNotifications(t){return T(this,null,function*(){let i=this.authService.getUser(),e=q(this.functions,K({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield lt({methodName:"getCrossOrgUserNotifications",data:y({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},s=e?.isInitial??!0,n=e?.bumpedOrgs??[],r=Array.isArray(o.organizationIds),a=r?o.organizationIds.filter(h=>!!h).map(h=>at(h)):[],c=(o.excludeOrganizationIds||[]).filter(h=>!!h).map(h=>at(h)),l=new Set(c);i&&l.add(i);let g=this.userPermissionService?.getPermissionsCache?.()?.filter(h=>h?.type===k.CONTEXT),f={organizationId:i,excludeOrganizationIds:Array.from(l),timestamp:this.getStartAtTimestamp(),limitToLast:this.CROSS_ORG_PAGE_SIZE,isContextEnabled:this.userPermissionService?.getIsContextEnabled?.(),cachedData:g,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig?.()};if(this.userPermissionService?.isClientDevResolverActive?.()&&(f.clientResolverAvailable=!0),s)r&&(f.organizationIds=this.dedupeIncludeOrgs(a,l));else{let h=n.filter(m=>!!m&&!l.has(m));if(r){let m=new Set(a);h=h.filter(b=>m.has(b))}h=Array.from(new Set(h)),f.organizationIds=h;let d={};h.forEach(m=>{d[m]=this.crossOrgSeenTimestamps[m]??this.getStartAtTimestamp()}),f.orgTimestamps=d}return f}dedupeIncludeOrgs(t,i){let e=new Set;return t.filter(o=>o==null||i.has(o)||e.has(o)?!1:(e.add(o),!0))}teardownCrossOrgPerUserListeners(){this.crossOrgGeneration++,this.crossOrgIndexSubscription&&(this.crossOrgIndexSubscription.unsubscribe(),this.crossOrgIndexSubscription=void 0),this.crossOrgOrgSwitchSubscription&&(this.crossOrgOrgSwitchSubscription.unsubscribe(),this.crossOrgOrgSwitchSubscription=void 0),this.crossOrgFetchTimer&&(clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=void 0),this.crossOrgFetchPending=!1,this.clearCrossOrgStragglerRetry()}teardownCrossOrgUserWatcher(){this.teardownCrossOrgPerUserListeners(),this.crossOrgUserSubscription&&(this.crossOrgUserSubscription.unsubscribe(),this.crossOrgUserSubscription=void 0)}resetCrossOrgDeltaState(){this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1}resetCrossOrgForUser(){this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.getValue().length&&this.crossOrgNotifications$.next([])}teardownCrossOrg(){this.teardownCrossOrgUserWatcher(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([])}markCrossOrgEntriesRead(t){try{let i=this.crossOrgNotifications$.getValue();if(!i?.length)return;let e=new Set((t||[]).map(r=>r?.id??r?.notificationId).filter(r=>r!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),s=!1,n=o?i.filter(r=>{let a=r?.id??r?.notificationId,c=a!=null&&e.has(a);return c&&(s=!0),!c}):i.map(r=>{let a=r?.id??r?.notificationId;return a!=null&&e.has(a)&&r?.isUnread!==!1?(s=!0,E(y({},r),{isUnread:!1})):r});s&&this.crossOrgNotifications$.next(n)}catch(i){this.loggingService.catch("Error in NotificationService markCrossOrgEntriesRead: ",i)}}subscribeNotificationsData(t,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let e,o;try{if(t&&(o=nt(t)),i&&typeof i=="object"){let s=At(i);e=nt(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return this.authService.getAuthState$().pipe(P(s=>!!s),I(s=>this.isFeatureAllowed({firebaseUser:s})),I(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(v(n=>(s.featureAllowed=n,s))):D(s)),I(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),D([])):D(s).pipe(I(n=>this.docService.getDocumentPaths$().pipe(v(r=>(this.documentPaths=r,n.documentPaths=r,n)))),I(n=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(P(i=>!!i),v(i=>E(y({},t),{config:i})),I(i=>this.authService.getUser$().pipe(v(e=>E(y({},i),{user:e})))),I(i=>Ct(i.config,i.user,pt.NOTIFICATION)?D(E(y({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),D(E(y({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(P(i=>!!i),I(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let e=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(e+=`/${z.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let o=this.realtimeAdapter.rtdbRef(this.db,`${t?e+"/"+z.FIREBASE_PARTIAL_PATH_DOCS+"/"+t+"/"+z.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return this.realtimeAdapter.rtdbObjectVal$("notification",o).pipe(L(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),D(null))),v(s=>{let n=[],r=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(c=>{let l=s?.raw[c];l?.id&&n.push(l)}),n.forEach(c=>{c.id&&r.set(c.id,c)})),this.notifications$.next(n),this.rawNotificationsByIdMap$.next(r);let a=[];s?.processed&&Object.keys(s?.processed||{}).forEach(c=>{let l=s?.processed[c];l?.id&&a.push(l)}),this.processedNotifications$.next(a),this.setNotificationsByIdMap()}))}else return D(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=x(t?.email));let o;t?.userId&&(o=x(t?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(r=>{if(r.id&&r?.displayHeadlineMessageTemplate){let a=!1;(e&&r.notifyUsers?.[e]||o&&r.notifyUsers?.[o])&&(a=!0);let c={id:r.id,notificationSource:r.notificationSource,actionType:r.actionType,actionUser:r.actionUser,timestamp:r.timestamp,targetAnnotationId:r.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),forYou:a,notificationSourceData:r.notificationSourceData},l=this.getRawNotificationById(c.id);if(l?.metadata&&(c.metadata={apiKey:l.metadata.apiKey,organizationId:l.metadata.organizationId,clientOrganizationId:l.metadata.clientOrganizationId,documentId:l.metadata.documentId,clientDocumentId:l.metadata.clientDocumentId,location:l?.location,locationId:l?.locationId}),c?.notificationSource==="comment"&&c?.targetAnnotationId){let g=this.commentService?.getAnnotationById(c.targetAnnotationId);g||l?.annotationData&&(g=l.annotationData),g&&(c.notificationSourceData=this.commentService?.getCommentAnnotationForClient(g))}s.set(r.id,c)}}),s.forEach((r,a)=>{r.isUnread=r?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[a]?.views?.[t?.userSnippylyId],s.set(a,r)}),this.notificationsByIdMap$.next(s)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:s}){try{let n=this.authService.getUser(),r=s||t;if(r.id&&r?.displayHeadlineMessageTemplate&&n){let a=null;n?.email&&(a=x(n?.email));let c=null;n?.userId&&(c=x(n?.userId));let l=!1,g=!0;(a&&r.notifyUsers?.[a]||c&&r.notifyUsersByUserId?.[c])&&(l=!0),c&&o?.[c]&&(g=!1);let f={id:r.id};if(s?f=E(y(y({},f),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:l,isUnread:g}):f={id:t.id,notificationSource:t.notificationSource,actionType:t.actionType,actionUser:t.actionUser,timestamp:t.timestamp,targetAnnotationId:t.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(t),displayBodyMessage:this.getNotificationBodyMessage(t),forYou:l,isUnread:g,metadata:e},f?.notificationSource==="comment"&&f?.targetAnnotationId){let h=this.commentService?.getAnnotationById(f.targetAnnotationId);h||s?.notificationSourceData&&(h=s?.notificationSourceData),h||i?.annotationData&&(h=i.annotationData),h&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(h))}return i?.targetAnnotationData?.isCommentResolverUsed&&(f.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),s?.isNotificationResolverUsed&&(f.isNotificationResolverUsed=s.isNotificationResolverUsed),f}return}catch(n){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",n);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(v(t=>t?Object.keys(t??{}).map(i=>{let e=t[i].notifications||[],o=e.filter(n=>n.isUnread).length,s=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:s,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return V([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable(),this.getUserScopedAllTabRows$()]).pipe(v(([t,i,e])=>{let o=Array.isArray(i)?i:[],s=Array.isArray(e)?e:[],n=null;if(t&&(n=[],t.forEach(a=>{a.notifications.forEach(c=>{n?.push(c)})})),!o.length&&!s.length)return t?n.sort((a,c)=>c.timestamp-a.timestamp):null;if(!t)return null;let r=n||[];return s.length&&(r=this.mergeCrossOrgForYou(r,s)),o.length&&(r=this.mergeCrossOrgForYou(r,o)),r}))}getUserScopedAllTabRows$(){return V([this.userScopedNotifications$,this.userNotificationsFromServer$.asObservable()]).pipe(v(([t,i])=>!t?.enabled||!i?.length?[]:i.map(e=>e?.notification??this.getClientNotificationObject(e)).filter(e=>!!e)))}processNotificationData(t){try{let i=t?.annotationData?.metadata,e=this.docService.getOrganizationConfig()?.organizationId;t.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t.metadata||(t.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete t.metadata.locations,t.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t?.metadata?.documentMetadata?.clientDocumentId&&t?.metadata?.documentMetadata?.documentId&&(t.metadata.documentMetadata.documentId=t?.metadata?.documentMetadata?.clientDocumentId),delete t.metadata.documentMetadata.locations,t.metadata.organizationMetadata=JSON.parse(JSON.stringify(e?this.docService.getOrganizationMetadata(e)||{}:{})),t?.metadata?.organizationMetadata?.clientOrganizationId&&t?.metadata?.organizationMetadata?.organizationId&&(t.metadata.organizationMetadata.organizationId=t?.metadata?.organizationMetadata?.clientOrganizationId);let o=this.configService.getApiKey();t.metadata.apiKey=o,t.platform=this.configService.getSF()?"sf":"sdk",t.actionUser=this.authService.getUser();let s=i?.documentId?new ft({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=s?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=s?.clientOrganizationId||t.actionUser.clientOrganizationId);let n=this.docService.getLocation();n&&(t.location=n?.location,t.locationId=n?.locationId),this.loggingService.log(`[NOTIFICATION] ${t?.notificationSource} ${t?.actionType}`,t);let r=this.commonDbService.getServerTimestamp(),a=this.notificationUtilsService.formatNotification(t,r);return JSON.parse(JSON.stringify(a))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(t){try{if(!this.notificationsDb)return;let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=this.processNotificationData(t);try{let o=bt(t?.annotationData);if(o&&e&&typeof e=="object"){e.visibility=o;let s=Object.values(t?.annotationData?.subscribedUsers||{}).map(r=>r?.user?.userId).filter(r=>!!r),n=Dt(t?.annotationData,s);n.length&&(e.deniedForYouUsers=[...new Set([...e.deniedForYouUsers??[],...n])])}}catch(o){this.loggingService.catch("Error applying notification visibility in updateNotificationDatabase: ",o)}this.realtimeAdapter.rtdbPush("notificationIndex",i,JSON.parse(JSON.stringify(e)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(t){return this.authService.getUser$().pipe(I(i=>i?i.organizationId?this.getAllNotifications$().pipe(I(e=>this.notificationsForYou$.pipe(v(o=>{if(e||o){let s=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(n=>{n.id&&s.set(n.id,n)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(n=>{n.id&&!s.has(n.id)&&s.set(n.id,n)}),Array.from(s.values()).sort((n,r)=>(r.timestamp||0)-(n.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(v(e=>Array.from(e.values())),v(e=>e.sort((o,s)=>s.timestamp-o.timestamp)),dt()):D(null)),Y(Et))}getRawNotificationById(t){try{return this.rawNotificationsByIdMap$.getValue()?.get(t)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(t){try{this.notificationViews$.next(t),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(t){try{let i=this.authService.getUser();if(t?.displayHeadlineMessageTemplate&&t?.displayHeadlineMessageTemplateData){let e=t.displayHeadlineMessageTemplate,o=t.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,n=e.replace(s,(r,a)=>(a==="actionUser"||a==="recipientUser")&&o[a]?i?.email&&o[a].email===i?.email||i?.userId&&o[a]?.userId===i?.userId?"You":o[a].name||o[a].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':o[a]?o[a]:r);return this.domService.sanitizeHtml(n)}return this.domService.sanitizeHtml(t.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(t){try{if(t?.displayBodyMessageTemplate&&t?.displayBodyMessageTemplateData){let i=t?.displayBodyMessageTemplate;return t?.displayBodyMessageTemplateData&&t?.displayBodyMessageTemplateData?.users?.forEach(e=>{if(e?.userId){let o=this.usersService.getUserById(e?.userId);i=i?.replaceAll(`{{${e.userId}}}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),i=i?.replaceAll(`@User ${e.userId}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(t.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(t,i=!1,e=!1){try{t?document.querySelector(z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(t):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(t),t?this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(t=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(t){return T(this,null,function*(){try{let i=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(t?.length){for(let n=0;n<t.length;n+=50){let a=t.slice(n,n+50).filter(g=>g?.id),c=a.map(g=>this.setNotificationAsRead({notification:g,userNotifications:JSON.parse(JSON.stringify(i))})),l=yield Promise.all(c);a.forEach((g,f)=>{let h=l[f];if(!h.some(m=>m.notificationId===g.id))i=i.filter(m=>m.notificationId!==g.id);else{let m=i.find(A=>A.notificationId===g.id),b=h.find(A=>A.notificationId===g.id);m&&b?.views&&(m.views=b.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(n=>{let r=n.metadata?.documentId;if(r&&o?.[r]){let a=o?.[r]?.notifications||[],c=a.find(l=>l.id===n.id);c&&(c.isUnread=!1),o[r].notifications=a}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!J(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return T(this,null,function*(){try{if(t?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(_(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(v(t=>t?.filter(e=>e?.isUnread)?.length??null),I(t=>this.getNotifications$().pipe(v(i=>{let e=i?.filter(o=>o?.isUnread)?.length??null;return{forYou:t,all:e}}))))}catch(t){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",t),D({forYou:null,all:null})}}setNotificationAsRead(e){return T(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let s=x(o?.userId),{metadata:n}=t;if(n){let{apiKey:r,organizationId:a,documentId:c}=n;if(r&&a&&c&&s){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:a,documentId:c,apiKey:r}});l?.notificationId&&(l?.views?.[s]||(l.views||(l.views={}),l.views[s]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:a,documentId:c,apiKey:r},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:a}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:a}}),i=i.filter(f=>f.notificationId!==t.id);else if(!g?.views?.[s]){g.views||(g.views={}),g.views[s]={timestamp:Date.now()};let f=i.find(h=>h.notificationId===t.id);f&&(f.views=g.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:t.id,userId:s,documentId:c,organizationId:a},data:g})}}}}}return i}catch(o){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",o),i}})}setMaxDays(t){try{t>0?this.maxNotificationDays$.next(t):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(t){try{t&&this.tabConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",t)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",t)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(t){return T(this,null,function*(){try{this.getNotifications$().pipe(_(1)).subscribe(i=>{if(i){let e=i.filter(o=>o.id===t);this.setNotificationsAsRead(e)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(t){try{return this.allowedDocumentMetadataMap$.value?.[t]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(t){try{this.enableSettings$.value&&this.settingsConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(t){try{this.enableSettings$.value&&(this.settingsConfig$.next(t),this.updateSettingsConfigToDb())}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",t)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettings: ",t)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",t)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",t)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",t)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",t)}}enableUserScopedNotifications(t){try{this.userScopedNotifications$.next({enabled:!0,limit:qt(t?.limit)})}catch(i){this.loggingService.catch("Error in NotificationService enableUserScopedNotifications: ",i)}}disableUserScopedNotifications(){try{this.userScopedNotifications$.value.enabled!==!1&&this.userScopedNotifications$.next({enabled:!1,limit:this.userScopedNotifications$.value.limit})}catch(t){this.loggingService.catch("Error in NotificationService disableUserScopedNotifications: ",t)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettings: ",t)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(t){try{let i=!1;if(t.forEach(e=>{["email","inbox"].includes(e.id)&&(i=!e.values?.every(o=>["ALL","NONE","MINE"].includes(o.id)))}),i){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",i)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(t){return T(this,null,function*(){try{let i=this.authService.getUser(),e=x(i?.userId??""),o=this.docService.getDocumentPaths(),s=this.docService.getOrganizationConfig(),n=o?.organizationId??s?.organizationId,r=o?.clientOrganizationId??s?.clientOrganizationId,a={apiKey:this.configService.getApiKey(),organizationId:n,documentId:o?.documentId,clientOrganizationId:r,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:r??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:o?.documentId,userId:e},data:{id:o?.documentId,notificationsConfig:t||this.settingsConfig$.getValue(),metadata:a}})))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",t)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",t)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};U.\u0275fac=function(i){return new(i||U)(S(mt),S(Ft),S(Z),S(Pt),S(Wt),S(Yt),S(et),S(tt),S(ot),S(Ht),S(_t),S(Bt),S(kt),S(X),S(Kt),S(it),S(St),S(Jt),S(xt),S(Q),S(Gt))},U.\u0275prov=G({token:U,factory:U.\u0275fac,providedIn:"root"});let R=U;return R})();export{Kt as a,xi as b};
1
+ import{a as Jt}from"./chunk-WFO2GRDO.js";import{a as kt}from"./chunk-RLD74EXO.js";import{$ as G,$e as W,Ai as Ht,Bf as nt,Bi as tt,Cf as x,Ch as j,Df as yt,Dh as q,E as P,Ed as mt,Ee as z,Ef as at,Fh as $t,Fi as _t,G as L,Gi as it,Hh as Mt,Hi as et,J as _,Ki as ft,L as Y,M as rt,Mi as ot,Ni as Yt,O as dt,Od as St,Oi as Gt,Pi as Wt,Qf as bt,Rf as Dt,Sh as Rt,T as I,Uf as Ct,Uh as wt,Vf as Ut,W as ht,Yf as At,a as y,af as k,b as E,be as vt,bg as Tt,ca as S,cg as ct,da as ut,g as T,hg as J,ii as Q,ji as Ft,ki as X,l as N,li as Pt,oe as pt,oi as zt,p as H,q as st,qh as Et,qi as xt,r as D,si as Bt,ti as Z,uf as Nt,ui as Lt,v,vi as jt,w as V,xh as lt,xi as Vt,yf as It,zf as Ot,zh as K,zi as gt}from"./chunk-VKGZ33MA.js";var Kt=(()=>{let U=class U{constructor(t,i,e,o,s,n,r){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=s,this.notificationResolverService=n,this.serviceBook=r,this.serviceBook.set(Mt,this)}getUserIdsToResolveFromNotifications(t){try{let i=new Set;for(let e of t){let{notification:o}=e;switch(o?.actionUser?.userId&&i.add(o?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.recipientUser?.userId),o?.notificationSource){case"comment":if(o?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let n of s)i.add(n)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.notification?.targetAnnotationId),e=t?.raw?.targetAnnotationData?.commentId,o=i?.comments?.[e]?.commentText,s=i?.comments?.[e]?.commentHtml;return o&&s&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=s),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),t}}mergeLocationWithNotification(t,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let e=t?.notification?.notificationSourceData?.location?.id,o=t?.notification?.notificationSourceData?.metadata?.documentId;if(!e||!o)return t;let s=i?.[o]?.[e];return s&&(t.notification.notificationSourceData.location=s?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=s?.location)),t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",e),t}}mergeNotificationWithUser(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=t;if(i?.actionUser?.userId){let e=this.usersService.getUserById(i?.actionUser?.userId);e&&(i.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);e&&(i.displayHeadlineMessageTemplateData.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);e&&(i.displayHeadlineMessageTemplateData.recipientUser=e)}return i?.notificationSource==="comment"&&i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),t}}formatNotification(t,i){try{switch(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData);break;case"recorder":this.serviceBook.get(Rt)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),t}}getTargetAnnotationIdsFromNotifications(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(t).forEach(e=>{e?.notification?.targetAnnotationId&&e?.raw?.notificationSource==="comment"&&i.push(e.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return T(this,arguments,function*({data:t}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let e="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield Tt(t,e)}catch(e){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",e),t}})}getCustomNotificationIdsToResolve(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let i=new Set,e=Array.isArray(t)?t:Object.values(t||{});for(let o of e)if(o?.raw?.notificationSource==="custom"){let s=o?.notification?.id||o?.notificationId;s&&i.add(s)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",i),[]}}mergeResolvedNotificationData(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||t?.raw?.notificationSource!=="custom")return t;let i=t?.notification?.id||t?.notificationId;if(!i)return t;let e=this.notificationResolverService.getNotificationById(i);if(!e)return t;let o=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let s of o)e[s]!==void 0&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]));return Object.keys(e).forEach(s=>{!o.includes(s)&&s!=="notificationId"&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};U.\u0275fac=function(i){return new(i||U)(S(et),S(X),S(it),S(Z),S(tt),S(ot),S(Q))},U.\u0275prov=G({token:U,factory:U.\u0275fac,providedIn:"root"});let R=U;return R})();function qt(R){if(typeof R!="number"||!Number.isFinite(R))return 25;let t=Math.floor(R);return t<1?25:Math.min(200,t)}var xi=(()=>{let U=class U{constructor(t,i,e,o,s,n,r,a,c,l,g,f,h,d,m,b,A,M,O,C,w){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=s,this.commonDbUtilsService=n,this.commentUtilsService=r,this.commentAnnotationsResolverService=a,this.notificationResolverService=c,this.databaseService=l,this.docService=g,this.domService=f,this.iamService=h,this.loggingService=d,this.notificationUtilsService=m,this.usersService=b,this.functions=A,this.userPermissionService=M,this.coreActionsService=O,this.serviceBook=C,this.realtimeAdapter=w,this.endpointsService=ut(zt),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new N([]),this.rawNotificationsByIdMap$=new N(new Map),this.processedNotifications$=new N([]),this.userNotificationsFromServer$=new N(null),this.readNotificationsOnForYouTab$=new N(!1),this.currentDocumentOnly$=new N(!1),this.notificationViews$=new N({}),this.notificationsByIdMap$=new N(new Map),this.historyPanelVisible$=new N(!1),this.notificationsForYou$=new N(null),this.notificationsByDocumentIdMap$=new N(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new N(null),this.maxNotificationDays$=new N(15),this.tabConfig$=new N({people:{enable:!1}}),this.settingsConfig$=new N(null),this.setSettingsConfigByOrganization$=new N(!1),this.muteAllNotifications$=new N(!1),this.enableSettings$=new N(!1),this.selfNotifications$=new N(!1),this.userScopedNotifications$=new N({enabled:!1,limit:25}),this.settingsInitialConfig$=new N([{name:"Inbox",id:"inbox",default:"ALL",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]},{name:"Email",id:"email",default:"MINE",enable:!0,values:[{name:"All",id:"ALL"},{name:"Only Involved",id:"MINE"},{name:"None",id:"NONE"}]}]),this.settingsConfigGeneration=0,this.notificationsPanelVisible$=new N(!1),this.crossOrganizationConfig$=new N({enabled:!1}),this.crossOrgNotifications$=new N([]),this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1,this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=0,this.CROSS_ORG_FETCH_WINDOW_MS=500,this.CROSS_ORG_PAGE_SIZE=50,this.crossOrgGeneration=0,this.crossOrgResolveRoundInFlight=!1,this.crossOrgStragglerRetryUsed=!1,this.CROSS_ORG_STRAGGLER_RETRY_MS=3e4;try{this.serviceBook.set($t,this),this.serviceBook.observe(wt).subscribe(u=>{this.commentService=u??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(P(u=>!!u),_(1)).subscribe(u=>{if(u){this.db=u;try{let p=this.configService.getProxyConfig(),$=this.endpointsService.getNotificationsDbUrl();It($)?this.notificationsDb=null:(p?.v1DbHost&&$&&($=Ot($,p.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance($),p?.v1DbHost&&$&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(p){this.loggingService.catch("Error initializing notifications DB, using default: ",p),this.notificationsDb=u}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},u=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",u)}),this.authService.getUser$().subscribe(u=>{u?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(p=>{this.notificationsByDocumentIdSubscription[p]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(u=>{if(u){let p=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(u||{}).forEach($=>{let B=p?.[$]?.notifications;B?.length&&B.forEach(F=>{this.notificationUtilsService.mergeLocationWithNotification({notification:F},u)?.notification})}),this.notificationsByDocumentIdMap$.next(p)}})}catch(u){this.loggingService.catch("Error in NotificationService constructor: ",u)}}setDBConfigDataToInitialConfig(t){try{let i=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(t||{}).forEach(([e,o])=>{i[e]=o}),this.settingsConfig$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",i)}}getInitialConfigFromDB(t){return T(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=x(this.authService.getUser()?.userId??""),o=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:t?.documentId,organizationId:t?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:e}});if(i!==this.settingsConfigGeneration)return;if(o?.notificationsConfig)this.setDBConfigDataToInitialConfig(o?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let s={};this.settingsInitialConfig$.getValue().forEach(r=>{if(r.enable){let a=r?.values?.find(c=>c.id===r.default);s[r.id]=a||r?.values?.[0]||{id:"NONE",name:"None"}}});let n={};Object.keys(s).forEach(r=>{n[r]=s[r].id}),yield this.updateSettingsConfigToDb(n)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=x(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(P(i=>i===!0),I(()=>V([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(P(([i,e,o])=>(e||!!i)&&!!o?.organizationId),I(([i,e,o])=>st(this.getInitialConfigFromDB(i)).pipe(I(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(v(s=>{s?.data?.notificationsConfig&&!J(s?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(s?.data?.notificationsConfig)})))))))).subscribe()}catch(t){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",t)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null),this.resetCrossOrgForUser()}catch(t){this.loggingService.catch("Error in NotificationService resetCacheData: ",t)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",t)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(I(()=>this.getCurrentDocumentOnly$().pipe(I(t=>t?this.docService.getDocumentPaths$().pipe(v(i=>{})):D(void 0)))),ht(()=>{this.notificationsByDocumentIdMap$.next(null)}),I(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(rt(),v(([t,i])=>{let e=t?.map(a=>a.documentId),o=i?.map(a=>a.documentId),s=e?.filter(a=>!o?.includes(a)),n=o?.map(a=>({documentId:a,timestamp:i?.find(c=>c.documentId===a)?.timestamp})).filter(a=>!e?.includes(a.documentId)),r=o?.map(a=>{let c=i?.find(l=>l.documentId===a)?.timestamp;return{documentId:a,timestamp:c}}).filter(a=>{let c=t?.find(l=>l.documentId===a.documentId)?.timestamp;return c&&a.timestamp&&c!==a.timestamp});n?.length&&this.fetchNotificationsForDocumentIds(n),r?.length&&this.fetchNotificationsForDocumentIds(r,1),s?.forEach(a=>{this.removeNotificationsForDocumentId(a)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}getDocumentIdsByLastNotificationTimestamp(t=15){try{return this.authService.getUser$().pipe(I(i=>this.docService.getOrganizationConfig$().pipe(v(e=>{let o=null,s=this.configService.getApiKey(),n=e?.organizationId||i?.organizationId,r=e?.clientOrganizationId||i?.clientOrganizationId||"";return s&&n&&(o=new ft({apiKey:s,organizationId:n})),{user:i,documentPaths:o,clientOrganizationId:r}}))),I(i=>{let{user:e,documentPaths:o,clientOrganizationId:s}=i;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return D(null);if(e&&o?.organizationNotificationsLastNotificationTimestamp){let n=new Date,r=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;n.setDate(n.getDate()-r);let a=n.getTime(),c=[Lt(gt("timestamp",">=",a),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[gt("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];this.getCurrentDocumentOnly()||(c.push(Vt("timestamp","desc")),c.push(jt(t)));let l=e?.userId??"";return st(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:s})??Promise.resolve({})).pipe(I(g=>l&&s&&g?.[l]?.organization?.[s]?.errorCode===Nt.PERMISSION_DENIED?D(null):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:o?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:c}}).pipe(v(f=>f?.data),v(f=>{let h=[];return Object.keys(f||{}).forEach(d=>{let m=this.commonDbService.shouldUseFirestore()?f[d]?.timestamp??0:f[d],b=this.commonDbService.shouldUseFirestore()?f[d]?.deletedNotification??!1:!1;if(b&&b.id&&b?.timestamp===m){let A=b.id,M=f[d]?.metadata?.documentId,O=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),C=O?.[M]??{documentMetadata:null,notifications:[]},w=C.notifications??[],u=w?.findIndex(p=>p.id===A);u!==-1&&(w.splice(u,1),this.notificationsByDocumentIdMap$.next(E(y({},O),{[M]:E(y({},C),{notifications:w})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(A)&&this.notificationResolverService.deleteNotification(A,this.docService.getDocumentPaths()?.clientOrganizationId??"")}h.push({documentId:d,timestamp:m})}),h}),L(f=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",f),D([]))))))}return D(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),D([])}}resolveAndUpdateDocumentNotifications(t,i){try{Object.keys(t).forEach(e=>{let o=t[e]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[e]||{},s;if(i==="user")s=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[e]?.notifications||[]});else if(i==="notification"){let n=t[e]?.notifications?.reduce((a,c)=>(a[c.notificationId]=c,a),{}),r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:n});s=Object.values(r??{})}else{let n=t[e]?.notifications?.reduce((a,c)=>(a[c.notificationId]=c,a),{}),r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:n});s=Object.values(r??{})}s.forEach(n=>{n.notification=this.getClientNotificationObject(n)}),this.setNotificationForDocumentIdInCache(e,o,s)})}catch(e){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",e)}}resolveAndMergeUserNotifications(t,i,e=!1){try{let o=t;if(e&&i==="comment"){let c=this.getUserNotificationsFromServer()??[],l=new Set(t.map(g=>g.notificationId));o=c.filter(g=>l.has(g.notificationId)).concat(t.filter(g=>!c.some(f=>f.notificationId===g.notificationId)))}let s=o.reduce((c,l)=>(c[l.notificationId]=l,c),{}),n;if(i==="user"){let c=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}else if(i==="notification"){let c=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}else{let c=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}n.forEach(c=>{c.notification=this.getClientNotificationObject(c)});let r=this.getUserNotificationsFromServer()??[],a=new Map(r.map(c=>[c.notificationId,c]));n.forEach(c=>{a.set(c.notificationId,c)}),this.setUserNotificationsFromServer(Array.from(a.values()))}catch(o){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",o)}}fetchNotificationsForDocumentIds(t,i=15){return T(this,null,function*(){try{if(t?.length){let e=this.docService.getOrganizationConfig()?.organizationId??"";if(!e)return[];let o=this.getStartAtTimestamp(),s={};if(t.forEach(d=>{if(d?.documentId){let m=this.getAllowedDocumentMetadataByDocumentId(d.documentId);m&&(s[d.documentId]=m)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let d=[];if(t.forEach(O=>{this.docService.getDocumentMetadata(O.documentId)||d.push(O.documentId)}),d.length){let O=this.authService.getUser(),C=q(this.functions,K({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let w=yield lt({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:O?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:d},getSdkProxy:C,userId:O?.userId??""});if(w?.data?.length){let u={};w.data.forEach(p=>{p?.documentId&&(u[p.documentId]=p)}),this.docService.setAllDocumentMetadata(y(y({},this.docService.getAllDocumentMetadataMap()),u))}}catch(w){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",w)}}let m=[],b=[];t.forEach(O=>{let C=this.docService.getDocumentMetadata(O.documentId);C?.clientDocumentId?m.push({userId:this.authService.getUser()?.userId??"",resource:y({id:C.clientDocumentId,type:k.DOCUMENT,source:W.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""},C.folderId&&{parentFolderId:C.folderId})}):b.push(O.documentId)}),b.length&&(t=t.filter(O=>!b.includes(O.documentId)));let A=Ut();this.coreActionsService.triggerAction(vt.PERMISSION_PROVIDER,{event:j.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:A,methodName:W.GET_NOTIFICATIONS,source:"internal",payload:{requests:m}});let M=yield this.userPermissionService?.onResourceAccessRequired({requests:m,uniqueId:A,methodName:W.GET_NOTIFICATIONS});M?.success&&M?.data?.length?M.data.forEach(O=>{!O.hasAccess&&O.resourceId&&(t=t.filter(C=>C.documentId!==yt(O.resourceId)))}):t=[]}catch(d){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",d),t=[]}let n=this.userScopedNotifications$.getValue(),r=!!n?.enabled&&i!==1&&!this.getCurrentDocumentOnly();if(!t.length&&(this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),!r))return[];let a=this.userPermissionService?.getPermissionsCache()?.filter(d=>d.type===k.CONTEXT),c=y({organizationId:e,documentIds:t.filter(d=>!!d.documentId&&!!d.timestamp).map(d=>({documentId:d.documentId,timestamp:d.timestamp??0})),timestamp:o,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:a,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},r&&{getUserNotificationsForOrganization:!0,userNotificationsLimitToLast:qt(n?.limit)}),{notificationsByDocumentId:l,userNotifications:g=[],userNotificationIdsInDocNotifications:f=[],permissionResults:h=[]}=yield this.callGetNotificationsForDocuments(c);if(this.userPermissionService?.getIsContextEnabled()){let d=[...this.userPermissionService?.getPermissionsCache()??[],...h??[]];this.userPermissionService?.setPermissionsCache(d)}if(l&&typeof l=="object"){let d=this.usersService.userDataProviderAvailable(),m=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),b=this.notificationResolverService.notificationDataProviderAvailable(),A=[],M=[],O=[];Object.keys(l).forEach((u,p)=>{let $=l[u].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[u];if($){let F=this.allowedDocumentMetadataMap$.value||{};(!F?.[u]||!J(F?.[u],$))&&this.allowedDocumentMetadataMap$.next(E(y({},F),{[u]:$}))}let B=l[u].notifications||[];B.forEach(F=>{f.includes(F.notificationId)&&!g.find(Qt=>Qt.notificationId===F.notificationId)&&g.push(JSON.parse(JSON.stringify(F))),F.notification=this.getClientNotificationObject(F)}),this.setNotificationForDocumentIdInCache(u,$,B),d&&(A.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:B,shouldAwait:!0,forceResolve:!0})),A.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:g,shouldAwait:!0,forceResolve:!0}))),m&&(M.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:B,shouldCommentAnnotationsResolverAwait:!0})),M.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:g,shouldCommentAnnotationsResolverAwait:!0}))),b&&(O.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:B,shouldNotificationResolverAwait:!0})),O.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:g,shouldNotificationResolverAwait:!0})))});let C=JSON.parse(JSON.stringify(g));if(r){let u=new Map((this.getUserNotificationsFromServer()??[]).map(p=>[p?.notificationId,p]));g.forEach(p=>u.set(p?.notificationId,p)),this.setUserNotificationsFromServer(Array.from(u.values()))}else this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...g]);(b||d||m)&&(()=>{let u=Promise.resolve();if(b&&(u=u.then(()=>Promise.allSettled(O)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"notification"),this.resolveAndMergeUserNotifications(C,"notification")})),d&&(u=u.then(()=>Promise.allSettled(A)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"user"),this.resolveAndMergeUserNotifications(C,"user")})),m){let p=b||d;u=u.then(()=>Promise.allSettled(M)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"comment"),this.resolveAndMergeUserNotifications(C,"comment",p)})}return u})().catch(u=>{this.loggingService.catch("Error in NotificationService resolveChain: ",u)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}callGetNotificationsForDocuments(t){return T(this,null,function*(){let i=q(this.functions,K({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),e=yield this.notificationUtilsService.handleNotificationEncryption({data:t}),o=yield i({veltData:e}),s=o?.data?.data?.veltData||{},n=o?.data?.data?.veltAdditionalData||{},r="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),a=yield ct(s,r),{userNotifications:c,userNotificationIdsInDocNotifications:l,permissionResults:g}=yield ct(n,r);return{notificationsByDocumentId:a,userNotifications:c,userNotificationIdsInDocNotifications:l,permissionResults:g}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,s)=>o===s.findIndex(n=>n.notificationId===e.notificationId)),this.userNotificationsFromServer$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",i)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(t,i,e,o){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",n=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),n||(n=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let r=this.notificationsByDocumentIdMap$.getValue(),a=r?.[t]?.notifications||[],c=this.docService.getLocationMetadatas(),l=e?.map(h=>{let d=h?.notification;return d?(d.metadata&&(d.metadata.documentName=i?.documentName||d.metadata.documentName,d.metadata.organizationMetadata=n||d.metadata.organizationMetadata,d.metadata.documentMetadata=i||d.metadata.documentMetadata),c&&(d=this.notificationUtilsService.mergeLocationWithNotification({notification:d},c)?.notification),d):null})?.filter(h=>!!h)||[],g=new Map(a.map(h=>[h.id,h]));l.forEach(h=>{g.set(h.id,h)});let f=Array.from(g.values()).sort((h,d)=>(d.timestamp||0)-(h.timestamp||0));this.notificationsByDocumentIdMap$.next(E(y({},r),{[t]:{notifications:f,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(t){try{this.notificationsByDocumentIdSubscription[t]&&this.notificationsByDocumentIdSubscription[t].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[t],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getStartAtTimestamp(){try{let t=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return t.setDate(t.getDate()-i),t.getTime()}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(I(t=>D(t).pipe(P(i=>!!i),v(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),s=this.notificationResolverService?.notificationDataProviderAvailable();if(s||e||o){let r=i?.reduce((a,c)=>(a[c.notificationId]=c,a),{});s&&(r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:r||[]})),e&&(r=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:r||[]})),o&&(r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:r||[]})),i=Object.values(r??{})}return i.forEach(r=>{r.notification=this.getClientNotificationObject(r)}),i.sort((r,a)=>a.timestamp-r.timestamp),i.map(r=>r.notification).filter(r=>!!r)}),I(i=>{let e={data:i?.reduce((o,s)=>(o[s.id]={notification:s},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(v(o=>Object.values(o?.data||{}).map(s=>s?.notification)))}))),I(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(v(()=>t))}),I(t=>this.allowedDocumentMetadataMap$.pipe(v(()=>t))),v(t=>(t?.length&&(t=t.map(i=>{if(i?.metadata){let e=this.docService.getOrganizationConfig()?.organizationId??"",o=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(e);o||(o=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=o||i.metadata.documentMetadata}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),D(null)}}getNotificationsForYou(){try{return V([this.getCurrentOrgNotificationsForYou(),this.crossOrgNotifications$.asObservable()]).pipe(v(([t,i])=>{let e=this.mergeCrossOrgForYou(t,i);return e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),e}))}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",t),D({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],s=a=>a?.id??a?.notificationId,n=new Set;o.forEach(a=>{let c=s(a);c!=null&&n.add(c)});let r=[...o];return e.forEach(a=>{let c=s(a);c!=null&&n.has(c)||(c!=null&&n.add(c),r.push(a))}),r.sort((a,c)=>(c?.timestamp||0)-(a?.timestamp||0))}catch(e){return this.loggingService.catch("Error in NotificationService mergeCrossOrgForYou: ",e),t}}enableCrossOrganization(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableCrossOrganization();return}this.setCrossOrganizationConfig(E(y({},t||{}),{enabled:!0})),this.crossOrgUserSubscription?this.crossOrgIndexSubscription&&(this.crossOrgInitialFetchDone=!1,this.scheduleCrossOrgFetch()):this.attachCrossOrgIndexListener()}catch(i){this.loggingService.catch("Error in NotificationService enableCrossOrganization: ",i)}}disableCrossOrganization(){try{this.teardownCrossOrg();let t=this.crossOrganizationConfig$.getValue();this.crossOrganizationConfig$.next(E(y({},t||{}),{enabled:!1}))}catch(t){this.loggingService.catch("Error in NotificationService disableCrossOrganization: ",t)}}setCrossOrganizationConfig(t){try{let i=t||{},e=Array.isArray(i.feeds)&&i.feeds.length?i.feeds:["forYou"];e.includes("all")&&this.loggingService.warn('NotificationService: cross-organization notifications only support the "forYou" feed; ignoring "all".'),e=e.filter(s=>s==="forYou"),e.length||(e=["forYou"]);let o={enabled:i.enabled??!0,organizationIds:i.organizationIds,excludeOrganizationIds:i.excludeOrganizationIds,feeds:e};this.crossOrganizationConfig$.next(o)}catch(i){this.loggingService.catch("Error in NotificationService setCrossOrganizationConfig: ",i)}}getCrossOrganizationConfig(){return this.crossOrganizationConfig$.getValue()}getCrossOrganizationConfig$(){return this.crossOrganizationConfig$.asObservable()}attachCrossOrgIndexListener(){try{this.teardownCrossOrgUserWatcher(),this.crossOrgUserSubscription=this.authService.getUser$().pipe(v(t=>t?.userId),Y(),P(t=>!!t),L(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),H))).subscribe(t=>{try{this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([]),this.bindCrossOrgListenersForUser(t)}catch(i){this.loggingService.catch("Error in NotificationService cross-org user-change handler: ",i)}})}catch(t){this.loggingService.catch("Error in NotificationService attachCrossOrgIndexListener: ",t)}}bindCrossOrgListenersForUser(t){this.crossOrgIndexSubscription=this.commonDbService.dbListener({feature:"userNotificationIndex",properties:{id:x(t),isCollection:!1,useCollectionGroup:!1}}).pipe(L(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),H))).subscribe(i=>{try{let e=this.extractIndexOrgTimestamps(i);this.crossOrgIndexTimestamps=e;let o=Object.keys(e);this.crossOrgIndexOrgs=o,this.pruneCrossOrgBufferToAllowedOrgs(),o.length&&this.scheduleCrossOrgFetch()}catch(e){this.loggingService.catch("Error in NotificationService cross-org index snapshot: ",e)}}),this.crossOrgOrgSwitchSubscription=this.docService.getOrganizationConfig$().pipe(v(i=>i?.organizationId??""),Y(),rt(),P(([i])=>!!i),L(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),H))).subscribe(()=>{this.crossOrgInitialFetchDone=!1,this.crossOrgSeenTimestamps={},this.scheduleCrossOrgFetch()})}extractIndexOrgTimestamps(t){let i={};try{let e=t?.data??t,o=e?.organizationIds??e?.orgs;return Array.isArray(o)?(o.forEach(s=>{typeof s=="string"&&s.length&&(i[s]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(s=>{if(typeof s=="string"&&s.length){let n=Number(o[s]);i[s]=Number.isFinite(n)?n:0}}),i)}catch(e){return this.loggingService.catch("Error in NotificationService extractIndexOrgTimestamps: ",e),i}}scheduleCrossOrgFetch(){try{let t=Date.now();t-this.lastCrossOrgFetchTime>=this.CROSS_ORG_FETCH_WINDOW_MS?(this.lastCrossOrgFetchTime=t,this.crossOrgFetchPending=!1,this.fetchCrossOrgUserNotifications(),this.armCrossOrgTrailingTimer()):this.crossOrgFetchPending=!0}catch(t){this.loggingService.catch("Error in NotificationService scheduleCrossOrgFetch: ",t)}}pruneCrossOrgBufferToAllowedOrgs(){try{let t=this.crossOrgNotifications$.getValue();if(!t.length)return;let i=this.crossOrgIndexOrgs||[];if(!i.length){this.crossOrgNotifications$.next([]);return}let e=t.filter(o=>i.includes(o?.metadata?.organizationId));e.length!==t.length&&this.crossOrgNotifications$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService pruneCrossOrgBufferToAllowedOrgs: ",t)}}armCrossOrgTrailingTimer(){this.crossOrgFetchTimer&&clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=setTimeout(()=>{this.crossOrgFetchPending&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())},this.CROSS_ORG_FETCH_WINDOW_MS)}toCrossOrgClientNotification(t){try{if(!t)return null;if(t.notification){let e=this.getClientNotificationObject(t);if(!e)return null;let o=t?.metadata?.organizationId??e?.metadata?.organizationId;return o!=null&&(e.metadata=E(y({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:E(y({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return T(this,null,function*(){try{if(!t?.length)return t;let i=!!this.notificationResolverService?.notificationDataProviderAvailable?.(),e=!!this.usersService?.userDataProviderAvailable?.(),o=!!this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable?.();if(!i&&!e&&!o)return t;let s=new Map;for(let r of t){let a=r?.metadata?.clientOrganizationId??r?.metadata?.organizationId??"",c=s.get(a);c?c.push(r):s.set(a,[r])}let n=[];for(let[r,a]of s){let c=a.reduce((g,f,h)=>{let d=f?.notificationId??f?.id??`__cross_org_${h}`;return g[d]=f,g},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:c,organizationId:r||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let l=c;i&&(l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l??{}})),e&&(l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l??{}})),o&&(l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l??{}})),n.push(...Object.values(l??{}))}return n}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return T(this,null,function*(){let t=this.crossOrgGeneration;if(this.crossOrgResolveRoundInFlight){this.crossOrgFetchPending=!0;return}this.crossOrgResolveRoundInFlight=!0;try{let i=this.crossOrganizationConfig$.getValue(),e=this.docService.getOrganizationConfig()?.organizationId??"",o=!this.crossOrgInitialFetchDone,s=this.crossOrgIndexTimestamps||{},n=o?[]:Object.keys(s).filter(f=>f!==e&&(s[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!n.length)return;let r=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:n}),a=yield this.callGetCrossOrgUserNotifications(r);if(t!==this.crossOrgGeneration)return;let c=Array.isArray(a?.pendingPermissionQueries)?a.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),g=!c.length||!l;if(yield this.processCrossOrgResponse(a,{fetchGeneration:t,currentOrg:e,isInitial:o,indexTimestamps:s,advanceCursors:g}),t!==this.crossOrgGeneration||g){g&&t===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry();return}yield this.runCrossOrgResolveRound(c,{fetchGeneration:t,config:i,currentOrg:e,isInitial:o,bumpedOrgs:n,indexTimestamps:s})}catch(i){this.loggingService.catch("Error in NotificationService fetchCrossOrgUserNotifications: ",i)}finally{this.crossOrgResolveRoundInFlight=!1,this.crossOrgFetchPending&&t===this.crossOrgGeneration&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())}})}runCrossOrgResolveRound(t,i){return T(this,null,function*(){try{let e=yield this.userPermissionService.resolveClientSidePermissions(t);if(i.fetchGeneration!==this.crossOrgGeneration)return;let o=this.buildCrossOrgRequestData(i.config,i.currentOrg,{isInitial:i.isInitial,bumpedOrgs:i.bumpedOrgs});o.clientResolvedResults=e;let s=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(s,{fetchGeneration:i.fetchGeneration,currentOrg:i.currentOrg,isInitial:i.isInitial,indexTimestamps:i.indexTimestamps,advanceCursors:!0}),i.fetchGeneration===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry()}catch(e){this.loggingService.catch("Error in NotificationService runCrossOrgResolveRound: ",e),this.armCrossOrgStragglerRetry(i.fetchGeneration)}})}processCrossOrgResponse(t,i){return T(this,null,function*(){if(this.userPermissionService?.getIsContextEnabled?.()&&t?.permissionResults?.length){let l=[...this.userPermissionService?.getPermissionsCache?.()??[],...t.permissionResults];this.userPermissionService?.setPermissionsCache?.(l)}let e=Array.isArray(t?.forYou)?t.forYou:[],o=this.crossOrgIndexOrgs||[],s=l=>o.includes(l),n=e.filter(l=>{let g=l?.metadata?.organizationId;if(g===i.currentOrg)return this.loggingService.log("%c[WB] Cross-org: dropping current-org echo: "+g,"color: orange;"),!1;let f=s(g);return f||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),f}),r=yield this.resolveCrossOrgSelfHostedData(n);if(i.fetchGeneration!==this.crossOrgGeneration)return;let a=r.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=a:c=this.mergeCrossOrgForYou(a,this.crossOrgNotifications$.getValue()).filter(l=>s(l?.metadata?.organizationId)),i.advanceCursors&&(Object.keys(i.indexTimestamps).forEach(l=>{this.crossOrgSeenTimestamps[l]=i.indexTimestamps[l]}),this.crossOrgInitialFetchDone=!0),this.crossOrgNotifications$.next(c)})}armCrossOrgStragglerRetry(t){this.crossOrgStragglerRetryUsed||(this.crossOrgStragglerRetryUsed=!0,this.crossOrgStragglerRetryTimer&&clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=setTimeout(()=>{this.crossOrgStragglerRetryTimer=void 0,t===this.crossOrgGeneration&&this.fetchCrossOrgUserNotifications()},this.CROSS_ORG_STRAGGLER_RETRY_MS))}clearCrossOrgStragglerRetry(){this.crossOrgStragglerRetryUsed=!1,this.crossOrgStragglerRetryTimer&&(clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=void 0)}callGetCrossOrgUserNotifications(t){return T(this,null,function*(){let i=this.authService.getUser(),e=q(this.functions,K({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield lt({methodName:"getCrossOrgUserNotifications",data:y({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},s=e?.isInitial??!0,n=e?.bumpedOrgs??[],r=Array.isArray(o.organizationIds),a=r?o.organizationIds.filter(h=>!!h).map(h=>at(h)):[],c=(o.excludeOrganizationIds||[]).filter(h=>!!h).map(h=>at(h)),l=new Set(c);i&&l.add(i);let g=this.userPermissionService?.getPermissionsCache?.()?.filter(h=>h?.type===k.CONTEXT),f={organizationId:i,excludeOrganizationIds:Array.from(l),timestamp:this.getStartAtTimestamp(),limitToLast:this.CROSS_ORG_PAGE_SIZE,isContextEnabled:this.userPermissionService?.getIsContextEnabled?.(),cachedData:g,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig?.()};if(this.userPermissionService?.isClientDevResolverActive?.()&&(f.clientResolverAvailable=!0),s)r&&(f.organizationIds=this.dedupeIncludeOrgs(a,l));else{let h=n.filter(m=>!!m&&!l.has(m));if(r){let m=new Set(a);h=h.filter(b=>m.has(b))}h=Array.from(new Set(h)),f.organizationIds=h;let d={};h.forEach(m=>{d[m]=this.crossOrgSeenTimestamps[m]??this.getStartAtTimestamp()}),f.orgTimestamps=d}return f}dedupeIncludeOrgs(t,i){let e=new Set;return t.filter(o=>o==null||i.has(o)||e.has(o)?!1:(e.add(o),!0))}teardownCrossOrgPerUserListeners(){this.crossOrgGeneration++,this.crossOrgIndexSubscription&&(this.crossOrgIndexSubscription.unsubscribe(),this.crossOrgIndexSubscription=void 0),this.crossOrgOrgSwitchSubscription&&(this.crossOrgOrgSwitchSubscription.unsubscribe(),this.crossOrgOrgSwitchSubscription=void 0),this.crossOrgFetchTimer&&(clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=void 0),this.crossOrgFetchPending=!1,this.clearCrossOrgStragglerRetry()}teardownCrossOrgUserWatcher(){this.teardownCrossOrgPerUserListeners(),this.crossOrgUserSubscription&&(this.crossOrgUserSubscription.unsubscribe(),this.crossOrgUserSubscription=void 0)}resetCrossOrgDeltaState(){this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1}resetCrossOrgForUser(){this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.getValue().length&&this.crossOrgNotifications$.next([])}teardownCrossOrg(){this.teardownCrossOrgUserWatcher(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([])}markCrossOrgEntriesRead(t){try{let i=this.crossOrgNotifications$.getValue();if(!i?.length)return;let e=new Set((t||[]).map(r=>r?.id??r?.notificationId).filter(r=>r!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),s=!1,n=o?i.filter(r=>{let a=r?.id??r?.notificationId,c=a!=null&&e.has(a);return c&&(s=!0),!c}):i.map(r=>{let a=r?.id??r?.notificationId;return a!=null&&e.has(a)&&r?.isUnread!==!1?(s=!0,E(y({},r),{isUnread:!1})):r});s&&this.crossOrgNotifications$.next(n)}catch(i){this.loggingService.catch("Error in NotificationService markCrossOrgEntriesRead: ",i)}}subscribeNotificationsData(t,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let e,o;try{if(t&&(o=nt(t)),i&&typeof i=="object"){let s=At(i);e=nt(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return this.authService.getAuthState$().pipe(P(s=>!!s),I(s=>this.isFeatureAllowed({firebaseUser:s})),I(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(v(n=>(s.featureAllowed=n,s))):D(s)),I(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),D([])):D(s).pipe(I(n=>this.docService.getDocumentPaths$().pipe(v(r=>(this.documentPaths=r,n.documentPaths=r,n)))),I(n=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(P(i=>!!i),v(i=>E(y({},t),{config:i})),I(i=>this.authService.getUser$().pipe(v(e=>E(y({},i),{user:e})))),I(i=>Ct(i.config,i.user,pt.NOTIFICATION)?D(E(y({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),D(E(y({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(P(i=>!!i),I(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let e=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(e+=`/${z.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let o=this.realtimeAdapter.rtdbRef(this.db,`${t?e+"/"+z.FIREBASE_PARTIAL_PATH_DOCS+"/"+t+"/"+z.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return this.realtimeAdapter.rtdbObjectVal$("notification",o).pipe(L(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),D(null))),v(s=>{let n=[],r=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(c=>{let l=s?.raw[c];l?.id&&n.push(l)}),n.forEach(c=>{c.id&&r.set(c.id,c)})),this.notifications$.next(n),this.rawNotificationsByIdMap$.next(r);let a=[];s?.processed&&Object.keys(s?.processed||{}).forEach(c=>{let l=s?.processed[c];l?.id&&a.push(l)}),this.processedNotifications$.next(a),this.setNotificationsByIdMap()}))}else return D(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=x(t?.email));let o;t?.userId&&(o=x(t?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(r=>{if(r.id&&r?.displayHeadlineMessageTemplate){let a=!1;(e&&r.notifyUsers?.[e]||o&&r.notifyUsers?.[o])&&(a=!0);let c={id:r.id,notificationSource:r.notificationSource,actionType:r.actionType,actionUser:r.actionUser,timestamp:r.timestamp,targetAnnotationId:r.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),forYou:a,notificationSourceData:r.notificationSourceData},l=this.getRawNotificationById(c.id);if(l?.metadata&&(c.metadata={apiKey:l.metadata.apiKey,organizationId:l.metadata.organizationId,clientOrganizationId:l.metadata.clientOrganizationId,documentId:l.metadata.documentId,clientDocumentId:l.metadata.clientDocumentId,location:l?.location,locationId:l?.locationId}),c?.notificationSource==="comment"&&c?.targetAnnotationId){let g=this.commentService?.getAnnotationById(c.targetAnnotationId);g||l?.annotationData&&(g=l.annotationData),g&&(c.notificationSourceData=this.commentService?.getCommentAnnotationForClient(g))}s.set(r.id,c)}}),s.forEach((r,a)=>{r.isUnread=r?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[a]?.views?.[t?.userSnippylyId],s.set(a,r)}),this.notificationsByIdMap$.next(s)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:s}){try{let n=this.authService.getUser(),r=s||t;if(r.id&&r?.displayHeadlineMessageTemplate&&n){let a=null;n?.email&&(a=x(n?.email));let c=null;n?.userId&&(c=x(n?.userId));let l=!1,g=!0;(a&&r.notifyUsers?.[a]||c&&r.notifyUsersByUserId?.[c])&&(l=!0),c&&o?.[c]&&(g=!1);let f={id:r.id};if(s?f=E(y(y({},f),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:l,isUnread:g}):f={id:t.id,notificationSource:t.notificationSource,actionType:t.actionType,actionUser:t.actionUser,timestamp:t.timestamp,targetAnnotationId:t.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(t),displayBodyMessage:this.getNotificationBodyMessage(t),forYou:l,isUnread:g,metadata:e},f?.notificationSource==="comment"&&f?.targetAnnotationId){let h=this.commentService?.getAnnotationById(f.targetAnnotationId);h||s?.notificationSourceData&&(h=s?.notificationSourceData),h||i?.annotationData&&(h=i.annotationData),h&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(h))}return i?.targetAnnotationData?.isCommentResolverUsed&&(f.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),s?.isNotificationResolverUsed&&(f.isNotificationResolverUsed=s.isNotificationResolverUsed),f}return}catch(n){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",n);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(v(t=>t?Object.keys(t??{}).map(i=>{let e=t[i].notifications||[],o=e.filter(n=>n.isUnread).length,s=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:s,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return V([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable(),this.getUserScopedAllTabRows$()]).pipe(v(([t,i,e])=>{let o=Array.isArray(i)?i:[],s=Array.isArray(e)?e:[],n=null;if(t&&(n=[],t.forEach(a=>{a.notifications.forEach(c=>{n?.push(c)})})),!o.length&&!s.length)return t?n.sort((a,c)=>c.timestamp-a.timestamp):null;if(!t)return null;let r=n||[];return s.length&&(r=this.mergeCrossOrgForYou(r,s)),o.length&&(r=this.mergeCrossOrgForYou(r,o)),r}))}getUserScopedAllTabRows$(){return V([this.userScopedNotifications$,this.userNotificationsFromServer$.asObservable()]).pipe(v(([t,i])=>!t?.enabled||!i?.length?[]:i.map(e=>e?.notification??this.getClientNotificationObject(e)).filter(e=>!!e)))}processNotificationData(t){try{let i=t?.annotationData?.metadata,e=this.docService.getOrganizationConfig()?.organizationId;t.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t.metadata||(t.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete t.metadata.locations,t.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t?.metadata?.documentMetadata?.clientDocumentId&&t?.metadata?.documentMetadata?.documentId&&(t.metadata.documentMetadata.documentId=t?.metadata?.documentMetadata?.clientDocumentId),delete t.metadata.documentMetadata.locations,t.metadata.organizationMetadata=JSON.parse(JSON.stringify(e?this.docService.getOrganizationMetadata(e)||{}:{})),t?.metadata?.organizationMetadata?.clientOrganizationId&&t?.metadata?.organizationMetadata?.organizationId&&(t.metadata.organizationMetadata.organizationId=t?.metadata?.organizationMetadata?.clientOrganizationId);let o=this.configService.getApiKey();t.metadata.apiKey=o,t.platform=this.configService.getSF()?"sf":"sdk",t.actionUser=this.authService.getUser();let s=i?.documentId?new ft({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=s?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=s?.clientOrganizationId||t.actionUser.clientOrganizationId);let n=this.docService.getLocation();n&&(t.location=n?.location,t.locationId=n?.locationId),this.loggingService.log(`[NOTIFICATION] ${t?.notificationSource} ${t?.actionType}`,t);let r=this.commonDbService.getServerTimestamp(),a=this.notificationUtilsService.formatNotification(t,r);return JSON.parse(JSON.stringify(a))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(t){try{if(!this.notificationsDb)return;let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=this.processNotificationData(t);try{let o=bt(t?.annotationData);if(o&&e&&typeof e=="object"){e.visibility=o;let s=Object.values(t?.annotationData?.subscribedUsers||{}).map(r=>r?.user?.userId).filter(r=>!!r),n=Dt(t?.annotationData,s);n.length&&(e.deniedForYouUsers=[...new Set([...e.deniedForYouUsers??[],...n])])}}catch(o){this.loggingService.catch("Error applying notification visibility in updateNotificationDatabase: ",o)}this.realtimeAdapter.rtdbPush("notificationIndex",i,JSON.parse(JSON.stringify(e)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(t){return this.authService.getUser$().pipe(I(i=>i?i.organizationId?this.getAllNotifications$().pipe(I(e=>this.notificationsForYou$.pipe(v(o=>{if(e||o){let s=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(n=>{n.id&&s.set(n.id,n)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(n=>{n.id&&!s.has(n.id)&&s.set(n.id,n)}),Array.from(s.values()).sort((n,r)=>(r.timestamp||0)-(n.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(v(e=>Array.from(e.values())),v(e=>e.sort((o,s)=>s.timestamp-o.timestamp)),dt()):D(null)),Y(Et))}getRawNotificationById(t){try{return this.rawNotificationsByIdMap$.getValue()?.get(t)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(t){try{this.notificationViews$.next(t),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(t){try{let i=this.authService.getUser();if(t?.displayHeadlineMessageTemplate&&t?.displayHeadlineMessageTemplateData){let e=t.displayHeadlineMessageTemplate,o=t.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,n=e.replace(s,(r,a)=>(a==="actionUser"||a==="recipientUser")&&o[a]?i?.email&&o[a].email===i?.email||i?.userId&&o[a]?.userId===i?.userId?"You":o[a].name||o[a].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':o[a]?o[a]:r);return this.domService.sanitizeHtml(n)}return this.domService.sanitizeHtml(t.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(t){try{if(t?.displayBodyMessageTemplate&&t?.displayBodyMessageTemplateData){let i=t?.displayBodyMessageTemplate;return t?.displayBodyMessageTemplateData&&t?.displayBodyMessageTemplateData?.users?.forEach(e=>{if(e?.userId){let o=this.usersService.getUserById(e?.userId);i=i?.replaceAll(`{{${e.userId}}}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),i=i?.replaceAll(`@User ${e.userId}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(t.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(t,i=!1,e=!1){try{t?document.querySelector(z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(t):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(t),t?this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(t=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${z.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(t){return T(this,null,function*(){try{let i=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(t?.length){for(let n=0;n<t.length;n+=50){let a=t.slice(n,n+50).filter(g=>g?.id),c=a.map(g=>this.setNotificationAsRead({notification:g,userNotifications:JSON.parse(JSON.stringify(i))})),l=yield Promise.all(c);a.forEach((g,f)=>{let h=l[f];if(!h.some(m=>m.notificationId===g.id))i=i.filter(m=>m.notificationId!==g.id);else{let m=i.find(A=>A.notificationId===g.id),b=h.find(A=>A.notificationId===g.id);m&&b?.views&&(m.views=b.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(n=>{let r=n.metadata?.documentId;if(r&&o?.[r]){let a=o?.[r]?.notifications||[],c=a.find(l=>l.id===n.id);c&&(c.isUnread=!1),o[r].notifications=a}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!J(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return T(this,null,function*(){try{if(t?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(_(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(v(t=>t?.filter(e=>e?.isUnread)?.length??null),I(t=>this.getNotifications$().pipe(v(i=>{let e=i?.filter(o=>o?.isUnread)?.length??null;return{forYou:t,all:e}}))))}catch(t){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",t),D({forYou:null,all:null})}}setNotificationAsRead(e){return T(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let s=x(o?.userId),{metadata:n}=t;if(n){let{apiKey:r,organizationId:a,documentId:c}=n;if(r&&a&&c&&s){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:a,documentId:c,apiKey:r}});l?.notificationId&&(l?.views?.[s]||(l.views||(l.views={}),l.views[s]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:a,documentId:c,apiKey:r},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:a}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:a}}),i=i.filter(f=>f.notificationId!==t.id);else if(!g?.views?.[s]){g.views||(g.views={}),g.views[s]={timestamp:Date.now()};let f=i.find(h=>h.notificationId===t.id);f&&(f.views=g.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:t.id,userId:s,documentId:c,organizationId:a},data:g})}}}}}return i}catch(o){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",o),i}})}setMaxDays(t){try{t>0?this.maxNotificationDays$.next(t):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(t){try{t&&this.tabConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",t)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",t)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(t){return T(this,null,function*(){try{this.getNotifications$().pipe(_(1)).subscribe(i=>{if(i){let e=i.filter(o=>o.id===t);this.setNotificationsAsRead(e)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(t){try{return this.allowedDocumentMetadataMap$.value?.[t]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(t){try{this.enableSettings$.value&&this.settingsConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(t){try{this.enableSettings$.value&&(this.settingsConfig$.next(t),this.updateSettingsConfigToDb())}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",t)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettings: ",t)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",t)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",t)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",t)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",t)}}enableUserScopedNotifications(t){try{this.userScopedNotifications$.next({enabled:!0,limit:qt(t?.limit)})}catch(i){this.loggingService.catch("Error in NotificationService enableUserScopedNotifications: ",i)}}disableUserScopedNotifications(){try{this.userScopedNotifications$.value.enabled!==!1&&this.userScopedNotifications$.next({enabled:!1,limit:this.userScopedNotifications$.value.limit})}catch(t){this.loggingService.catch("Error in NotificationService disableUserScopedNotifications: ",t)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettings: ",t)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(t){try{let i=!1;if(t.forEach(e=>{["email","inbox"].includes(e.id)&&(i=!e.values?.every(o=>["ALL","NONE","MINE"].includes(o.id)))}),i){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",i)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(t){return T(this,null,function*(){try{let i=this.authService.getUser(),e=x(i?.userId??""),o=this.docService.getDocumentPaths(),s=this.docService.getOrganizationConfig(),n=o?.organizationId??s?.organizationId,r=o?.clientOrganizationId??s?.clientOrganizationId,a={apiKey:this.configService.getApiKey(),organizationId:n,documentId:o?.documentId,clientOrganizationId:r,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:r??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:o?.documentId,userId:e},data:{id:o?.documentId,notificationsConfig:t||this.settingsConfig$.getValue(),metadata:a}})))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",t)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",t)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};U.\u0275fac=function(i){return new(i||U)(S(mt),S(Ft),S(Z),S(Pt),S(Wt),S(Yt),S(et),S(tt),S(ot),S(Ht),S(_t),S(Bt),S(kt),S(X),S(Kt),S(it),S(St),S(Jt),S(xt),S(Q),S(Gt))},U.\u0275prov=G({token:U,factory:U.\u0275fac,providedIn:"root"});let R=U;return R})();export{Kt as a,xi as b};