@veltdev/sdk-staging 6.0.21 → 6.0.23

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 (59) hide show
  1. package/{chunk-Z3NOEF5O.js → chunk-3M5GZFCG.js} +1 -1
  2. package/{chunk-TIDK55EX.js → chunk-3PSEC6OK.js} +1 -1
  3. package/{chunk-Q5QIV3YT.js → chunk-5GFU7BU6.js} +1 -1
  4. package/{chunk-PGPXYZZN.js → chunk-6BCXLMAY.js} +1 -1
  5. package/{chunk-JC7WVK34.js → chunk-6F7MEOHL.js} +1 -1
  6. package/{chunk-PLEUR6AN.js → chunk-C3DWGOTZ.js} +1 -1
  7. package/{chunk-BQVD76TQ.js → chunk-C3PHZRKL.js} +1 -1
  8. package/chunk-CJVRXVE5.js +1 -0
  9. package/chunk-COMT5MGY.js +1 -0
  10. package/{chunk-G6CVZGMW.js → chunk-CQZ7DKJB.js} +1 -1
  11. package/{chunk-IYN573WN.js → chunk-D2UJGDHP.js} +1 -1
  12. package/{chunk-UPKZBLXG.js → chunk-EC25EQB5.js} +1 -1
  13. package/{chunk-MOU625G2.js → chunk-EIDOVJ3L.js} +1 -1
  14. package/{chunk-2PD23MCR.js → chunk-F2XJIYNI.js} +1 -1
  15. package/{chunk-RS4IIGBQ.js → chunk-F2Z7K4AL.js} +1 -1
  16. package/{chunk-KBPP2RJV.js → chunk-GUBXZVJ3.js} +1 -1
  17. package/{chunk-IV6TXG5Z.js → chunk-J2NS4TI4.js} +1 -1
  18. package/{chunk-GMP3ZGYE.js → chunk-KE64O5B7.js} +1 -1
  19. package/{chunk-XDDHCYC6.js → chunk-KXEU5HGR.js} +1 -1
  20. package/{chunk-IUO7RNPW.js → chunk-M5AN4E5A.js} +1 -1
  21. package/{chunk-LG756VXD.js → chunk-MGORC6ST.js} +1 -1
  22. package/{chunk-WXX73A2Z.js → chunk-MU6RYO5X.js} +1 -1
  23. package/{chunk-64VJSQ7G.js → chunk-N2ZDAA6T.js} +1 -1
  24. package/{chunk-5CHLXJQA.js → chunk-O4J2GUCR.js} +1 -1
  25. package/{chunk-T4CZDGU7.js → chunk-RCOPSCV6.js} +1 -1
  26. package/{chunk-3QL3XETD.js → chunk-TDVYFBCW.js} +1 -1
  27. package/{chunk-NK4G7LFH.js → chunk-TM2JOAC4.js} +1 -1
  28. package/{chunk-ACBISYSH.js → chunk-TVANUSZU.js} +1 -1
  29. package/{chunk-6EMXC6J7.js → chunk-UFGQLAOK.js} +1 -1
  30. package/{chunk-HRHQ2ONQ.js → chunk-UWH2AIKJ.js} +1 -1
  31. package/{chunk-YNU6L4ZC.js → chunk-V53LQO22.js} +6 -6
  32. package/{chunk-I3NP7X72.js → chunk-VFYLOVTK.js} +1 -1
  33. package/{chunk-TSAUKBNW.js → chunk-XAZILV5B.js} +1 -1
  34. package/{chunk-PXOUAPOU.js → chunk-ZEWGJF7N.js} +1 -1
  35. package/{chunk-TPPAZ2V2.js → chunk-ZURN7SUE.js} +1 -1
  36. package/package.json +1 -1
  37. package/velt-activity-log.js +1 -1
  38. package/velt-area.js +1 -1
  39. package/velt-arrow.js +1 -1
  40. package/velt-comment.js +7 -7
  41. package/velt-crdt.js +1 -1
  42. package/velt-cursor.js +1 -1
  43. package/velt-huddle.js +1 -1
  44. package/velt-live-state-sync.js +1 -1
  45. package/velt-notification.js +1 -1
  46. package/velt-portable.js +1 -1
  47. package/velt-presence.js +1 -1
  48. package/velt-reaction.js +1 -1
  49. package/velt-recorder.js +1 -1
  50. package/velt-rewriter.js +1 -1
  51. package/velt-selection.js +1 -1
  52. package/velt-tag.js +1 -1
  53. package/velt-user-invite.js +1 -1
  54. package/velt-user-request.js +1 -1
  55. package/velt-video-player.js +1 -1
  56. package/velt-views.js +1 -1
  57. package/velt.js +2 -2
  58. package/chunk-7YXWYOYZ.js +0 -1
  59. package/chunk-P2OUKDDH.js +0 -1
package/velt-views.js CHANGED
@@ -1,3 +1,3 @@
1
- import{t as lt}from"./chunk-I3NP7X72.js";import"./chunk-G6CVZGMW.js";import"./chunk-TPPAZ2V2.js";import{a as qe,c as Ge,d as We}from"./chunk-WXX73A2Z.js";import{a as ut}from"./chunk-XDDHCYC6.js";import"./chunk-IV6TXG5Z.js";import{a as at}from"./chunk-PXOUAPOU.js";import{a as gt}from"./chunk-2PD23MCR.js";import"./chunk-GMP3ZGYE.js";import"./chunk-3QL3XETD.js";import{b as st,d as ct}from"./chunk-T4CZDGU7.js";import{a as dt}from"./chunk-NK4G7LFH.js";import{a as Le}from"./chunk-JC7WVK34.js";import{A as ze,Fa as ot,G as Pe,H as Ne,Ha as rt,I as Fe}from"./chunk-MOU625G2.js";import{a as mt}from"./chunk-IYN573WN.js";import{A as ve,e as ge,y as nt}from"./chunk-P2OUKDDH.js";import{Bb as x,E as B,Ej as z,Fi as ye,Gd as Me,Ha as h,Hc as Te,He as E,Hj as et,Ia as re,Ic as le,Ii as Ye,K as te,Kb as se,M as K,Mb as ae,Nj as tt,O as Ce,Pb as _,Qb as J,Ra as I,Rb as R,Rc as $e,Tb as Ue,U as De,V as S,Va as Be,Vd as Re,Wa as Q,Wd as je,Wj as ue,Xa as Ae,Xi as Qe,Xj as it,Y as xe,Zf as we,_ as ie,a as m,ab as T,ai as He,b as y,ba as _e,ca as Ee,cc as ke,ci as de,ea as k,g as j,ij as Ze,ja as N,ka as F,l as $,la as H,lj as me,ma as Y,mc as A,nb as D,nc as U,nj as C,ob as v,oj as Xe,pb as w,qb as L,qe as Je,r as V,rc as ce,sa as ne,t as Ie,ub as q,v as f,vb as G,w as Z,wa as Oe,wg as Ke,xb as W,ya as oe,zb as M,zj as fe}from"./chunk-YNU6L4ZC.js";var P=(()=>{let c=class c{constructor(e,t,n,i,o,a,l,s,u,p){this.afAuth=e,this.authService=t,this.configService=n,this.databaseService=i,this.docService=o,this.commonDbService=a,this.iamService=l,this.loggingService=s,this.userPermissionService=u,this.serviceBook=p,this.documentPaths=null,this.views$=new $({}),this.commentViews$=new $({}),this.documentViews$=new $({}),this.locationViews$=new $({}),this.commentViewsByOrganizationIdAndDocumentId$=new $({}),this.documentViewsByOrganizationIdAndDocumentId$=new $({}),this.locationViewsByOrganizationIdAndLocationId$=new $({}),this.documentViewsEnabled$=new $(!1),this.documentViewsSetByDocumentId={},this.notificationService=null,this.loggingService.log("%c[WB] Creating CLASS: ViewsService","color: blue;");try{this.serviceBook.observe(Qe).subscribe(g=>{this.commentService=g??void 0}),this.serviceBook.observe(Ye).subscribe(g=>{this.notificationService=g??null}),this.viewsDbReadyGate$().pipe(te(1)).subscribe(()=>{this.subscribeViewsData().subscribe(),this.getNotificationFeatureViews$().subscribe(g=>{this.notificationService?.setNotificationViews(g)}),this.authService.getUser$().pipe(B(g=>!!g),S(g=>this.documentViewsEnabled$.pipe(B(b=>b),f(()=>g))),S(g=>this.docService.getDocumentPaths$().pipe(De(null),Ce(),f(([b,O])=>(b?.documentId!==O?.documentId&&this.views$.next({}),O)),f(b=>(this.documentPaths=b,this.setDocumentAsRead({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),{_user:g,_documentPaths:b})),S(b=>this.docService.getDocumentIds$().pipe(S(O=>(O?.length&&(O.find(ee=>ee.documentId===this.documentPaths?.documentId)||O.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),O.forEach(ee=>{this.setDocumentAsRead({documentId:ee.documentId,clientDocumentId:ee.clientDocumentId})})),V(b))))))),S(g=>this.docService.getDocumentMetadata$().pipe(B(b=>!!b),f(b=>y(m({},g),{_documentMetadata:b}))))).subscribe(),this.authService.getUser$().pipe(B(g=>!!g),S(g=>this.documentViewsEnabled$.pipe(B(b=>b),f(()=>g))),S(g=>this.docService.getLocation$().pipe(B(b=>!!b))),S(g=>this.docService.getDocumentIds$().pipe(S(b=>(b.find(O=>O.documentId===this.documentPaths?.documentId)||b.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),b.forEach(O=>{this.setLocationAsRead({documentId:O.documentId,clientDocumentId:O.clientDocumentId})}),V(g)))))).subscribe()},g=>{this.loggingService.catch("Error in ViewsService getDb subscription: ",g)})}catch(g){this.loggingService.catch("Error in ViewsService constructor: ",g)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ViewsService","color: green;");try{this.documentPaths=null,this.documentViews$.next({}),this.views$.next({}),this.commentViews$.next({}),this.locationViews$.next({}),this.commentViewsByOrganizationIdAndDocumentId$.next({}),this.documentViewsByOrganizationIdAndDocumentId$.next({}),this.locationViewsByOrganizationIdAndLocationId$.next({})}catch(e){this.loggingService.catch("Error in ViewsService clearCache: ",e)}}subscribeViewsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let n,i;try{if(e&&(i=we(e)),t&&typeof t=="object"){let o=Ke(t);n=we(JSON.stringify(o))}}catch(o){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",o)}return this.authService.getAuthState$().pipe(B(o=>!!o),S(o=>this.isFeatureAllowed({firebaseUser:o})),S(o=>o.featureAllowed?this.iamService.isUserAllowed$().pipe(f(a=>(o.featureAllowed=a,o))):V(o)),S(o=>o.featureAllowed?V(o).pipe(S(a=>this.docService.getDocumentPaths$().pipe(f(l=>(this.documentPaths=l,a.documentPaths=l,a)))),S(a=>i?this.getDataFromDocumentIds([i]):this.docService.getDocumentIds$().pipe(S(l=>{let s=l?.length>0?l.map(u=>u.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(s)})))):V([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(B(t=>!!t),f(t=>y(m({},e),{config:t})),S(t=>this.authService.getUser$().pipe(f(n=>y(m({},t),{user:n})))),S(t=>t.user?V(y(m({},t),{featureAllowed:!0})):V(y(m({},t),{featureAllowed:!1}))),K((t,n)=>t?.featureAllowed===n?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getCommentViewsById(e){try{return this.commentViews$.value?.[e]?this.commentViews$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in ViewsService getCommentViewsById: ",t);return}}getDocumentViewsById(e){try{return this.documentViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getDocumentViewsById: ",t);return}}getLocationViewsById(e){try{return this.locationViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getLocationViewsById: ",t);return}}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:n}=e;return t?.some(i=>!i)||!this.documentPaths?V([]):this.documentViewsEnabled$.pipe(S(i=>i?Z([this.getCommentViewsDataFromDocuments(),this.getDocumentViewsDataFromDocuments(t),this.getLocationViewsDataFromDocuments(t)]):Z([this.getCommentViewsDataFromDocuments()])))}else return V(null)}getCommentViews(e){try{let t={};Object.entries(e??{}).forEach(([n,i])=>{let o=i.metadata?.documentId,a=i.views;!o||!a||(t[o]||(t[o]={}),t[o][i.annotationId]=a)}),Object.entries(t??{}).forEach(([n,i])=>{this.setCommentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:n,commentViews:i})})}catch(t){this.loggingService.catch("Error in ViewsService getCommentViews: ",t)}}getCommentViewsDataFromDocuments(){try{return this.commentService?this.commentService?.getAllCommentAnnotations({detectGhostComments:!0,addFilterCommentsOnDomCheck:!0,fromCommentSidebar:!0,skipPositionCalculation:!0,analytics:{enabled:!0,properties:{source:"internal",sourceId:"commentsContainer"}}}).pipe(B(e=>!!e),xe(e=>{this.getCommentViews(e)})):V([])}catch(e){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",e),V([])}}viewsDbReadyGate$(){return tt({isPortableFeedActive:()=>this.commonDbService?.usesPortableChannelFeed(ge),firebaseDb$:()=>this.databaseService.getDb(),onError:(e,t)=>this.loggingService.catch(`Error in ViewsService viewsDbReadyGate$ ${e}: `,t)})}getDocumentViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,n=V([]),i={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(i.documentId=e?.length?e[0]:void 0,i.organizationId=this.documentPaths?.organizationId),this.commonDbService.usesPortableChannelFeed(ge))n=this.commonDbService.dbListener({feature:"allDocumentViews",properties:y(m({},i),{organizationId:this.documentPaths?.organizationId,documentIds:e})}).pipe(ie(),f(o=>de(JSON.parse(JSON.stringify([o])))));else{let o=[];for(let a=0;a<(e?.length??0);a+=E.LISTENER_BATCH_SIZE)o.push(e?.slice(a,a+E.LISTENER_BATCH_SIZE)??[]);n=Z(o.map(a=>this.commonDbService.dbListener({feature:"allDocumentViews",properties:y(m({},i),{firestoreQuery:[fe(z("metadata.apiKey","==",this.configService?.getApiKey()),z("metadata.documentId","in",a),z("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[z("metadata.veltFolderId","==",t)]:[])]})}).pipe(ie()))).pipe(f(a=>de(a)))}return n.pipe(f(o=>({data:o?.data,operation:o?.operation})),f(({data:o,operation:a})=>{let l={};return e?(Object.entries(o??{}).forEach(([s,u])=>{let p=u.metadata?.documentId;p&&(l[p]||(l[p]={}),l[p][s]=u)}),{data:o,documentMap:l,operation:a}):{data:o,documentMap:l,operation:a}}),f(({data:o,documentMap:a,operation:l})=>{if(l?.type==="removed"){if(l?.ids?.length){let s=this.documentViews$.value;l?.ids?.forEach(u=>{delete s?.[u]}),this.documentViews$.next(s)}}else Object.entries(a??{}).forEach(([s,u])=>{this.setDocumentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:s,documentViews:u})})}))}getLocationViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,n=V([]),i={useCollectionGroup:!0,isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(i.documentId=e?.length?e[0]:void 0,i.organizationId=this.documentPaths?.organizationId);let o=[];for(let a=0;a<(e?.length??0);a+=E.LISTENER_BATCH_SIZE)o.push(e?.slice(a,a+E.LISTENER_BATCH_SIZE)??[]);return n=Z(o.map(a=>this.commonDbService.dbListener({feature:"allLocationViews",properties:y(m({},i),{firestoreQuery:[fe(z("metadata.apiKey","==",this.configService?.getApiKey()),z("metadata.documentId","in",a),z("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[z("metadata.veltFolderId","==",t)]:[])]})}).pipe(ie()))).pipe(f(a=>de(a))),n.pipe(f(a=>({data:a?.data,operation:a?.operation})),f(({data:a,operation:l})=>{let s={};return e?(Object.entries(a??{}).forEach(([u,p])=>{let g=p.metadata?.documentId;g&&(s[g]||(s[g]={}),s[g][u]=p)}),{data:a,documentMap:s,operation:l}):{data:a,documentMap:s,operation:l}}),f(({data:a,documentMap:l,operation:s})=>{if(s?.type==="removed"){if(s?.ids?.length){let u=this.locationViews$.value;s?.ids?.forEach(p=>{delete u?.[p]}),this.locationViews$.next(u)}}else Object.entries(l??{}).forEach(([u,p])=>{this.setLocationViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:u,locationViews:p})})}))}setViewsData(e){try{this.views$.next(m(m({},this.views$.getValue()),e||{}))}catch(t){this.loggingService.catch("Error in ViewsService setViewsData:",t)}}setCommentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,commentViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.commentViews$.value),n);this.commentViews$.next(o),this.commentViewsByOrganizationIdAndDocumentId$.next(y(m({},this.commentViewsByOrganizationIdAndDocumentId$.value),{[e]:y(m({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]),{[t]:y(m({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}setDocumentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,documentViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.documentViews$.value),n);this.documentViews$.next(o),this.documentViewsByOrganizationIdAndDocumentId$.next(y(m({},this.documentViewsByOrganizationIdAndDocumentId$.value),{[e]:y(m({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]),{[t]:y(m({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}setLocationViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,locationViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.locationViews$.value),n);this.locationViews$.next(o),this.locationViewsByOrganizationIdAndLocationId$.next(y(m({},this.locationViewsByOrganizationIdAndLocationId$.value),{[e]:y(m({},this.locationViewsByOrganizationIdAndLocationId$.value[e]),{[t]:y(m({},this.locationViewsByOrganizationIdAndLocationId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}getCommentFeatureViews$(){return this.commentViews$.pipe(K((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}setCommentAnnotationAsRead(e){return j(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){if(e.annotationId.startsWith("TEMP_COMPOSER_"))return;this.updateCommentAnnotationViews(e);let n=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",i=e?.metadata?.documentId??this.documentPaths?.documentId??"";if(e?.isDraft)return;yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:i,organizationId:n,metadata:{apiKey:this.configService.getApiKey(),organizationId:n,veltFolderId:e?.metadata?.veltFolderId,documentId:i}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}setCommentAnnotationAsUnread(e){return j(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){if(e.annotationId.startsWith("TEMP_COMPOSER_"))return;this.removeCommentAnnotationViews(e);let n=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",i=e?.metadata?.documentId??this.documentPaths?.documentId??"";if(e?.isDraft)return;yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:i,organizationId:n,metadata:{apiKey:this.configService.getApiKey(),organizationId:n,veltFolderId:e?.metadata?.veltFolderId,documentId:i}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}updateCommentAnnotationViews(e){try{let t=this.authService.getUser(),n={views:{},comments:{}};if(t){let i={},o=e?.views?.comments||{},a=new Date().getTime()+this.commonDbService.getOffset();e.comments?.forEach(s=>{o[s.commentId]||(o[s.commentId]={views:{}}),o[s.commentId].views||(o[s.commentId].views={}),o[s.commentId].views[t.userSnippylyId]||(o[s.commentId].views[t.userSnippylyId]={timestamp:a})});let l=new Set(e.comments?.map(s=>s.commentId+""));if(Object.keys(o??{}).forEach(s=>{l.has(s)||delete o[s]}),e.comments?.length){let s=o[e.comments[0].commentId]?.views||{},u=Object.keys(s??{}).filter(p=>e.comments?.every(g=>o[g.commentId]?.views?.[p]));u.forEach(p=>{i[p]={timestamp:s[p].timestamp}}),e.viewedByUserIds=u}n.views=i,n.comments=o,e.views=n}return n}catch(t){return this.loggingService.catch("Error in ViewsService updateCommentAnnotationViews:",t),{views:{},comments:{}}}}removeCommentAnnotationViews(e){try{let t=this.authService.getUser(),n={views:{},comments:{}};if(t){let i={},o=e?.views?.comments||{};e.comments?.forEach(l=>{o[l.commentId]?.views?.[t.userSnippylyId]&&delete o[l.commentId].views[t.userSnippylyId]});let a=new Set(e.comments?.map(l=>l.commentId+""));if(Object.keys(o??{}).forEach(l=>{a.has(l)||delete o[l]}),e.comments?.length){let l=o[e.comments[0].commentId]?.views||{},s=Object.keys(l??{}).filter(u=>e.comments?.every(p=>o[p.commentId]?.views?.[u]));s.forEach(u=>{i[u]={timestamp:l[u].timestamp}}),e.viewedByUserIds=s}else e.viewedByUserIds=[];n.views=i,n.comments=o,e.views=n}return n}catch(t){return this.loggingService.catch("Error in ViewsService removeCommentAnnotationViews:",t),{views:{},comments:{}}}}getNotificationFeatureViews$(){return this.views$.pipe(K((e,t)=>JSON.stringify(e?.notification||{})===JSON.stringify(t?.notification||{})))}setNotificationsAsRead(e){try{let t=this.authService.getUser();if(t){let n=new Date().getTime()+this.commonDbService.getOffset();e.forEach(i=>{this.commonDbService.updateData({feature:"notificationViewsTimestamp",properties:{id:i,user:t.userSnippylyId,documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??""},data:{timestamp:n}})})}}catch(t){this.loggingService.catch("Error in ViewsService setNotificationAsRead:",t)}}getDocumentViews$(){return this.views$.pipe(K((e,t)=>JSON.stringify(e?.documentViews||{})===JSON.stringify(t?.documentViews||{})))}getUniqueViewsByUser(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(S(t=>(this.documentPaths=t,e?this.locationViews$.pipe(f(n=>{let i=Object.keys(n||{}).find(o=>n?.[o]?.location?.id===e);return i?n?.[i]?.users||{}:{}})):this.documentViews$.pipe(f(n=>{let i=this.documentPaths?.documentId;return i?n?.[i]?.users||{}:{}})))),K(He))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByUser:",t),V({})}}getUniqueViewsByDate(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(S(t=>(this.documentPaths=t,e?this.locationViews$.pipe(f(n=>{let i=Object.keys(n||{}).find(o=>n?.[o]?.location?.id===e);return i?n?.[i]?.day||{}:{}})):this.documentViews$.pipe(f(n=>{let i=this.documentPaths?.documentId;return i?n?.[i]?.day||{}:{}})))))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByDate:",t),V({})}}enableDocumentViews(){try{if(this.documentViewsEnabled$.value===!0)return;this.documentViewsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ViewsService enableDocumentViews:",e)}}disableDocumentViews(){try{if(this.documentViewsEnabled$.value===!1)return;this.documentViewsEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ViewsService disableDocumentViews:",e)}}setDocumentAsRead(n){return j(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let i=this.authService.getUser();if(i&&e&&this.userPermissionService?.hasEditAccess({documentId:e??"",folderId:this.documentPaths?.allDocuments&&this.documentPaths?.veltFolderId?this.documentPaths?.veltFolderId:void 0})){if(this.documentViewsSetByDocumentId[e])return;this.documentViewsSetByDocumentId[e]=!0;let o=new Date().getTime()+this.commonDbService.getOffset(),a=new Date().toISOString().split("T")[0];if(this.commonDbService.usesPortableChannelFeed(ge)){let s=yield Ie(this.docService.getDocumentPaths$().pipe(f(u=>u?.organizationId),B(u=>!!u)));yield this.commonDbService.whenPortableRealtimeReady(),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:a,user:i.userSnippylyId,documentId:e,organizationId:s},data:{}}),this.checkAndTriggerNotification(i);return}let l=this.getDocumentViewsById(e);if(l){let s=new Date().toISOString().split("T")[0];l?.users[i.userSnippylyId]||(l.users[i.userSnippylyId]={}),l.users[i.userSnippylyId][s]={timestamp:this.timestamp},l?.day[s]||(l.day[s]={}),l.day[s][i.userSnippylyId]={timestamp:this.timestamp},l.metadata=this.docService.getBaseMetadata("documentViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:s,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??""},data:l})}else this.commonDbService.updateData({feature:"documentDayViews",properties:{id:e,date:a,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:o}}),this.commonDbService.updateData({feature:"documentUsersViews",properties:{id:e,user:i.userSnippylyId,date:a,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:o}}),this.commonDbService.updateData({feature:"documentMetadataViews",properties:{id:e,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})}),this.docService.getDocumentMetadata$(e).pipe(B(s=>s!==null),te(1)).subscribe(()=>{let s={day:{[a]:{[i.userSnippylyId]:{timestamp:o}}},users:{[i.userSnippylyId]:{[a]:{timestamp:o}}},metadata:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})};this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:a,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0},data:s})});this.checkAndTriggerNotification(i)}}catch(i){this.loggingService.catch("Error in ViewsService setDocumentAsRead:",i)}})}checkAndTriggerNotification(e){try{this.getUniqueViewsByUser().pipe(te(1)).subscribe(t=>{if(Object.keys(t??{}).length===2){let n=this.docService.getDocumentMetadata();if(n?.creator?.email&&n?.creator?.email!==e.email){let i=[n.creator.email];this.updateNotificationsDatabase(Je.FIRST_VIEWED,{documentViews:{emails:i}})}}})}catch(t){this.loggingService.catch("Error in checkAndTriggerNotification:",t)}}setLocationAsRead(n){return j(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let i=this.authService.getUser(),o=this.docService.getLocation(),a=o?.locationId,l=o?.location;if(i&&a&&l){let s=new Date().getTime()+this.commonDbService.getOffset(),u=new Date().toISOString().split("T")[0],p=this.getLocationViewsById(a);if(p){let g=new Date().toISOString().split("T")[0];p?.users[i.userSnippylyId]||(p.users[i.userSnippylyId]={}),p.users[i.userSnippylyId][g]={timestamp:this.timestamp},p?.day[g]||(p.day[g]={}),p.day[g][i.userSnippylyId]={timestamp:this.timestamp},p.metadata=this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"location",data:p,properties:{id:a,documentId:e,organizationId:this.documentPaths?.organizationId??""}})}else{this.commonDbService.updateData({feature:"locationViews",data:l,properties:{id:a,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}}),this.commonDbService.updateData({feature:"locationUsersViews",properties:{id:a,user:i.userSnippylyId,date:u,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:s}}),this.commonDbService.updateData({feature:"locationDayViews",properties:{id:a,date:u,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:s}}),this.commonDbService.updateData({feature:"locationMetadataViews",properties:{id:a,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t})});let g={day:{[u]:{[i.userSnippylyId]:{timestamp:s}}},users:{[i.userSnippylyId]:{[u]:{timestamp:s}}},metadata:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),location:l};this.commonDbService.updateData({feature:"location",data:g,properties:{id:a,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0}})}}}catch(i){this.loggingService.catch("Error in ViewsService setLocationAsRead:",i)}})}updateNotificationsDatabase(e,t={}){try{let n=m({actionType:e,notificationSource:"documentViews"},t);this.notificationService?.updateNotificationDatabase(n)}catch(n){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",n)}}get timestamp(){return this.commonDbService.getServerTimestamp()}};c.\u0275fac=function(t){return new(t||c)(k(Me),k(it),k(Xe),k(et),k(ve),k(nt),k(dt),k(C),k(ut),k(me))},c.\u0275prov=_e({token:c,factory:c.\u0275fac,providedIn:"root"});let d=c;return d})();function ft(d,c){if(d&1&&(q(0),v(1,"div",21)(2,"div",22),L(3,"snippyly-user-avatar",23),w(),v(4,"div",24)(5,"div",25),_(6),A(7,"translate"),w()(),v(8,"div",26),_(9),A(10,"timeAgo"),w()(),G()),d&2){let r=c.$implicit;h(3),D("user",r==null?null:r.user)("size",32),h(3),R(" ",U(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),h(3),R(" ",U(10,6,r==null?null:r.timestamp)," ")}}function St(d,c){if(d&1&&(v(0,"div",19),T(1,ft,11,8,"ng-container",20),w()),d&2){let r=x(2).ngIf;h(),D("ngForOf",r.userViews)}}function bt(d,c){if(d&1){let r=W();q(0),v(1,"div",4)(2,"button",5),M("click",function(){N(r);let t=x(2);return F(t.closeTrendDialog())}),H(),v(3,"svg",6),L(4,"path",7),w(),Y(),v(5,"span"),_(6),A(7,"translate"),w()()(),v(8,"div",8)(9,"div",9)(10,"div",10),_(11),w(),v(12,"div",11),H(),v(13,"svg",12),L(14,"path",13)(15,"path",14),w(),Y(),v(16,"span"),_(17),A(18,"translate"),w()()(),v(19,"div",15)(20,"div",16),_(21),w(),v(22,"div",17)(23,"span"),_(24),A(25,"translate"),w()()()(),T(26,St,2,1,"div",18),G()}if(d&2){let r=x().ngIf;h(6),J(U(7,6,"Go Back")),h(5),R(" ",r.totalUniqueViewsCount," "),h(6),J(U(18,8,"Total Views")),h(4),R(" ",r.todayViewsCount," "),h(3),J(U(25,10,"Views Today")),h(2),D("ngIf",r.userViews==null?null:r.userViews.length)}}function Vt(d,c){if(d&1&&(q(0),v(1,"div",21)(2,"div",22),L(3,"snippyly-user-avatar",23),w(),v(4,"div",24)(5,"div",25),_(6),A(7,"translate"),w(),v(8,"div",26),_(9),A(10,"timeAgo"),w()()(),G()),d&2){let r=c.$implicit;h(3),D("user",r==null?null:r.user)("size",32),h(3),R(" ",U(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),h(3),R(" ",U(10,6,r==null?null:r.timestamp)," ")}}function It(d,c){if(d&1&&(v(0,"div",29)(1,"div",19),T(2,Vt,11,8,"ng-container",20),w()()),d&2){let r=x(2).ngIf;h(2),D("ngForOf",r.userViews)}}function Ct(d,c){if(d&1&&(v(0,"div",27)(1,"div",9)(2,"div",10),_(3),w(),v(4,"div",11),H(),v(5,"svg",12),L(6,"path",13)(7,"path",14),w(),Y(),v(8,"span"),_(9),A(10,"translate"),w()()(),v(11,"div",15),_(12),A(13,"translate"),A(14,"translate"),A(15,"translate"),w()(),T(16,It,3,1,"div",28)),d&2){let r=x().ngIf;h(3),R(" ",r.totalUniqueViewsCount," "),h(6),J(U(10,6,"Total Views")),h(3),Ue(" ",r.todayViewsCount," ",r.todayViewsCount===1?U(13,8,"View"):U(14,10,"Views")," ",U(15,12,"Today")," "),h(4),D("ngIf",r.userViews==null?null:r.userViews.length)}}function Dt(d,c){if(d&1){let r=W();q(0),v(1,"div",2),M("clickOutside",function(){N(r);let t=x();return F(t.closeTrendDialog())}),T(2,bt,27,12,"ng-container",3)(3,Ct,17,14,"ng-template",null,0,ce),w(),G()}if(d&2){let r=c.ngIf,e=se(4);h(),ae("bottom-sheet",r.bottomSheetMode),h(),D("ngIf",r.bottomSheetMode)("ngIfElse",e)}}var X=(()=>{let c=class c{constructor(e,t,n,i,o,a,l){this.contactService=e,this.loggingService=t,this.viewsService=n,this.themeService=i,this.elementRef=o,this.domService=a,this.bottomSheetData=l,this.close=new re,this.componentConfigSignal=ne({today:new Date().toISOString().split("T")[0],todayViews:{},todayViewsCount:0,totalUniqueViews:{},totalUniqueViewsCount:0,views:{},usersMap:{},userViews:[],bottomSheetMode:!1}),this.subscriptions=[];try{l&&(this.componentConfigSignal.update(s=>(s=y(m({},s),{bottomSheetMode:!0}),s)),this.clientLocationId=l.clientLocationId,this.closeBottomSheetFn=l.closeBottomSheetFn),this.subscriptions.push(this.contactService.getUsersMap$().subscribe(s=>{this.componentConfigSignal.update(u=>(u=y(m({},u),{usersMap:s||{}}),u)),this.setLatestViewsByUsers()},s=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUsersMap$ subscription: ",s)})),this.subscriptions.push(this.themeService.getDarkMode$().subscribe(s=>{s?this.elementRef.nativeElement.setAttribute("dark",""):this.elementRef.nativeElement.removeAttribute("dark")}))}catch(s){this.loggingService.catch("Error in ViewAnalyticsDialogComponent constructor: ",s)}}ngOnInit(){this.getDocumentViews()}ngAfterViewInit(){try{this.subscriptions.push(this.domService.subscribeInjectCustomCss(this.elementRef))}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent ngAfterViewInit: ",e)}}trackByUserIdAndTimestamp(e,t){return`${t?.user?.userSnippylyId}-${t.timestamp}`}getDocumentViews(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentViews","color: green;"),this.uniqueViewsByUserSubscription&&(this.componentConfigSignal.update(e=>(e=y(m({},e),{totalUniqueViews:{},totalUniqueViewsCount:0}),e)),this.uniqueViewsByUserSubscription.unsubscribe()),this.uniqueViewsByDateSubscription&&(this.componentConfigSignal.update(e=>(e=y(m({},e),{todayViews:{},todayViewsCount:0}),e)),this.uniqueViewsByDateSubscription.unsubscribe()),this.uniqueViewsByUserSubscription=this.viewsService.getUniqueViewsByUser(this.clientLocationId).subscribe(e=>{this.componentConfigSignal.update(t=>(t=y(m({},t),{totalUniqueViews:e||{},totalUniqueViewsCount:Object.keys(e||{})?.length||0}),t)),this.setLatestViewsByUsers()},e=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUniqueViewsByUser subscription: ",e)}),this.uniqueViewsByDateSubscription=this.viewsService.getUniqueViewsByDate(this.clientLocationId).subscribe(e=>{this.componentConfigSignal.update(t=>(t=m({},t),t.todayViews=e&&e[t.today]?e[t.today]:{},t.todayViewsCount=Object.keys(t.todayViews||{})?.length||0,t)),this.setLatestViewsByUsers()},e=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUniqueViewsByDate subscription: ",e)})}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent getDocumentViews: ",e)}}setLatestViewsByUsers(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLatestViewsByUsers","color: green;"),Object.keys(this.componentConfigSignal().todayViews||{}).forEach(e=>{let t=this.componentConfigSignal().usersMap[e],n=this.componentConfigSignal().todayViews[e]?.timestamp;t&&n&&(this.componentConfigSignal().userViews.find(o=>o.user.userSnippylyId===e)||this.componentConfigSignal.update(o=>(o=y(m({},o),{userViews:[...o.userViews,{user:t,timestamp:n}]}),o)))}),this.componentConfigSignal.update(e=>(e=m({},e),e.userViews.sort((t,n)=>n.timestamp-t.timestamp),e.userViews=e.userViews.slice(0,3),e))}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent setLatestViewsByUsers: ",e)}}closeTrendDialog(){try{this.close.emit(),this.closeBottomSheetFn&&this.closeBottomSheetFn?.()}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent onClose: ",e)}}ngOnDestroy(){try{this.subscriptions.forEach(e=>{e.unsubscribe()}),this.uniqueViewsByDateSubscription?.unsubscribe(),this.uniqueViewsByUserSubscription?.unsubscribe()}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent ngOnDestroy: ",e)}}};c.\u0275fac=function(t){return new(t||c)(I(ot),I(C),I(P),I(rt),I(oe),I(ue),I(qe,8))},c.\u0275cmp=Q({type:c,selectors:[["velt-view-analytics-dialog"]],inputs:{clientLocationId:"clientLocationId"},outputs:{close:"close"},standalone:!1,decls:1,vars:1,consts:[["defaultDialogRef",""],[4,"ngIf"],["snippylyClickOutside","",1,"v-view-analytics-dialog-container",3,"clickOutside"],[4,"ngIf","ngIfElse"],[1,"v-back-btn-container"],[1,"v-back-btn",3,"click"],["width","16","height","16","viewBox","0 0 16 16","fill","none","xmlns","http://www.w3.org/2000/svg"],["d","M9.99988 4L5.99988 8L9.99988 12","stroke","currentColor","stroke-width","1.33333","stroke-linecap","round","stroke-linejoin","round"],[1,"v-view-analytics-count-container"],[1,"v-total-views-container"],[1,"v-total-views-count"],[1,"v-total-views-text"],["width","18","height","18","viewBox","0 0 18 18","fill","none","xmlns","http://www.w3.org/2000/svg"],["d","M7.5 9C7.5 9.39782 7.65804 9.77936 7.93934 10.0607C8.22064 10.342 8.60218 10.5 9 10.5C9.39782 10.5 9.77936 10.342 10.0607 10.0607C10.342 9.77936 10.5 9.39782 10.5 9C10.5 8.60218 10.342 8.22064 10.0607 7.93934C9.77936 7.65804 9.39782 7.5 9 7.5C8.60218 7.5 8.22064 7.65804 7.93934 7.93934C7.65804 8.22064 7.5 8.60218 7.5 9Z","stroke","#625DF5","stroke-width","1.25","stroke-linecap","round","stroke-linejoin","round"],["d","M15.75 9C13.95 12 11.7 13.5 9 13.5C6.3 13.5 4.05 12 2.25 9C4.05 6 6.3 4.5 9 4.5C11.7 4.5 13.95 6 15.75 9Z","stroke","#625DF5","stroke-width","1.25","stroke-linecap","round","stroke-linejoin","round"],[1,"v-today-views-container"],[1,"v-today-views-count"],[1,"v-today-views-text"],["class","v-users-container",4,"ngIf"],[1,"v-users-container"],[4,"ngFor","ngForOf"],[1,"v-user"],[1,"v-user-image"],[3,"user","size"],[1,"v-user-view-details"],[1,"v-user-name"],[1,"v-user-view-time"],[1,"v-document-viewer-tread-left"],["class","v-document-viewer-tread-right",4,"ngIf"],[1,"v-document-viewer-tread-right"]],template:function(t,n){t&1&&T(0,Dt,5,4,"ng-container",1),t&2&&D("ngIf",n.componentConfigSignal())},dependencies:[Te,le,at,ct,st,gt],styles:[`.v-view-analytics-dialog-container{border-radius:var(--legacy-velt-view-analytics-dialog-border-radius);border:var(--legacy-velt-view-analytics-dialog-border);background:var(--legacy-velt-view-analytics-dialog-bg-color);box-shadow:var(--legacy-velt-view-analytics-dialog-box-shadow);padding:var(--legacy-velt-view-analytics-dialog-padding);display:flex;gap:16px}.v-view-analytics-dialog-container .v-document-viewer-tread-left{display:flex;flex-direction:column;gap:4px}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container{width:140px;height:110px;flex-shrink:0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color);box-sizing:border-box;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:10px}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container .v-total-views-count{color:var(--legacy-velt-view-analytics-dialog-total-views-count-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container .v-total-views-text{color:var(--legacy-velt-view-analytics-dialog-total-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-today-views-container{display:flex;width:140px;padding:8px 4px;justify-content:center;align-items:center;gap:4px;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color);box-sizing:border-box;color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}.v-view-analytics-dialog-container .v-document-viewer-tread-right{padding:8px 0}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container{display:inline-flex;flex-direction:column;align-items:flex-start;gap:16px;margin-right:16px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user{display:flex;align-items:center;gap:12px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user snippyly-user-avatar{display:flex}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details{display:flex;flex-direction:column;gap:8px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details .v-user-name{color:var(--legacy-velt-view-analytics-dialog-user-name-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details .v-user-view-time{color:var(--legacy-velt-view-analytics-dialog-user-timestamp-color);font-size:10px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}.v-view-analytics-dialog-container.bottom-sheet{display:flex;flex-direction:column;border-bottom-left-radius:0;border-bottom-right-radius:0}.v-view-analytics-dialog-container.bottom-sheet .v-back-btn-container{display:flex;padding:8px 8px 0}.v-view-analytics-dialog-container.bottom-sheet .v-back-btn-container .v-back-btn{background:transparent;border:0;outline:0;display:flex;align-items:center;gap:8px;color:var(--legacy-velt-view-analytics-dialog-back-btn-color);cursor:pointer;font-size:16px;font-style:normal;font-weight:400;line-height:normal}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container{display:flex;flex:1;gap:10px}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container{display:flex;padding:25px 20px;flex-direction:column;justify-content:center;align-items:center;gap:10px;flex:1 0 0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color)}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container .v-total-views-count{color:var(--legacy-velt-view-analytics-dialog-total-views-count-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container .v-total-views-text{color:var(--legacy-velt-view-analytics-dialog-total-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container{display:flex;padding:25px 20px;flex-direction:column;justify-content:center;align-items:center;gap:10px;flex:1 0 0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color)}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container .v-today-views-count{color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container .v-today-views-text{color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container.bottom-sheet .v-users-container{display:inline-flex;flex-direction:column;align-items:flex-start;gap:16px;margin-right:16px}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user{display:flex;align-items:center;gap:12px;width:100%}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user snippyly-user-avatar{display:flex}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-details{display:flex;flex-direction:column;gap:8px;flex:1}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-details .v-user-name{color:var(--legacy-velt-view-analytics-dialog-user-name-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-time{color:var(--legacy-velt-view-analytics-dialog-user-timestamp-color);font-size:10px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}
1
+ import{t as lt}from"./chunk-VFYLOVTK.js";import"./chunk-CQZ7DKJB.js";import"./chunk-ZURN7SUE.js";import{a as qe,c as Ge,d as We}from"./chunk-MU6RYO5X.js";import{a as ut}from"./chunk-KXEU5HGR.js";import"./chunk-J2NS4TI4.js";import{a as at}from"./chunk-ZEWGJF7N.js";import{a as gt}from"./chunk-F2XJIYNI.js";import"./chunk-KE64O5B7.js";import"./chunk-TDVYFBCW.js";import{b as st,d as ct}from"./chunk-RCOPSCV6.js";import{a as dt}from"./chunk-TM2JOAC4.js";import{a as Le}from"./chunk-6F7MEOHL.js";import{A as ze,Fa as ot,G as Pe,H as Ne,Ha as rt,I as Fe}from"./chunk-EIDOVJ3L.js";import{a as mt}from"./chunk-D2UJGDHP.js";import{A as ve,f as ge,z as nt}from"./chunk-COMT5MGY.js";import{$j as it,Bb as x,Dj as fe,E as B,Fi as ye,Gd as Me,Ha as h,Hc as Te,He as E,Ia as re,Ic as le,Ii as Ye,Ij as z,K as te,Kb as se,Lj as et,M as K,Mb as ae,O as Ce,Pb as _,Qb as J,Ra as I,Rb as R,Rc as $e,Rj as tt,Tb as Ue,U as De,V as S,Va as Be,Vd as Re,Wa as Q,Wd as je,Xa as Ae,Xi as Qe,Y as xe,Zf as we,_ as ie,_j as ue,a as m,ab as T,ai as He,b as y,ba as _e,ca as Ee,cc as ke,ci as de,ea as k,g as j,ij as Ze,ja as N,ka as F,l as $,la as H,lj as me,ma as Y,mc as A,nb as D,nc as U,nj as C,ob as v,oj as Xe,pb as w,qb as L,qe as Je,r as V,rc as ce,sa as ne,t as Ie,ub as q,v as f,vb as G,w as Z,wa as Oe,wg as Ke,xb as W,ya as oe,zb as M}from"./chunk-V53LQO22.js";var P=(()=>{let c=class c{constructor(e,t,n,i,o,a,l,s,u,p){this.afAuth=e,this.authService=t,this.configService=n,this.databaseService=i,this.docService=o,this.commonDbService=a,this.iamService=l,this.loggingService=s,this.userPermissionService=u,this.serviceBook=p,this.documentPaths=null,this.views$=new $({}),this.commentViews$=new $({}),this.documentViews$=new $({}),this.locationViews$=new $({}),this.commentViewsByOrganizationIdAndDocumentId$=new $({}),this.documentViewsByOrganizationIdAndDocumentId$=new $({}),this.locationViewsByOrganizationIdAndLocationId$=new $({}),this.documentViewsEnabled$=new $(!1),this.documentViewsSetByDocumentId={},this.notificationService=null,this.loggingService.log("%c[WB] Creating CLASS: ViewsService","color: blue;");try{this.serviceBook.observe(Qe).subscribe(g=>{this.commentService=g??void 0}),this.serviceBook.observe(Ye).subscribe(g=>{this.notificationService=g??null}),this.viewsDbReadyGate$().pipe(te(1)).subscribe(()=>{this.subscribeViewsData().subscribe(),this.getNotificationFeatureViews$().subscribe(g=>{this.notificationService?.setNotificationViews(g)}),this.authService.getUser$().pipe(B(g=>!!g),S(g=>this.documentViewsEnabled$.pipe(B(b=>b),f(()=>g))),S(g=>this.docService.getDocumentPaths$().pipe(De(null),Ce(),f(([b,O])=>(b?.documentId!==O?.documentId&&this.views$.next({}),O)),f(b=>(this.documentPaths=b,this.setDocumentAsRead({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),{_user:g,_documentPaths:b})),S(b=>this.docService.getDocumentIds$().pipe(S(O=>(O?.length&&(O.find(ee=>ee.documentId===this.documentPaths?.documentId)||O.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),O.forEach(ee=>{this.setDocumentAsRead({documentId:ee.documentId,clientDocumentId:ee.clientDocumentId})})),V(b))))))),S(g=>this.docService.getDocumentMetadata$().pipe(B(b=>!!b),f(b=>y(m({},g),{_documentMetadata:b}))))).subscribe(),this.authService.getUser$().pipe(B(g=>!!g),S(g=>this.documentViewsEnabled$.pipe(B(b=>b),f(()=>g))),S(g=>this.docService.getLocation$().pipe(B(b=>!!b))),S(g=>this.docService.getDocumentIds$().pipe(S(b=>(b.find(O=>O.documentId===this.documentPaths?.documentId)||b.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),b.forEach(O=>{this.setLocationAsRead({documentId:O.documentId,clientDocumentId:O.clientDocumentId})}),V(g)))))).subscribe()},g=>{this.loggingService.catch("Error in ViewsService getDb subscription: ",g)})}catch(g){this.loggingService.catch("Error in ViewsService constructor: ",g)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ViewsService","color: green;");try{this.documentPaths=null,this.documentViews$.next({}),this.views$.next({}),this.commentViews$.next({}),this.locationViews$.next({}),this.commentViewsByOrganizationIdAndDocumentId$.next({}),this.documentViewsByOrganizationIdAndDocumentId$.next({}),this.locationViewsByOrganizationIdAndLocationId$.next({})}catch(e){this.loggingService.catch("Error in ViewsService clearCache: ",e)}}subscribeViewsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let n,i;try{if(e&&(i=we(e)),t&&typeof t=="object"){let o=Ke(t);n=we(JSON.stringify(o))}}catch(o){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",o)}return this.authService.getAuthState$().pipe(B(o=>!!o),S(o=>this.isFeatureAllowed({firebaseUser:o})),S(o=>o.featureAllowed?this.iamService.isUserAllowed$().pipe(f(a=>(o.featureAllowed=a,o))):V(o)),S(o=>o.featureAllowed?V(o).pipe(S(a=>this.docService.getDocumentPaths$().pipe(f(l=>(this.documentPaths=l,a.documentPaths=l,a)))),S(a=>i?this.getDataFromDocumentIds([i]):this.docService.getDocumentIds$().pipe(S(l=>{let s=l?.length>0?l.map(u=>u.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(s)})))):V([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(B(t=>!!t),f(t=>y(m({},e),{config:t})),S(t=>this.authService.getUser$().pipe(f(n=>y(m({},t),{user:n})))),S(t=>t.user?V(y(m({},t),{featureAllowed:!0})):V(y(m({},t),{featureAllowed:!1}))),K((t,n)=>t?.featureAllowed===n?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getCommentViewsById(e){try{return this.commentViews$.value?.[e]?this.commentViews$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in ViewsService getCommentViewsById: ",t);return}}getDocumentViewsById(e){try{return this.documentViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getDocumentViewsById: ",t);return}}getLocationViewsById(e){try{return this.locationViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getLocationViewsById: ",t);return}}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:n}=e;return t?.some(i=>!i)||!this.documentPaths?V([]):this.documentViewsEnabled$.pipe(S(i=>i?Z([this.getCommentViewsDataFromDocuments(),this.getDocumentViewsDataFromDocuments(t),this.getLocationViewsDataFromDocuments(t)]):Z([this.getCommentViewsDataFromDocuments()])))}else return V(null)}getCommentViews(e){try{let t={};Object.entries(e??{}).forEach(([n,i])=>{let o=i.metadata?.documentId,a=i.views;!o||!a||(t[o]||(t[o]={}),t[o][i.annotationId]=a)}),Object.entries(t??{}).forEach(([n,i])=>{this.setCommentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:n,commentViews:i})})}catch(t){this.loggingService.catch("Error in ViewsService getCommentViews: ",t)}}getCommentViewsDataFromDocuments(){try{return this.commentService?this.commentService?.getAllCommentAnnotations({detectGhostComments:!0,addFilterCommentsOnDomCheck:!0,fromCommentSidebar:!0,skipPositionCalculation:!0,analytics:{enabled:!0,properties:{source:"internal",sourceId:"commentsContainer"}}}).pipe(B(e=>!!e),xe(e=>{this.getCommentViews(e)})):V([])}catch(e){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",e),V([])}}viewsDbReadyGate$(){return tt({isPortableFeedActive:()=>this.commonDbService?.usesPortableChannelFeed(ge),firebaseDb$:()=>this.databaseService.getDb(),onError:(e,t)=>this.loggingService.catch(`Error in ViewsService viewsDbReadyGate$ ${e}: `,t)})}getDocumentViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,n=V([]),i={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(i.documentId=e?.length?e[0]:void 0,i.organizationId=this.documentPaths?.organizationId),this.commonDbService.usesPortableChannelFeed(ge))n=this.commonDbService.dbListener({feature:"allDocumentViews",properties:y(m({},i),{organizationId:this.documentPaths?.organizationId,documentIds:e})}).pipe(ie(),f(o=>de(JSON.parse(JSON.stringify([o])))));else{let o=[];for(let a=0;a<(e?.length??0);a+=E.LISTENER_BATCH_SIZE)o.push(e?.slice(a,a+E.LISTENER_BATCH_SIZE)??[]);n=Z(o.map(a=>this.commonDbService.dbListener({feature:"allDocumentViews",properties:y(m({},i),{firestoreQuery:[fe(z("metadata.apiKey","==",this.configService?.getApiKey()),z("metadata.documentId","in",a),z("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[z("metadata.veltFolderId","==",t)]:[])]})}).pipe(ie()))).pipe(f(a=>de(a)))}return n.pipe(f(o=>({data:o?.data,operation:o?.operation})),f(({data:o,operation:a})=>{let l={};return e?(Object.entries(o??{}).forEach(([s,u])=>{let p=u.metadata?.documentId;p&&(l[p]||(l[p]={}),l[p][s]=u)}),{data:o,documentMap:l,operation:a}):{data:o,documentMap:l,operation:a}}),f(({data:o,documentMap:a,operation:l})=>{if(l?.type==="removed"){if(l?.ids?.length){let s=this.documentViews$.value;l?.ids?.forEach(u=>{delete s?.[u]}),this.documentViews$.next(s)}}else Object.entries(a??{}).forEach(([s,u])=>{this.setDocumentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:s,documentViews:u})})}))}getLocationViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,n=V([]),i={useCollectionGroup:!0,isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(i.documentId=e?.length?e[0]:void 0,i.organizationId=this.documentPaths?.organizationId);let o=[];for(let a=0;a<(e?.length??0);a+=E.LISTENER_BATCH_SIZE)o.push(e?.slice(a,a+E.LISTENER_BATCH_SIZE)??[]);return n=Z(o.map(a=>this.commonDbService.dbListener({feature:"allLocationViews",properties:y(m({},i),{firestoreQuery:[fe(z("metadata.apiKey","==",this.configService?.getApiKey()),z("metadata.documentId","in",a),z("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[z("metadata.veltFolderId","==",t)]:[])]})}).pipe(ie()))).pipe(f(a=>de(a))),n.pipe(f(a=>({data:a?.data,operation:a?.operation})),f(({data:a,operation:l})=>{let s={};return e?(Object.entries(a??{}).forEach(([u,p])=>{let g=p.metadata?.documentId;g&&(s[g]||(s[g]={}),s[g][u]=p)}),{data:a,documentMap:s,operation:l}):{data:a,documentMap:s,operation:l}}),f(({data:a,documentMap:l,operation:s})=>{if(s?.type==="removed"){if(s?.ids?.length){let u=this.locationViews$.value;s?.ids?.forEach(p=>{delete u?.[p]}),this.locationViews$.next(u)}}else Object.entries(l??{}).forEach(([u,p])=>{this.setLocationViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:u,locationViews:p})})}))}setViewsData(e){try{this.views$.next(m(m({},this.views$.getValue()),e||{}))}catch(t){this.loggingService.catch("Error in ViewsService setViewsData:",t)}}setCommentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,commentViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.commentViews$.value),n);this.commentViews$.next(o),this.commentViewsByOrganizationIdAndDocumentId$.next(y(m({},this.commentViewsByOrganizationIdAndDocumentId$.value),{[e]:y(m({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]),{[t]:y(m({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}setDocumentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,documentViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.documentViews$.value),n);this.documentViews$.next(o),this.documentViewsByOrganizationIdAndDocumentId$.next(y(m({},this.documentViewsByOrganizationIdAndDocumentId$.value),{[e]:y(m({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]),{[t]:y(m({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}setLocationViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,locationViews:n,queryHash:i}){try{if(n||(n={}),t){e||(e=E.NO_ORGANIZATION_ID),i||(i=E.DEFAULT_QUERY_HASH);let o=m(m({},this.locationViews$.value),n);this.locationViews$.next(o),this.locationViewsByOrganizationIdAndLocationId$.next(y(m({},this.locationViewsByOrganizationIdAndLocationId$.value),{[e]:y(m({},this.locationViewsByOrganizationIdAndLocationId$.value[e]),{[t]:y(m({},this.locationViewsByOrganizationIdAndLocationId$.value[e]?.[t]),{[i]:n})})}))}}catch(o){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",o)}}getCommentFeatureViews$(){return this.commentViews$.pipe(K((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}setCommentAnnotationAsRead(e){return j(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){if(e.annotationId.startsWith("TEMP_COMPOSER_"))return;this.updateCommentAnnotationViews(e);let n=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",i=e?.metadata?.documentId??this.documentPaths?.documentId??"";if(e?.isDraft)return;yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:i,organizationId:n,metadata:{apiKey:this.configService.getApiKey(),organizationId:n,veltFolderId:e?.metadata?.veltFolderId,documentId:i}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}setCommentAnnotationAsUnread(e){return j(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){if(e.annotationId.startsWith("TEMP_COMPOSER_"))return;this.removeCommentAnnotationViews(e);let n=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",i=e?.metadata?.documentId??this.documentPaths?.documentId??"";if(e?.isDraft)return;yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:i,organizationId:n,metadata:{apiKey:this.configService.getApiKey(),organizationId:n,veltFolderId:e?.metadata?.veltFolderId,documentId:i}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}updateCommentAnnotationViews(e){try{let t=this.authService.getUser(),n={views:{},comments:{}};if(t){let i={},o=e?.views?.comments||{},a=new Date().getTime()+this.commonDbService.getOffset();e.comments?.forEach(s=>{o[s.commentId]||(o[s.commentId]={views:{}}),o[s.commentId].views||(o[s.commentId].views={}),o[s.commentId].views[t.userSnippylyId]||(o[s.commentId].views[t.userSnippylyId]={timestamp:a})});let l=new Set(e.comments?.map(s=>s.commentId+""));if(Object.keys(o??{}).forEach(s=>{l.has(s)||delete o[s]}),e.comments?.length){let s=o[e.comments[0].commentId]?.views||{},u=Object.keys(s??{}).filter(p=>e.comments?.every(g=>o[g.commentId]?.views?.[p]));u.forEach(p=>{i[p]={timestamp:s[p].timestamp}}),e.viewedByUserIds=u}n.views=i,n.comments=o,e.views=n}return n}catch(t){return this.loggingService.catch("Error in ViewsService updateCommentAnnotationViews:",t),{views:{},comments:{}}}}removeCommentAnnotationViews(e){try{let t=this.authService.getUser(),n={views:{},comments:{}};if(t){let i={},o=e?.views?.comments||{};e.comments?.forEach(l=>{o[l.commentId]?.views?.[t.userSnippylyId]&&delete o[l.commentId].views[t.userSnippylyId]});let a=new Set(e.comments?.map(l=>l.commentId+""));if(Object.keys(o??{}).forEach(l=>{a.has(l)||delete o[l]}),e.comments?.length){let l=o[e.comments[0].commentId]?.views||{},s=Object.keys(l??{}).filter(u=>e.comments?.every(p=>o[p.commentId]?.views?.[u]));s.forEach(u=>{i[u]={timestamp:l[u].timestamp}}),e.viewedByUserIds=s}else e.viewedByUserIds=[];n.views=i,n.comments=o,e.views=n}return n}catch(t){return this.loggingService.catch("Error in ViewsService removeCommentAnnotationViews:",t),{views:{},comments:{}}}}getNotificationFeatureViews$(){return this.views$.pipe(K((e,t)=>JSON.stringify(e?.notification||{})===JSON.stringify(t?.notification||{})))}setNotificationsAsRead(e){try{let t=this.authService.getUser();if(t){let n=new Date().getTime()+this.commonDbService.getOffset();e.forEach(i=>{this.commonDbService.updateData({feature:"notificationViewsTimestamp",properties:{id:i,user:t.userSnippylyId,documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??""},data:{timestamp:n}})})}}catch(t){this.loggingService.catch("Error in ViewsService setNotificationAsRead:",t)}}getDocumentViews$(){return this.views$.pipe(K((e,t)=>JSON.stringify(e?.documentViews||{})===JSON.stringify(t?.documentViews||{})))}getUniqueViewsByUser(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(S(t=>(this.documentPaths=t,e?this.locationViews$.pipe(f(n=>{let i=Object.keys(n||{}).find(o=>n?.[o]?.location?.id===e);return i?n?.[i]?.users||{}:{}})):this.documentViews$.pipe(f(n=>{let i=this.documentPaths?.documentId;return i?n?.[i]?.users||{}:{}})))),K(He))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByUser:",t),V({})}}getUniqueViewsByDate(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(S(t=>(this.documentPaths=t,e?this.locationViews$.pipe(f(n=>{let i=Object.keys(n||{}).find(o=>n?.[o]?.location?.id===e);return i?n?.[i]?.day||{}:{}})):this.documentViews$.pipe(f(n=>{let i=this.documentPaths?.documentId;return i?n?.[i]?.day||{}:{}})))))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByDate:",t),V({})}}enableDocumentViews(){try{if(this.documentViewsEnabled$.value===!0)return;this.documentViewsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ViewsService enableDocumentViews:",e)}}disableDocumentViews(){try{if(this.documentViewsEnabled$.value===!1)return;this.documentViewsEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ViewsService disableDocumentViews:",e)}}setDocumentAsRead(n){return j(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let i=this.authService.getUser();if(i&&e&&this.userPermissionService?.hasEditAccess({documentId:e??"",folderId:this.documentPaths?.allDocuments&&this.documentPaths?.veltFolderId?this.documentPaths?.veltFolderId:void 0})){if(this.documentViewsSetByDocumentId[e])return;this.documentViewsSetByDocumentId[e]=!0;let o=new Date().getTime()+this.commonDbService.getOffset(),a=new Date().toISOString().split("T")[0];if(this.commonDbService.usesPortableChannelFeed(ge)){let s=yield Ie(this.docService.getDocumentPaths$().pipe(f(u=>u?.organizationId),B(u=>!!u)));yield this.commonDbService.whenPortableRealtimeReady(),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:a,user:i.userSnippylyId,documentId:e,organizationId:s},data:{}}),this.checkAndTriggerNotification(i);return}let l=this.getDocumentViewsById(e);if(l){let s=new Date().toISOString().split("T")[0];l?.users[i.userSnippylyId]||(l.users[i.userSnippylyId]={}),l.users[i.userSnippylyId][s]={timestamp:this.timestamp},l?.day[s]||(l.day[s]={}),l.day[s][i.userSnippylyId]={timestamp:this.timestamp},l.metadata=this.docService.getBaseMetadata("documentViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:s,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??""},data:l})}else this.commonDbService.updateData({feature:"documentDayViews",properties:{id:e,date:a,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:o}}),this.commonDbService.updateData({feature:"documentUsersViews",properties:{id:e,user:i.userSnippylyId,date:a,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:o}}),this.commonDbService.updateData({feature:"documentMetadataViews",properties:{id:e,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})}),this.docService.getDocumentMetadata$(e).pipe(B(s=>s!==null),te(1)).subscribe(()=>{let s={day:{[a]:{[i.userSnippylyId]:{timestamp:o}}},users:{[i.userSnippylyId]:{[a]:{timestamp:o}}},metadata:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})};this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:a,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0},data:s})});this.checkAndTriggerNotification(i)}}catch(i){this.loggingService.catch("Error in ViewsService setDocumentAsRead:",i)}})}checkAndTriggerNotification(e){try{this.getUniqueViewsByUser().pipe(te(1)).subscribe(t=>{if(Object.keys(t??{}).length===2){let n=this.docService.getDocumentMetadata();if(n?.creator?.email&&n?.creator?.email!==e.email){let i=[n.creator.email];this.updateNotificationsDatabase(Je.FIRST_VIEWED,{documentViews:{emails:i}})}}})}catch(t){this.loggingService.catch("Error in checkAndTriggerNotification:",t)}}setLocationAsRead(n){return j(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let i=this.authService.getUser(),o=this.docService.getLocation(),a=o?.locationId,l=o?.location;if(i&&a&&l){let s=new Date().getTime()+this.commonDbService.getOffset(),u=new Date().toISOString().split("T")[0],p=this.getLocationViewsById(a);if(p){let g=new Date().toISOString().split("T")[0];p?.users[i.userSnippylyId]||(p.users[i.userSnippylyId]={}),p.users[i.userSnippylyId][g]={timestamp:this.timestamp},p?.day[g]||(p.day[g]={}),p.day[g][i.userSnippylyId]={timestamp:this.timestamp},p.metadata=this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"location",data:p,properties:{id:a,documentId:e,organizationId:this.documentPaths?.organizationId??""}})}else{this.commonDbService.updateData({feature:"locationViews",data:l,properties:{id:a,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}}),this.commonDbService.updateData({feature:"locationUsersViews",properties:{id:a,user:i.userSnippylyId,date:u,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:s}}),this.commonDbService.updateData({feature:"locationDayViews",properties:{id:a,date:u,user:i.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:s}}),this.commonDbService.updateData({feature:"locationMetadataViews",properties:{id:a,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t})});let g={day:{[u]:{[i.userSnippylyId]:{timestamp:s}}},users:{[i.userSnippylyId]:{[u]:{timestamp:s}}},metadata:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),location:l};this.commonDbService.updateData({feature:"location",data:g,properties:{id:a,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0}})}}}catch(i){this.loggingService.catch("Error in ViewsService setLocationAsRead:",i)}})}updateNotificationsDatabase(e,t={}){try{let n=m({actionType:e,notificationSource:"documentViews"},t);this.notificationService?.updateNotificationDatabase(n)}catch(n){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",n)}}get timestamp(){return this.commonDbService.getServerTimestamp()}};c.\u0275fac=function(t){return new(t||c)(k(Me),k(it),k(Xe),k(et),k(ve),k(nt),k(dt),k(C),k(ut),k(me))},c.\u0275prov=_e({token:c,factory:c.\u0275fac,providedIn:"root"});let d=c;return d})();function ft(d,c){if(d&1&&(q(0),v(1,"div",21)(2,"div",22),L(3,"snippyly-user-avatar",23),w(),v(4,"div",24)(5,"div",25),_(6),A(7,"translate"),w()(),v(8,"div",26),_(9),A(10,"timeAgo"),w()(),G()),d&2){let r=c.$implicit;h(3),D("user",r==null?null:r.user)("size",32),h(3),R(" ",U(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),h(3),R(" ",U(10,6,r==null?null:r.timestamp)," ")}}function St(d,c){if(d&1&&(v(0,"div",19),T(1,ft,11,8,"ng-container",20),w()),d&2){let r=x(2).ngIf;h(),D("ngForOf",r.userViews)}}function bt(d,c){if(d&1){let r=W();q(0),v(1,"div",4)(2,"button",5),M("click",function(){N(r);let t=x(2);return F(t.closeTrendDialog())}),H(),v(3,"svg",6),L(4,"path",7),w(),Y(),v(5,"span"),_(6),A(7,"translate"),w()()(),v(8,"div",8)(9,"div",9)(10,"div",10),_(11),w(),v(12,"div",11),H(),v(13,"svg",12),L(14,"path",13)(15,"path",14),w(),Y(),v(16,"span"),_(17),A(18,"translate"),w()()(),v(19,"div",15)(20,"div",16),_(21),w(),v(22,"div",17)(23,"span"),_(24),A(25,"translate"),w()()()(),T(26,St,2,1,"div",18),G()}if(d&2){let r=x().ngIf;h(6),J(U(7,6,"Go Back")),h(5),R(" ",r.totalUniqueViewsCount," "),h(6),J(U(18,8,"Total Views")),h(4),R(" ",r.todayViewsCount," "),h(3),J(U(25,10,"Views Today")),h(2),D("ngIf",r.userViews==null?null:r.userViews.length)}}function Vt(d,c){if(d&1&&(q(0),v(1,"div",21)(2,"div",22),L(3,"snippyly-user-avatar",23),w(),v(4,"div",24)(5,"div",25),_(6),A(7,"translate"),w(),v(8,"div",26),_(9),A(10,"timeAgo"),w()()(),G()),d&2){let r=c.$implicit;h(3),D("user",r==null?null:r.user)("size",32),h(3),R(" ",U(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),h(3),R(" ",U(10,6,r==null?null:r.timestamp)," ")}}function It(d,c){if(d&1&&(v(0,"div",29)(1,"div",19),T(2,Vt,11,8,"ng-container",20),w()()),d&2){let r=x(2).ngIf;h(2),D("ngForOf",r.userViews)}}function Ct(d,c){if(d&1&&(v(0,"div",27)(1,"div",9)(2,"div",10),_(3),w(),v(4,"div",11),H(),v(5,"svg",12),L(6,"path",13)(7,"path",14),w(),Y(),v(8,"span"),_(9),A(10,"translate"),w()()(),v(11,"div",15),_(12),A(13,"translate"),A(14,"translate"),A(15,"translate"),w()(),T(16,It,3,1,"div",28)),d&2){let r=x().ngIf;h(3),R(" ",r.totalUniqueViewsCount," "),h(6),J(U(10,6,"Total Views")),h(3),Ue(" ",r.todayViewsCount," ",r.todayViewsCount===1?U(13,8,"View"):U(14,10,"Views")," ",U(15,12,"Today")," "),h(4),D("ngIf",r.userViews==null?null:r.userViews.length)}}function Dt(d,c){if(d&1){let r=W();q(0),v(1,"div",2),M("clickOutside",function(){N(r);let t=x();return F(t.closeTrendDialog())}),T(2,bt,27,12,"ng-container",3)(3,Ct,17,14,"ng-template",null,0,ce),w(),G()}if(d&2){let r=c.ngIf,e=se(4);h(),ae("bottom-sheet",r.bottomSheetMode),h(),D("ngIf",r.bottomSheetMode)("ngIfElse",e)}}var X=(()=>{let c=class c{constructor(e,t,n,i,o,a,l){this.contactService=e,this.loggingService=t,this.viewsService=n,this.themeService=i,this.elementRef=o,this.domService=a,this.bottomSheetData=l,this.close=new re,this.componentConfigSignal=ne({today:new Date().toISOString().split("T")[0],todayViews:{},todayViewsCount:0,totalUniqueViews:{},totalUniqueViewsCount:0,views:{},usersMap:{},userViews:[],bottomSheetMode:!1}),this.subscriptions=[];try{l&&(this.componentConfigSignal.update(s=>(s=y(m({},s),{bottomSheetMode:!0}),s)),this.clientLocationId=l.clientLocationId,this.closeBottomSheetFn=l.closeBottomSheetFn),this.subscriptions.push(this.contactService.getUsersMap$().subscribe(s=>{this.componentConfigSignal.update(u=>(u=y(m({},u),{usersMap:s||{}}),u)),this.setLatestViewsByUsers()},s=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUsersMap$ subscription: ",s)})),this.subscriptions.push(this.themeService.getDarkMode$().subscribe(s=>{s?this.elementRef.nativeElement.setAttribute("dark",""):this.elementRef.nativeElement.removeAttribute("dark")}))}catch(s){this.loggingService.catch("Error in ViewAnalyticsDialogComponent constructor: ",s)}}ngOnInit(){this.getDocumentViews()}ngAfterViewInit(){try{this.subscriptions.push(this.domService.subscribeInjectCustomCss(this.elementRef))}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent ngAfterViewInit: ",e)}}trackByUserIdAndTimestamp(e,t){return`${t?.user?.userSnippylyId}-${t.timestamp}`}getDocumentViews(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentViews","color: green;"),this.uniqueViewsByUserSubscription&&(this.componentConfigSignal.update(e=>(e=y(m({},e),{totalUniqueViews:{},totalUniqueViewsCount:0}),e)),this.uniqueViewsByUserSubscription.unsubscribe()),this.uniqueViewsByDateSubscription&&(this.componentConfigSignal.update(e=>(e=y(m({},e),{todayViews:{},todayViewsCount:0}),e)),this.uniqueViewsByDateSubscription.unsubscribe()),this.uniqueViewsByUserSubscription=this.viewsService.getUniqueViewsByUser(this.clientLocationId).subscribe(e=>{this.componentConfigSignal.update(t=>(t=y(m({},t),{totalUniqueViews:e||{},totalUniqueViewsCount:Object.keys(e||{})?.length||0}),t)),this.setLatestViewsByUsers()},e=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUniqueViewsByUser subscription: ",e)}),this.uniqueViewsByDateSubscription=this.viewsService.getUniqueViewsByDate(this.clientLocationId).subscribe(e=>{this.componentConfigSignal.update(t=>(t=m({},t),t.todayViews=e&&e[t.today]?e[t.today]:{},t.todayViewsCount=Object.keys(t.todayViews||{})?.length||0,t)),this.setLatestViewsByUsers()},e=>{this.loggingService.catch("Error in ViewAnalyticsDialogComponent getUniqueViewsByDate subscription: ",e)})}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent getDocumentViews: ",e)}}setLatestViewsByUsers(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLatestViewsByUsers","color: green;"),Object.keys(this.componentConfigSignal().todayViews||{}).forEach(e=>{let t=this.componentConfigSignal().usersMap[e],n=this.componentConfigSignal().todayViews[e]?.timestamp;t&&n&&(this.componentConfigSignal().userViews.find(o=>o.user.userSnippylyId===e)||this.componentConfigSignal.update(o=>(o=y(m({},o),{userViews:[...o.userViews,{user:t,timestamp:n}]}),o)))}),this.componentConfigSignal.update(e=>(e=m({},e),e.userViews.sort((t,n)=>n.timestamp-t.timestamp),e.userViews=e.userViews.slice(0,3),e))}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent setLatestViewsByUsers: ",e)}}closeTrendDialog(){try{this.close.emit(),this.closeBottomSheetFn&&this.closeBottomSheetFn?.()}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent onClose: ",e)}}ngOnDestroy(){try{this.subscriptions.forEach(e=>{e.unsubscribe()}),this.uniqueViewsByDateSubscription?.unsubscribe(),this.uniqueViewsByUserSubscription?.unsubscribe()}catch(e){this.loggingService.catch("Error in ViewAnalyticsDialogComponent ngOnDestroy: ",e)}}};c.\u0275fac=function(t){return new(t||c)(I(ot),I(C),I(P),I(rt),I(oe),I(ue),I(qe,8))},c.\u0275cmp=Q({type:c,selectors:[["velt-view-analytics-dialog"]],inputs:{clientLocationId:"clientLocationId"},outputs:{close:"close"},standalone:!1,decls:1,vars:1,consts:[["defaultDialogRef",""],[4,"ngIf"],["snippylyClickOutside","",1,"v-view-analytics-dialog-container",3,"clickOutside"],[4,"ngIf","ngIfElse"],[1,"v-back-btn-container"],[1,"v-back-btn",3,"click"],["width","16","height","16","viewBox","0 0 16 16","fill","none","xmlns","http://www.w3.org/2000/svg"],["d","M9.99988 4L5.99988 8L9.99988 12","stroke","currentColor","stroke-width","1.33333","stroke-linecap","round","stroke-linejoin","round"],[1,"v-view-analytics-count-container"],[1,"v-total-views-container"],[1,"v-total-views-count"],[1,"v-total-views-text"],["width","18","height","18","viewBox","0 0 18 18","fill","none","xmlns","http://www.w3.org/2000/svg"],["d","M7.5 9C7.5 9.39782 7.65804 9.77936 7.93934 10.0607C8.22064 10.342 8.60218 10.5 9 10.5C9.39782 10.5 9.77936 10.342 10.0607 10.0607C10.342 9.77936 10.5 9.39782 10.5 9C10.5 8.60218 10.342 8.22064 10.0607 7.93934C9.77936 7.65804 9.39782 7.5 9 7.5C8.60218 7.5 8.22064 7.65804 7.93934 7.93934C7.65804 8.22064 7.5 8.60218 7.5 9Z","stroke","#625DF5","stroke-width","1.25","stroke-linecap","round","stroke-linejoin","round"],["d","M15.75 9C13.95 12 11.7 13.5 9 13.5C6.3 13.5 4.05 12 2.25 9C4.05 6 6.3 4.5 9 4.5C11.7 4.5 13.95 6 15.75 9Z","stroke","#625DF5","stroke-width","1.25","stroke-linecap","round","stroke-linejoin","round"],[1,"v-today-views-container"],[1,"v-today-views-count"],[1,"v-today-views-text"],["class","v-users-container",4,"ngIf"],[1,"v-users-container"],[4,"ngFor","ngForOf"],[1,"v-user"],[1,"v-user-image"],[3,"user","size"],[1,"v-user-view-details"],[1,"v-user-name"],[1,"v-user-view-time"],[1,"v-document-viewer-tread-left"],["class","v-document-viewer-tread-right",4,"ngIf"],[1,"v-document-viewer-tread-right"]],template:function(t,n){t&1&&T(0,Dt,5,4,"ng-container",1),t&2&&D("ngIf",n.componentConfigSignal())},dependencies:[Te,le,at,ct,st,gt],styles:[`.v-view-analytics-dialog-container{border-radius:var(--legacy-velt-view-analytics-dialog-border-radius);border:var(--legacy-velt-view-analytics-dialog-border);background:var(--legacy-velt-view-analytics-dialog-bg-color);box-shadow:var(--legacy-velt-view-analytics-dialog-box-shadow);padding:var(--legacy-velt-view-analytics-dialog-padding);display:flex;gap:16px}.v-view-analytics-dialog-container .v-document-viewer-tread-left{display:flex;flex-direction:column;gap:4px}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container{width:140px;height:110px;flex-shrink:0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color);box-sizing:border-box;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:10px}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container .v-total-views-count{color:var(--legacy-velt-view-analytics-dialog-total-views-count-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-total-views-container .v-total-views-text{color:var(--legacy-velt-view-analytics-dialog-total-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container .v-document-viewer-tread-left .v-today-views-container{display:flex;width:140px;padding:8px 4px;justify-content:center;align-items:center;gap:4px;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color);box-sizing:border-box;color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}.v-view-analytics-dialog-container .v-document-viewer-tread-right{padding:8px 0}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container{display:inline-flex;flex-direction:column;align-items:flex-start;gap:16px;margin-right:16px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user{display:flex;align-items:center;gap:12px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user snippyly-user-avatar{display:flex}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details{display:flex;flex-direction:column;gap:8px}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details .v-user-name{color:var(--legacy-velt-view-analytics-dialog-user-name-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%}.v-view-analytics-dialog-container .v-document-viewer-tread-right .v-users-container .v-user .v-user-view-details .v-user-view-time{color:var(--legacy-velt-view-analytics-dialog-user-timestamp-color);font-size:10px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}.v-view-analytics-dialog-container.bottom-sheet{display:flex;flex-direction:column;border-bottom-left-radius:0;border-bottom-right-radius:0}.v-view-analytics-dialog-container.bottom-sheet .v-back-btn-container{display:flex;padding:8px 8px 0}.v-view-analytics-dialog-container.bottom-sheet .v-back-btn-container .v-back-btn{background:transparent;border:0;outline:0;display:flex;align-items:center;gap:8px;color:var(--legacy-velt-view-analytics-dialog-back-btn-color);cursor:pointer;font-size:16px;font-style:normal;font-weight:400;line-height:normal}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container{display:flex;flex:1;gap:10px}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container{display:flex;padding:25px 20px;flex-direction:column;justify-content:center;align-items:center;gap:10px;flex:1 0 0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color)}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container .v-total-views-count{color:var(--legacy-velt-view-analytics-dialog-total-views-count-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-total-views-container .v-total-views-text{color:var(--legacy-velt-view-analytics-dialog-total-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container{display:flex;padding:25px 20px;flex-direction:column;justify-content:center;align-items:center;gap:10px;flex:1 0 0;border-radius:8px;background:var(--legacy-velt-view-analytics-dialog-views-container-bg-color)}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container .v-today-views-count{color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:32px;font-style:normal;font-weight:600;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-view-analytics-count-container .v-today-views-container .v-today-views-text{color:var(--legacy-velt-view-analytics-dialog-today-views-text-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase;display:flex;gap:4px;align-items:center}.v-view-analytics-dialog-container.bottom-sheet .v-users-container{display:inline-flex;flex-direction:column;align-items:flex-start;gap:16px;margin-right:16px}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user{display:flex;align-items:center;gap:12px;width:100%}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user snippyly-user-avatar{display:flex}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-details{display:flex;flex-direction:column;gap:8px;flex:1}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-details .v-user-name{color:var(--legacy-velt-view-analytics-dialog-user-name-color);font-size:12px;font-style:normal;font-weight:500;line-height:100%}.v-view-analytics-dialog-container.bottom-sheet .v-users-container .v-user .v-user-view-time{color:var(--legacy-velt-view-analytics-dialog-user-timestamp-color);font-size:10px;font-style:normal;font-weight:500;line-height:100%;text-transform:uppercase}
2
2
  `],encapsulation:3,changeDetection:0});let d=c;return d})();var be=(()=>{let c=class c{constructor(e,t){this.bottomSheet=e,this.loggingService=t,this.close=new re,this.subscriptions=[]}ngOnInit(){}ngAfterViewInit(){this.openBottomSheet()}openBottomSheet(){return j(this,null,function*(){try{this.bottomSheetRef=this.bottomSheet.open(X,{data:{clientLocationId:this.clientLocationId,closeBottomSheetFn:()=>{this.onClose(),this.bottomSheetRef?.dismiss()}},panelClass:["v-view-analytics-bottom-sheet-container","velt-mat-bottom-sheet-container"]}),this.subscriptions.push(this.bottomSheetRef.backdropClick().subscribe(()=>{this.onClose()},e=>{this.loggingService.catch("Error in ViewAnalyticsBottomSheetComponent backdropClick subscription: ",e)}))}catch(e){this.loggingService.catch("Error in ViewAnalyticsBottomSheetComponent openBottomSheet: ",e)}})}onClose(){try{this.close.emit()}catch(e){this.loggingService.catch("Error in ViewAnalyticsBottomSheetComponent onClose: ",e)}}ngOnDestroy(){try{this.subscriptions.forEach(e=>{e.unsubscribe()})}catch(e){this.loggingService.catch("Error in ViewAnalyticsBottomSheetComponent ngOnDestroy: ",e)}}};c.\u0275fac=function(t){return new(t||c)(I(Ge),I(C))},c.\u0275cmp=Q({type:c,selectors:[["velt-view-analytics-bottom-sheet-internal"]],inputs:{clientLocationId:"clientLocationId"},outputs:{close:"close"},standalone:!1,decls:0,vars:0,template:function(t,n){},styles:[".velt-mat-bottom-sheet-container.v-view-analytics-bottom-sheet-container{padding:0!important} .velt-mat-bottom-sheet-container.v-view-analytics-bottom-sheet-container .mat-bottom-sheet-container{padding:0!important}"],changeDetection:0});let d=c;return d})();var Et=()=>["snippyly-overlay-panel","v-view-analytics-overlay-panel","velt-overlay-panel"];function Ot(d,c){if(d&1){let r=W();v(0,"velt-view-analytics-dialog",11),M("close",function(){N(r);let t=x(2);return F(t.toggleTrends())}),w()}if(d&2){let r=x(2);D("clientLocationId",r.clientLocationId)}}function Bt(d,c){if(d&1){let r=W();v(0,"velt-view-analytics-bottom-sheet-internal",11),M("close",function(){N(r);let t=x(2);return F(t.closeTrends())}),w()}if(d&2){let r=x(2);D("clientLocationId",r.clientLocationId)}}function At(d,c){if(d&1){let r=W();q(0),v(1,"div",3,0),M("click",function(t){return N(r),x().toggleTrends(),F(t.stopPropagation())}),v(3,"slot",4),M("slotchange",function(){N(r);let t=x();return F(t.onButtonSlotChange())}),v(4,"div",5),H(),v(5,"svg",6),L(6,"path",7),w(),Y(),v(7,"span",8),_(8),w()()()(),T(9,Ot,1,1,"ng-template",9,1,ce)(11,Bt,1,1,"velt-view-analytics-bottom-sheet-internal",10),G()}if(d&2){let r=c.ngIf,e=se(2),t=x();h(4),ae("active",r.treadsVisible),h(4),J(r.totalUniqueViewsCount),h(),D("cdkConnectedOverlayOrigin",e)("cdkConnectedOverlayOpen",!r.isPhone&&r.treadsVisible)("cdkConnectedOverlayPanelClass",ke(11,Et))("cdkConnectedOverlayBackdropClass","snippyly-overlay-backdrop")("cdkConnectedOverlayGrowAfterOpen",!0)("cdkConnectedOverlayPositions",t.positions)("cdkConnectedOverlayDisableClose",!0),h(2),D("ngIf",r.isPhone&&r.treadsVisible)}}var Ve=(()=>{let c=class c{constructor(e,t,n,i,o,a){this.breakpointObserver=e,this.docService=t,this.loggingService=n,this.viewsService=i,this.elementRef=o,this.domService=a,this.type="document",this.componentConfigSignal=ne({today:new Date().toISOString().split("T")[0],todayViews:{},todayViewsCount:0,totalUniqueViews:{},totalUniqueViewsCount:0,treadsVisible:!1,customButtonAdded:!1,isPhone:!1,componentId:Math.random().toString(36).substring(2)}),this.positions=E.OVERLAY_POSITIONS.map(l=>new ze({originX:l.originX,originY:l.originY},{overlayX:l.overlayX,overlayY:l.overlayY})),this.subscriptions=[]}ngOnInit(){try{this.getUniqueViewsByUser(),this.subscriptions.push(this.breakpointObserver.observe(je.XSmall).subscribe(e=>{this.componentConfigSignal.update(t=>(t=m({},t),t.isPhone=!!e.matches,t))},e=>{this.loggingService.catch("Error in ViewAnalyticsComponent breakpointObserver subscription: ",e)})),this.subscriptions.push(this.docService.getLocation$().subscribe(e=>{e?.location?.id&&(this.clientLocationId=e?.location?.id,this.getUniqueViewsByUser())}))}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent ngOnInit: ",e)}}ngOnChanges(e){try{(e.type||e.clientLocationId)&&this.getUniqueViewsByUser()}catch(t){this.loggingService.catch("Error in ViewAnalyticsComponent ngOnChanges: ",t)}}ngAfterViewInit(){try{this.subscriptions.push(this.domService.subscribeInjectCustomCss(this.elementRef))}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent ngAfterViewInit: ",e)}}getUniqueViewsByUser(){try{this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentViews","color: green;"),this.uniqueViewsByUserSubscription&&(this.componentConfigSignal.update(t=>(t=m({},t),t.totalUniqueViews={},t.totalUniqueViewsCount=0,t)),this.uniqueViewsByUserSubscription.unsubscribe());let e=this.type==="location"&&this.clientLocationId?this.clientLocationId:void 0;this.uniqueViewsByUserSubscription=this.viewsService.getUniqueViewsByUser(e).subscribe(t=>{this.componentConfigSignal.update(n=>(n=m({},n),n.totalUniqueViews=t||{},n.totalUniqueViewsCount=Object.keys(n.totalUniqueViews||{})?.length||0,n))},t=>{this.loggingService.catch("Error in ViewAnalyticsComponent getUniqueViewsByUser subscription: ",t)})}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent getDocumentViews: ",e)}}toggleTrends(){try{this.loggingService.log("%c[WB] Calling FUNCTION: toggleTrends","color: green;"),this.componentConfigSignal.update(e=>(e=m({},e),e.treadsVisible=!e.treadsVisible,e))}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent toggleTrends: ",e)}}openTrends(){try{this.loggingService.log("%c[WB] Calling FUNCTION: openTrends","color: green;"),this.componentConfigSignal.update(e=>(e=m({},e),e.treadsVisible=!0,e))}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent openTrends: ",e)}}closeTrends(){try{this.loggingService.log("%c[WB] Calling FUNCTION: closeTrends","color: green;"),this.componentConfigSignal.update(e=>(e=m({},e),e.treadsVisible=!1,e))}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent closeTrends: ",e)}}onButtonSlotChange(){this.componentConfigSignal.update(e=>(e=m({},e),e.customButtonAdded=!0,e))}unsubscribe(){this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribe","color: green;");try{this.subscriptions.map(e=>{e.unsubscribe()}),this.subscriptions=[],this.uniqueViewsByUserSubscription&&this.uniqueViewsByUserSubscription.unsubscribe()}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent unsubscribe: ",e)}}ngOnDestroy(){try{this.unsubscribe()}catch(e){this.loggingService.catch("Error in ViewAnalyticsComponent ngOnDestroy: ",e)}}};c.\u0275fac=function(t){return new(t||c)(I(Re),I(ve),I(C),I(P),I(oe),I(ue))},c.\u0275cmp=Q({type:c,selectors:[["velt-view-analytics-internal"]],inputs:{type:"type",clientLocationId:[0,"locationId","clientLocationId"]},standalone:!1,features:[Oe],decls:1,vars:1,consts:[["trigger","cdkOverlayOrigin"],["overlay","cdkConnectedOverlay"],[4,"ngIf"],["part","container","cdkOverlayOrigin","",1,"v-document-viewer-tread-container",3,"click"],["name","button",3,"slotchange"],["part","button-container",1,"action-btn"],["part","button-icon","width","24","height","24","viewBox","0 0 24 24","fill","none","xmlns","http://www.w3.org/2000/svg",1,"action-btn-icon"],["d","M4.5 16.1667L9.5 11.1667L12.8333 14.5L19.5 7.83334M19.5 7.83334H13.6667M19.5 7.83334V13.6667","stroke","currentColor","stroke-width","1.5","stroke-linecap","round","stroke-linejoin","round"],["part","button-label",1,"action-btn-label"],["cdkConnectedOverlay","",3,"cdkConnectedOverlayOrigin","cdkConnectedOverlayOpen","cdkConnectedOverlayPanelClass","cdkConnectedOverlayBackdropClass","cdkConnectedOverlayGrowAfterOpen","cdkConnectedOverlayPositions","cdkConnectedOverlayDisableClose"],[3,"clientLocationId","close",4,"ngIf"],[3,"close","clientLocationId"]],template:function(t,n){t&1&&T(0,At,12,12,"ng-container",2),t&2&&D("ngIf",n.componentConfigSignal())},dependencies:[le,Ne,Pe,X,be],styles:[`html{--velt-base-rem-unit: 1}*[data-snippyly-element=true],*[data-velt-element=true]{font-family:var(--velt-default-font-family)}velt-wireframe{display:none!important}body.velt-pin-dragging iframe{pointer-events:none!important}*{box-sizing:border-box;-webkit-tap-highlight-color:rgba(255,255,255,0);outline:none;margin:0;padding:0;height:unset;width:unset;text-align:left;line-height:1.5;font-size:calc((1rem + 0px) * var(--velt-base-rem-unit))}*:empty{display:revert}.v-document-viewer-tread-container{display:inline-block}.action-btn{display:inline-flex;justify-content:center;align-items:center;padding:6px;border-radius:var(--legacy-velt-tool-border-radius);border:var(--legacy-velt-tool-border);background-color:var(--legacy-velt-tool-bg-color);color:var(--legacy-velt-tool-icon-color);cursor:pointer}.action-btn .action-btn-label{font-size:calc((.9rem + 0px) * var(--velt-base-rem-unit));padding:0 12px 0 4px;font-weight:700;color:currentColor}.action-btn .action-btn-icon{width:calc((var(--legacy-velt-tool-icon-size) + 0px) * var(--velt-base-rem-unit));height:calc((var(--legacy-velt-tool-icon-size) + 0px) * var(--velt-base-rem-unit));color:currentColor;padding-left:8px;box-sizing:content-box}.action-btn .toolbar-icon-dropdown-arrow{width:16px;height:16px;color:currentColor}.action-btn:focus{border-radius:var(--legacy-velt-tool-focus-border-radius);border:var(--legacy-velt-tool-focus-border);background-color:var(--legacy-velt-tool-focus-bg-color);color:var(--legacy-velt-tool-focus-icon-color)}.action-btn:focus .action-btn-icon{width:calc((var(--legacy-velt-tool-focus-icon-size) + 0px) * var(--velt-base-rem-unit));height:calc((var(--legacy-velt-tool-focus-icon-size) + 0px) * var(--velt-base-rem-unit))}.action-btn:focus .toolbar-icon-dropdown-arrow{color:var(--legacy-velt-tool-focus-icon-color)}.action-btn:hover{border-radius:var(--legacy-velt-tool-hover-border-radius);border:var(--legacy-velt-tool-hover-border);background-color:var(--legacy-velt-tool-hover-bg-color);color:var(--legacy-velt-tool-hover-icon-color)}.action-btn:hover .action-btn-icon{width:calc((var(--legacy-velt-tool-hover-icon-size) + 0px) * var(--velt-base-rem-unit));height:calc((var(--legacy-velt-tool-hover-icon-size) + 0px) * var(--velt-base-rem-unit))}.action-btn:hover .toolbar-icon-dropdown-arrow{color:var(--legacy-velt-tool-hover-icon-color)}.action-btn:active,.action-btn.active{border-radius:var(--legacy-velt-tool-active-border-radius);border:var(--legacy-velt-tool-active-border);background-color:var(--legacy-velt-tool-active-bg-color);color:var(--legacy-velt-tool-active-icon-color)}.action-btn:active .action-btn-icon,.action-btn.active .action-btn-icon{width:calc((var(--legacy-velt-tool-active-icon-size) + 0px) * var(--velt-base-rem-unit));height:calc((var(--legacy-velt-tool-active-icon-size) + 0px) * var(--velt-base-rem-unit))}.action-btn:active .toolbar-icon-dropdown-arrow,.action-btn.active .toolbar-icon-dropdown-arrow{color:var(--legacy-velt-tool-active-icon-color)}
3
3
  `],encapsulation:3,changeDetection:0});let d=c;return d})();var he=class extends mt{constructor(c){super(c),this.getService(C).log("%c[WB] Creating CLASS: ViewsElement","color: blue;"),this.getUniqueViewsByUser=this._getUniqueViewsByUser,this.getUniqueViewsByDate=this._getUniqueViewsByDate}_getUniqueViewsByUser(c){this.getService(C).log("%c[WB] Calling FUNCTION: _getUniqueViewsByUser","color: green;");try{return this.trackEvent(ye.Events.Views.GET_UNIQUE_VIEWS_BY_USER_TRIGGERED,{payload:{clientLocationId:c}}),this.getService(P).getUniqueViewsByUser(c)}catch(r){return this.getService(C).catch("Error in getUniqueViewsByUser: ",r),V({})}}_getUniqueViewsByDate(c){this.getService(C).log("%c[WB] Calling FUNCTION: _getUniqueViewsByDate","color: green;");try{return this.trackEvent(ye.Events.Views.GET_UNIQUE_VIEWS_BY_DATE_TRIGGERED,{payload:{clientLocationId:c}}),this.getService(P).getUniqueViewsByDate(c)}catch(r){return this.getService(C).catch("Error in getUniqueViewsByDate: ",r),V({})}}};var pt=(()=>{let c=class c{};c.\u0275fac=function(t){return new(t||c)},c.\u0275mod=Ae({type:c}),c.\u0275inj=Ee({imports:[$e,Fe,We,lt]});let d=c;return d})();function Ut(d){d.get(C).log("%c[WB] Loading view feature chunk","color: blue;"),d.get(me).set(Ze,d.get(P));let t=Be(pt,d).injector;return kt(t,E.TAGS.VELT_VIEW_ANALYTICS,Ve),new he(d)}function kt(d,c,r){if(customElements.get(c))return;let e=Le(r,d);customElements.define(c,e)}export{Ut as default};
package/velt.js CHANGED
@@ -1,7 +1,7 @@
1
- var SNIPPYLY_VERSION = '6.0.21';
1
+ var SNIPPYLY_VERSION = '6.0.23';
2
2
  Promise.allSettled||(Promise.allSettled=function(t){return Promise.all(t.map(function(r){return Promise.resolve(r).then(function(e){return{status:"fulfilled",value:e}}).catch(function(e){return{status:"rejected",reason:e}})}))});
3
3
 
4
- import{a as ws}from"./chunk-TIDK55EX.js";import{a as Ls}from"./chunk-5CHLXJQA.js";import{d as T}from"./chunk-BQVD76TQ.js";import{b as ko,d as re}from"./chunk-TSAUKBNW.js";import"./chunk-PLEUR6AN.js";import{a as jo,d as Wo}from"./chunk-Z3NOEF5O.js";import{b as Ds,c as xs,j as Ps,q as hi,t as Ns}from"./chunk-I3NP7X72.js";import"./chunk-G6CVZGMW.js";import"./chunk-PGPXYZZN.js";import"./chunk-HRHQ2ONQ.js";import{l as Ho,m as $o,o as Xo,r as Jo,s as ts,u as is,v as rs,w as ns}from"./chunk-TPPAZ2V2.js";import{d as Ao}from"./chunk-LG756VXD.js";import{d as Zo}from"./chunk-WXX73A2Z.js";import{a as pi}from"./chunk-XDDHCYC6.js";import{a as Ms}from"./chunk-IV6TXG5Z.js";import"./chunk-PXOUAPOU.js";import"./chunk-IUO7RNPW.js";import"./chunk-2PD23MCR.js";import"./chunk-UPKZBLXG.js";import{A as Rs,B as ks,C as Pr,F as ye,G as Te,a as Ye,b as ai,f as li,g as st,i as Cs,j as ci,k as di,l as ui,m as At,n as bs,o as Ss,p as Es,q as Ts,r as Os,y as Is,z as As}from"./chunk-GMP3ZGYE.js";import{a as _s}from"./chunk-3QL3XETD.js";import{a as Ke,b as xe,c as Rt,d as mi}from"./chunk-T4CZDGU7.js";import{a as at}from"./chunk-NK4G7LFH.js";import{a as xr}from"./chunk-JC7WVK34.js";import{Ea as es,Fa as ee,Ha as It,I as ri,l as To,na as Yo,o as Oo,p as Io,ta as bt,v as Ro,y as Dr}from"./chunk-MOU625G2.js";import{a as Pe}from"./chunk-IYN573WN.js";import{A as D,k as Ot,l as ms,m as ps,o as gs,p as fs,q as vs,u as ys}from"./chunk-P2OUKDDH.js";import{$ as I,Ad as Po,Ba as Sr,Bb as B,Bd as Mo,Ca as ho,Cb as Ge,Db as je,Dd as No,E as no,Ea as mo,Ed as wo,Fa as po,Fb as Kt,Fd as Lo,Fi as g,Gb as Xt,Ha as W,Hb as Jt,Hc as ei,He as A,Ia as go,Ic as Qe,Id as Fo,Ja as Er,Jd as zo,K as oo,Kb as Or,Kd as Uo,M as so,Mb as yt,Md as qo,Nc as Ct,Pa as fo,Pb as We,Pe as ni,Qb as Ir,Qe as as,Qg as cs,Ra as R,Rb as _t,Rd as Bo,Re as Et,Sc as ti,Sd as Vo,Sj as si,Tc as Co,Td as Go,Uc as bo,Vc as ii,Vd as Qo,Wa as H,Wd as Ko,Wj as ve,Xa as ke,Xc as So,Xd as St,Xj as ie,Yc as Eo,Yd as fe,Yf as ls,_a as Tr,_f as oi,a as k,ab as ue,ac as Ar,b as j,ba as le,bc as De,c as Zn,ca as Re,cc as vo,d as fl,da as ao,e as Gt,ea as U,ec as Zt,ee as os,f as eo,fa as Fe,fb as Ue,g as L,hb as qe,hc as yo,i as jt,ib as Be,ja as Wt,ka as Ht,ki as ds,l as to,la as $t,m as M,mc as He,mj as Tt,na as Ee,nb as q,nc as $e,nj as l,oa as br,ob as $,od as Do,oj as V,pb as J,qa as lo,qb as Z,qj as us,r as x,rc as Rr,re as C,rj as hs,sa as co,sc as _o,ub as ft,ue as ss,v as io,vb as vt,w as ro,wa as Qt,xa as uo,xb as Yt,ya as ze,zb as Ve,zc as kr,zd as xo}from"./chunk-YNU6L4ZC.js";var $n=fl((Sv,Hn)=>{"use strict";var p={};p.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};p.localCName=p.generateIdentifier();p.splitLines=function(r){return r.trim().split(`
4
+ import{a as ws}from"./chunk-3PSEC6OK.js";import{a as Ls}from"./chunk-O4J2GUCR.js";import{d as T}from"./chunk-C3PHZRKL.js";import{b as ko,d as re}from"./chunk-XAZILV5B.js";import"./chunk-C3DWGOTZ.js";import{a as jo,d as Wo}from"./chunk-3M5GZFCG.js";import{b as Ds,c as xs,j as Ps,q as hi,t as Ns}from"./chunk-VFYLOVTK.js";import"./chunk-CQZ7DKJB.js";import"./chunk-6BCXLMAY.js";import"./chunk-UWH2AIKJ.js";import{l as Ho,m as $o,o as Xo,r as Jo,s as ts,u as is,v as rs,w as ns}from"./chunk-ZURN7SUE.js";import{d as Ao}from"./chunk-MGORC6ST.js";import{d as Zo}from"./chunk-MU6RYO5X.js";import{a as pi}from"./chunk-KXEU5HGR.js";import{a as Ms}from"./chunk-J2NS4TI4.js";import"./chunk-ZEWGJF7N.js";import"./chunk-M5AN4E5A.js";import"./chunk-F2XJIYNI.js";import"./chunk-EC25EQB5.js";import{A as Rs,B as ks,C as Pr,F as ye,G as Te,a as Ye,b as ai,f as li,g as st,i as Cs,j as ci,k as di,l as ui,m as At,n as bs,o as Ss,p as Es,q as Ts,r as Os,y as Is,z as As}from"./chunk-KE64O5B7.js";import{a as _s}from"./chunk-TDVYFBCW.js";import{a as Ke,b as xe,c as Rt,d as mi}from"./chunk-RCOPSCV6.js";import{a as at}from"./chunk-TM2JOAC4.js";import{a as xr}from"./chunk-6F7MEOHL.js";import{Ea as es,Fa as ee,Ha as It,I as ri,l as To,na as Yo,o as Oo,p as Io,ta as bt,v as Ro,y as Dr}from"./chunk-EIDOVJ3L.js";import{a as Pe}from"./chunk-D2UJGDHP.js";import{A as D,l as Ot,m as ms,n as ps,p as gs,q as fs,r as vs,v as ys}from"./chunk-COMT5MGY.js";import{$ as I,$j as ie,Ad as Po,Ba as Sr,Bb as B,Bd as Mo,Ca as ho,Cb as Ge,Db as je,Dd as No,E as no,Ea as mo,Ed as wo,Fa as po,Fb as Kt,Fd as Lo,Fi as g,Gb as Xt,Ha as W,Hb as Jt,Hc as ei,He as A,Ia as go,Ic as Qe,Id as Fo,Ja as Er,Jd as zo,K as oo,Kb as Or,Kd as Uo,M as so,Mb as yt,Md as qo,Nc as Ct,Pa as fo,Pb as We,Pe as ni,Qb as Ir,Qe as as,Qg as cs,Ra as R,Rb as _t,Rd as Bo,Re as Et,Sc as ti,Sd as Vo,Tc as Co,Td as Go,Uc as bo,Vc as ii,Vd as Qo,Wa as H,Wd as Ko,Wj as si,Xa as ke,Xc as So,Xd as St,Yc as Eo,Yd as fe,Yf as ls,_a as Tr,_f as oi,_j as ve,a as k,ab as ue,ac as Ar,b as j,ba as le,bc as De,c as Zn,ca as Re,cc as vo,d as fl,da as ao,e as Gt,ea as U,ec as Zt,ee as os,f as eo,fa as Fe,fb as Ue,g as L,hb as qe,hc as yo,i as jt,ib as Be,ja as Wt,ka as Ht,ki as ds,l as to,la as $t,m as M,mc as He,mj as Tt,na as Ee,nb as q,nc as $e,nj as l,oa as br,ob as $,od as Do,oj as V,pb as J,qa as lo,qb as Z,qj as us,r as x,rc as Rr,re as C,rj as hs,sa as co,sc as _o,ub as ft,ue as ss,v as io,vb as vt,w as ro,wa as Qt,xa as uo,xb as Yt,ya as ze,zb as Ve,zc as kr,zd as xo}from"./chunk-V53LQO22.js";var $n=fl((Sv,Hn)=>{"use strict";var p={};p.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};p.localCName=p.generateIdentifier();p.splitLines=function(r){return r.trim().split(`
5
5
  `).map(e=>e.trim())};p.splitSections=function(r){return r.split(`
6
6
  m=`).map((t,i)=>(i>0?"m="+t:t).trim()+`\r
7
7
  `)};p.getDescription=function(r){let e=p.splitSections(r);return e&&e[0]};p.getMediaSections=function(r){let e=p.splitSections(r);return e.shift(),e};p.matchPrefix=function(r,e){return p.splitLines(r).filter(t=>t.indexOf(e)===0)};p.parseCandidate=function(r){let e;r.indexOf("a=candidate:")===0?e=r.substring(12).split(" "):e=r.substring(10).split(" ");let t={foundation:e[0],component:{1:"rtp",2:"rtcp"}[e[1]]||e[1],protocol:e[2].toLowerCase(),priority:parseInt(e[3],10),ip:e[4],address:e[4],port:parseInt(e[5],10),type:e[7]};for(let i=8;i<e.length;i+=2)switch(e[i]){case"raddr":t.relatedAddress=e[i+1];break;case"rport":t.relatedPort=parseInt(e[i+1],10);break;case"tcptype":t.tcpType=e[i+1];break;case"ufrag":t.ufrag=e[i+1],t.usernameFragment=e[i+1];break;default:t[e[i]]===void 0&&(t[e[i]]=e[i+1]);break}return t};p.writeCandidate=function(r){let e=[];e.push(r.foundation);let t=r.component;t==="rtp"?e.push(1):t==="rtcp"?e.push(2):e.push(t),e.push(r.protocol.toUpperCase()),e.push(r.priority),e.push(r.address||r.ip),e.push(r.port);let i=r.type;return e.push("typ"),e.push(i),i!=="host"&&r.relatedAddress&&r.relatedPort&&(e.push("raddr"),e.push(r.relatedAddress),e.push("rport"),e.push(r.relatedPort)),r.tcpType&&r.protocol.toLowerCase()==="tcp"&&(e.push("tcptype"),e.push(r.tcpType)),(r.usernameFragment||r.ufrag)&&(e.push("ufrag"),e.push(r.usernameFragment||r.ufrag)),"candidate:"+e.join(" ")};p.parseIceOptions=function(r){return r.substring(14).split(" ")};p.parseRtpMap=function(r){let e=r.substring(9).split(" "),t={payloadType:parseInt(e.shift(),10)};return e=e[0].split("/"),t.name=e[0],t.clockRate=parseInt(e[1],10),t.channels=e.length===3?parseInt(e[2],10):1,t.numChannels=t.channels,t};p.writeRtpMap=function(r){let e=r.payloadType;r.preferredPayloadType!==void 0&&(e=r.preferredPayloadType);let t=r.channels||r.numChannels||1;return"a=rtpmap:"+e+" "+r.name+"/"+r.clockRate+(t!==1?"/"+t:"")+`\r
package/chunk-7YXWYOYZ.js DELETED
@@ -1 +0,0 @@
1
- import{a as ci}from"./chunk-XDDHCYC6.js";import{a as ai}from"./chunk-NK4G7LFH.js";import{A as ni,a as ei,f as ut,i as oi,k as it,l as et,n as ot,s as mt,u as rt,v as ri,y as si}from"./chunk-P2OUKDDH.js";import{$f as Pt,Ai as Lt,Aj as Jt,Bg as zt,Cg as gt,Cj as Kt,E as P,Ej as dt,Fi as _,G as j,Gd as yt,Gi as X,He as R,Hj as Qt,Ig as K,Ii as jt,Jj as Xt,K as Y,Ki as _t,Kj as qt,Lj as ht,M as k,O as at,Pj as Zt,Q as Nt,Qd as Dt,Qf as Ut,Sj as ti,U as It,Uf as Et,V as y,Vi as Ht,Wf as $t,Wj as ii,Xf as wt,Xi as Vt,Xj as tt,Y as Ot,Zd as Ct,Zf as ct,_f as F,a as I,ai as Bt,b as U,ba as G,bg as lt,ea as m,ee as At,fa as bt,g as D,i as vt,ji as ft,l as b,li as Q,lj as q,mj as Yt,ni as xt,nj as Z,oj as kt,p as V,q as nt,r as C,re as Tt,sg as Rt,sj as Gt,tf as W,tg as Ft,uf as J,v as p,w as H,wg as Mt,x as pt,zj as Wt}from"./chunk-YNU6L4ZC.js";var li=(()=>{let u=class u{constructor(t,i,e,o,r,a,s){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=r,this.notificationResolverService=a,this.serviceBook=s,this.serviceBook.set(_t,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 r=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let a of r)i.add(a)}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,r=i?.comments?.[e]?.commentHtml;return o&&r&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=r),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 r=i?.[o]?.[e];return r&&(t.notification.notificationSourceData.location=r?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=r?.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{if(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),this.usersService.userResolverConfigured?.()&&t&&typeof t=="object")for(let e of Object.keys(t))e!=="annotationData"&&e!=="targetAnnotationData"&&Lt(t[e])&&(t[e]=xt(t[e],Et));switch(t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData),t=this.commentUtilsService.stripCommentNotificationPayload(t);break;default:u.carriesCommentPayload(t)&&(t=this.commentUtilsService.stripCommentNotificationPayload(t));break;case"recorder":this.serviceBook.get(Ht)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),u.carriesCommentPayload(t)?this.commentUtilsService?.stripCommentNotificationPayload?.(I({},t))??t:t}}static carriesCommentPayload(t){return!t||typeof t!="object"?!1:t.notificationSource==="comment"||t.notificationSource===void 0&&Array.isArray(t.annotationData?.comments)}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 D(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 zt(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 r=o?.notification?.id||o?.notificationId;r&&i.add(r)}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 r of o)e[r]!==void 0&&(t.notification&&(t.notification[r]=e[r]),t.raw&&(t.raw[r]=e[r]));return Object.keys(e).forEach(r=>{!o.includes(r)&&r!=="notificationId"&&(t.notification&&(t.notification[r]=e[r]),t.raw&&(t.raw[r]=e[r]))}),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)(m(ot),m(Z),m(it),m(tt),m(et),m(rt),m(q))},u.\u0275prov=G({token:u,factory:u.\u0275fac,providedIn:"root"});let S=u;return S})();function St(S,u=new Date){let M=S>0?S:15,t=new Date(u.getTime());return t.setDate(t.getDate()-M),t.getTime()}function gi(S){let u={startAtTimestamp:S.startAtTimestamp};return S.currentDocumentOnly&&S.currentDocumentId&&(u.documentId=S.currentDocumentId),S.currentDocumentOnly||(u.limit=S.limit),u}function fi(S,u){let M=[];if(!S||typeof S!="object")return{};for(let e of Object.keys(S)){let o=S[e];if(!o||typeof o!="object")continue;let r=o.timestamp;typeof r!="number"||Number.isNaN(r)||!(r>=u.startAtTimestamp)||u.documentId!==void 0&&o.metadata?.documentId!==u.documentId||M.push({id:e,timestamp:r,row:S[e]})}let t=M;u.limit!==void 0&&(t=[...M].sort((e,o)=>o.timestamp-e.timestamp||(e.id<o.id?1:e.id>o.id?-1:0)).slice(0,Math.max(0,u.limit)));let i={};for(let e of t)i[e.id]=e.row;return i}function di(S){if(typeof S!="number"||!Number.isFinite(S))return 25;let t=Math.floor(S);return t<1?25:Math.min(200,t)}function hi(S,u){let M=t=>!!t&&typeof t=="object"&&Object.keys(t).length>0;return M(S)?S:M(u)?u:{}}var ae=(()=>{let u=class u{constructor(t,i,e,o,r,a,s,c,n,l,g,d,f,h,N,A,$,z,B,x,L,O){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=r,this.commonDbUtilsService=a,this.commentUtilsService=s,this.commentAnnotationsResolverService=c,this.notificationResolverService=n,this.databaseService=l,this.docService=g,this.domService=d,this.iamService=f,this.loggingService=h,this.notificationUtilsService=N,this.usersService=A,this.functions=$,this.userPermissionService=z,this.coreActionsService=B,this.serviceBook=x,this.realtimeAdapter=L,this.adapterSelectorService=O,this.endpointsService=bt(Gt),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new b([]),this.rawNotificationsByIdMap$=new b(new Map),this.processedNotifications$=new b([]),this.userNotificationsFromServer$=new b(null),this.readNotificationsOnForYouTab$=new b(!1),this.currentDocumentOnly$=new b(!1),this.notificationViews$=new b({}),this.notificationsByIdMap$=new b(new Map),this.historyPanelVisible$=new b(!1),this.notificationsForYou$=new b(null),this.notificationsByDocumentIdMap$=new b(null),this.notificationsByDocumentIdSubscription={},this.notificationsHubDisabled=!1,this.reportedDroppedHubPushes=new Set,this.allowedDocumentMetadataMap$=new b(null),this.documentIdsPipelineOnPortableTrigger=!1,this.maxNotificationDays$=new b(15),this.tabConfig$=new b({people:{enable:!1}}),this.settingsConfig$=new b(null),this.setSettingsConfigByOrganization$=new b(!1),this.muteAllNotifications$=new b(!1),this.enableSettings$=new b(!1),this.selfNotifications$=new b(!1),this.userScopedNotifications$=new b({enabled:!1,limit:25}),this.settingsInitialConfig$=new b([{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 b(!1),this.crossOrganizationConfig$=new b({enabled:!1}),this.crossOrgNotifications$=new b([]),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(jt,this),this.serviceBook.observe(Vt).subscribe(v=>{this.commentService=v??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(P(v=>!!v),Y(1)).subscribe(v=>{if(v){this.db=v;try{let T=this.configService.getProxyConfig(),E=this.endpointsService.getNotificationsDbUrl();$t(E)?(this.notificationsDb=null,this.notificationsHubDisabled=!0):(T?.v1DbHost&&E&&(E=wt(E,T.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance(E),T?.v1DbHost&&E&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(T){this.loggingService.catch("Error initializing notifications DB, using default: ",T),this.notificationsDb=v}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},v=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",v)}),this.authService.getUser$().subscribe(v=>{v?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(T=>{this.notificationsByDocumentIdSubscription[T]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),ht(()=>{try{if(this.adapterSelectorService?.isPortableBackendActive()){if(this.documentIdsPipelineOnPortableTrigger)return;this.getDocumentIds()}}catch(v){this.loggingService.catch("Error re-evaluating portable notification list on chunk registration: ",v)}}),this.docService.getLocationMetadata$().subscribe(v=>{if(v){let T=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(v||{}).forEach(E=>{let w=T?.[E]?.notifications;w?.length&&w.forEach(st=>{this.notificationUtilsService.mergeLocationWithNotification({notification:st},v)?.notification})}),this.notificationsByDocumentIdMap$.next(T)}})}catch(v){this.loggingService.catch("Error in NotificationService constructor: ",v)}}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 D(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=F(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 r={};this.settingsInitialConfig$.getValue().forEach(s=>{if(s.enable){let c=s?.values?.find(n=>n.id===s.default);r[s.id]=c||s?.values?.[0]||{id:"NONE",name:"None"}}});let a={};Object.keys(r).forEach(s=>{a[s]=r[s].id}),yield this.updateSettingsConfigToDb(a)}}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=F(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(P(i=>i===!0),y(()=>H([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(P(([i,e,o])=>(e||!!i)&&!!o?.organizationId),y(([i,e,o])=>nt(this.getInitialConfigFromDB(i)).pipe(y(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(p(r=>{r?.data?.notificationsConfig&&!K(r?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(r?.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=pt(()=>{let t=!!this.adapterSelectorService?.isPortableBackendActive();return this.documentIdsPipelineOnPortableTrigger=t,this.notificationListPipeline$(t)}).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}notificationListPipeline$(t=!1){return this.selfNotifications$.pipe(y(()=>this.getCurrentDocumentOnly$().pipe(y(i=>i?this.docService.getDocumentPaths$().pipe(p(e=>{})):C(void 0)))),Ot(()=>{this.notificationsByDocumentIdMap$.next(null)}),y(()=>this.getDocumentIdsByLastNotificationTimestamp(void 0,t).pipe(at(),p(([i,e])=>{let o=i?.map(n=>n.documentId),r=e?.map(n=>n.documentId),a=o?.filter(n=>!r?.includes(n)),s=r?.map(n=>({documentId:n,timestamp:e?.find(l=>l.documentId===n)?.timestamp})).filter(n=>!o?.includes(n.documentId)),c=r?.map(n=>{let l=e?.find(g=>g.documentId===n)?.timestamp;return{documentId:n,timestamp:l}}).filter(n=>{let l=i?.find(g=>g.documentId===n.documentId)?.timestamp;return l&&n.timestamp&&l!==n.timestamp});s?.length&&this.fetchNotificationsForDocumentIds(s),c?.length&&this.fetchNotificationsForDocumentIds(c,1),a?.forEach(n=>{this.removeNotificationsForDocumentId(n)}),e&&!e?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))}))))}portableNotificationTriggerRows$(t){return new vt(i=>{let e=!1,o=null,r=()=>{try{o?.unsubscribe()}catch(c){this.loggingService.catch("Error releasing the notification trigger subscription: ",c)}o=null},a=()=>{e||(r(),o=this.openPortableNotificationTrigger(t,c=>i.next(c)))},s=ht(a);return a(),()=>{e=!0;try{s()}catch(c){this.loggingService.catch("Error disposing the notification trigger registration listener: ",c)}r()}})}openPortableNotificationTrigger(t,i){try{let e=oi(ut,{apiKey:this.configService.getApiKey(),organizationId:t}),o=this.adapterSelectorService?.resolveRealtimeAdapter?.();if(!e||!o)return null;let r=Xt(e.feature)?.mode??"persistent",a={},s={},c=!1,n=!1;return o.subscribe(e,r,l=>{try{if(n)return;if(typeof l.seq=="number"){let g=s[l.id];if(g!==void 0&&l.seq<=g)return;s[l.id]=l.seq}l.type==="removed"?delete a[l.id]:a[l.id]=l.data,c&&typeof l.seq=="number"&&i(I({},a))}catch(g){this.loggingService.catch("Error materializing a notification trigger delta: ",g)}},{onSnapshotComplete:l=>{try{if(n)return;if(l?.full===!0)for(let g of Object.keys(s))delete s[g];c=!0,i(I({},a))}catch(g){this.loggingService.catch("Error completing the notification trigger snapshot: ",g)}},onError:l=>{n=!0,this.loggingService.catch(`Portable channel denied for ${ut}: `,{ok:!1,code:l})}})}catch(e){return this.loggingService.catch("Error subscribing the notification trigger channel: ",e),null}}getDocumentIdsByLastNotificationTimestamp(t=15,i=!1){try{return this.authService.getUser$().pipe(y(e=>this.docService.getOrganizationConfig$().pipe(p(o=>{let r=null,a=this.configService.getApiKey(),s=o?.organizationId||e?.organizationId,c=o?.clientOrganizationId||e?.clientOrganizationId||"";return a&&s&&(r=new mt({apiKey:a,organizationId:s})),{user:e,documentPaths:r,clientOrganizationId:c}}))),y(e=>{let{user:o,documentPaths:r,clientOrganizationId:a}=e;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return C(null);if(o&&r?.organizationNotificationsLastNotificationTimestamp){let s=St(this.maxNotificationDays$.getValue()),c=gi({startAtTimestamp:s,currentDocumentOnly:this.getCurrentDocumentOnly(),currentDocumentId:this.docService.getDocumentPaths()?.documentId,limit:t}),n=o?.userId??"";return nt(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:a})??Promise.resolve({})).pipe(y(l=>n&&a&&l?.[n]?.organization?.[a]?.errorCode===Ut.PERMISSION_DENIED?C(null):this.lastNotificationTimestampRows$(r,c,i).pipe(p(g=>{let d=()=>i||this.commonDbService.shouldUseFirestore(),f=[];return Object.keys(g||{}).forEach(h=>{let N=d()?g[h]?.timestamp??0:g[h],A=d()?g[h]?.deletedNotification??!1:!1;if(A&&A.id&&A?.timestamp===N){let $=A.id,z=g[h]?.metadata?.documentId,B=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),x=B?.[z]??{documentMetadata:null,notifications:[]},L=x.notifications??[],O=L?.findIndex(v=>v.id===$);O!==-1&&(L.splice(O,1),this.notificationsByDocumentIdMap$.next(U(I({},B),{[z]:U(I({},x),{notifications:L})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById($)&&this.notificationResolverService.deleteNotification($,this.docService.getDocumentPaths()?.clientOrganizationId??"")}f.push({documentId:h,timestamp:N})}),f}),j(g=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",g),C([]))))))}return C(null)}))}catch(e){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",e),C([])}}lastNotificationTimestampRows$(t,i,e=!1){return e?this.portableNotificationTriggerRows$(t?.organizationId).pipe(p(o=>fi(o,i)),It(void 0)):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:t?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:this.toFirestoreTriggerQuery(i)}}).pipe(p(o=>o?.data))}toFirestoreTriggerQuery(t){let i=[Wt(dt("timestamp",">=",t.startAtTimestamp),...t.documentId!==void 0?[dt("metadata.documentId","==",t.documentId)]:[])];return t.limit!==void 0&&(i.push(Kt("timestamp","desc")),i.push(Jt(t.limit))),i}resolveAndUpdateDocumentNotifications(t,i){try{Object.keys(t).forEach(e=>{let o=t[e]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[e]||{},r;if(i==="user")r=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[e]?.notifications||[]});else if(i==="notification"){let a=t[e]?.notifications?.reduce((c,n)=>(c[n.notificationId]=n,c),{}),s=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:a});r=Object.values(s??{})}else{let a=t[e]?.notifications?.reduce((c,n)=>(c[n.notificationId]=n,c),{}),s=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:a});r=Object.values(s??{})}r.forEach(a=>{a.notification=this.getClientNotificationObject(a)}),this.setNotificationForDocumentIdInCache(e,o,r)})}catch(e){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",e)}}resolveAndMergeUserNotifications(t,i,e=!1){try{let o=t;if(e&&i==="comment"){let n=this.getUserNotificationsFromServer()??[],l=new Set(t.map(g=>g.notificationId));o=n.filter(g=>l.has(g.notificationId)).concat(t.filter(g=>!n.some(d=>d.notificationId===g.notificationId)))}let r=o.reduce((n,l)=>(n[l.notificationId]=l,n),{}),a;if(i==="user"){let n=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:r});a=Object.values(n??{})}else if(i==="notification"){let n=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:r});a=Object.values(n??{})}else{let n=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:r});a=Object.values(n??{})}a.forEach(n=>{n.notification=this.getClientNotificationObject(n)});let s=this.getUserNotificationsFromServer()??[],c=new Map(s.map(n=>[n.notificationId,n]));a.forEach(n=>{c.set(n.notificationId,n)}),this.setUserNotificationsFromServer(Array.from(c.values()))}catch(o){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",o)}}fetchNotificationsForDocumentIds(t,i=15){return D(this,null,function*(){try{if(t?.length){let e=this.docService.getOrganizationConfig()?.organizationId??"";if(!e)return[];let o=this.getStartAtTimestamp(),r={};t.forEach(h=>{if(h?.documentId){let N=this.getAllowedDocumentMetadataByDocumentId(h.documentId);N&&(r[h.documentId]=N)}}),this.userPermissionService?.isPermissionProviderAvailable()&&(t=yield this.filterDocumentIdsByPermissionProvider(t));let a=this.userScopedNotifications$.getValue(),s=!!a?.enabled&&i!==1&&!this.getCurrentDocumentOnly();if(!t.length&&(this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),!s))return[];let c=this.userPermissionService?.getPermissionsCache()?.filter(h=>h.type===J.CONTEXT),n=I({organizationId:e,documentIds:t.filter(h=>!!h.documentId&&!!h.timestamp).map(h=>({documentId:h.documentId,timestamp:h.timestamp??0})),timestamp:o,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:c,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},s&&{getUserNotificationsForOrganization:!0,userNotificationsLimitToLast:di(a?.limit)}),{notificationsByDocumentId:l,userNotifications:g=[],userNotificationIdsInDocNotifications:d=[],permissionResults:f=[]}=yield this.callGetNotificationsForDocuments(n);if(this.userPermissionService?.getIsContextEnabled()){let h=[...this.userPermissionService?.getPermissionsCache()??[],...f??[]];this.userPermissionService?.setPermissionsCache(h)}if(l&&typeof l=="object"){let h=this.usersService.userDataProviderAvailable(),N=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),A=this.notificationResolverService.notificationDataProviderAvailable(),$=[],z=[],B=[];Object.keys(l).forEach((O,v)=>{let T=l[O].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[O];if(T){let w=this.allowedDocumentMetadataMap$.value||{};(!w?.[O]||!K(w?.[O],T))&&this.allowedDocumentMetadataMap$.next(U(I({},w),{[O]:T}))}let E=l[O].notifications||[];E.forEach(w=>{d.includes(w.notificationId)&&!g.find(st=>st.notificationId===w.notificationId)&&g.push(JSON.parse(JSON.stringify(w))),w.notification=this.getClientNotificationObject(w)}),this.setNotificationForDocumentIdInCache(O,T,E),h&&($.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:E,shouldAwait:!0,forceResolve:!0})),$.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:g,shouldAwait:!0,forceResolve:!0}))),N&&(z.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:E,shouldCommentAnnotationsResolverAwait:!0})),z.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:g,shouldCommentAnnotationsResolverAwait:!0}))),A&&(B.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:E,shouldNotificationResolverAwait:!0})),B.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:g,shouldNotificationResolverAwait:!0})))});let x=JSON.parse(JSON.stringify(g));if(s){let O=new Map((this.getUserNotificationsFromServer()??[]).map(v=>[v?.notificationId,v]));g.forEach(v=>O.set(v?.notificationId,v)),this.setUserNotificationsFromServer(Array.from(O.values()))}else this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...g]);(A||h||N)&&(()=>{let O=Promise.resolve();if(A&&(O=O.then(()=>Promise.allSettled(B)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"notification"),this.resolveAndMergeUserNotifications(x,"notification")})),h&&(O=O.then(()=>Promise.allSettled($)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"user"),this.resolveAndMergeUserNotifications(x,"user")})),N){let v=A||h;O=O.then(()=>Promise.allSettled(z)).then(()=>{this.resolveAndUpdateDocumentNotifications(l,"comment"),this.resolveAndMergeUserNotifications(x,"comment",v)})}return O})().catch(O=>{this.loggingService.catch("Error in NotificationService resolveChain: ",O)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}filterDocumentIdsByPermissionProvider(t){return D(this,null,function*(){try{let i=[];if(t.forEach(s=>{this.docService.getDocumentMetadata(s.documentId)||i.push(s.documentId)}),i.length){let s=this.authService.getUser(),c={type:"getDocumentMetadataFromIds",metadata:{organizationId:s?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:i},n=!!this.adapterSelectorService?.isPortableBackendActive(),l=n?void 0:X(this.functions,Q({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let g=n?yield this.invokePortableSdkProxyOp("getDocumentMetadataFromIds",c):yield ft({methodName:"getDocumentMetadataFromIds",data:c,getSdkProxy:l,userId:s?.userId??""});if(g?.data?.length){let d={};g.data.forEach(f=>{f?.documentId&&(d[f.documentId]=f)}),this.docService.setAllDocumentMetadata(I(I({},this.docService.getAllDocumentMetadataMap()),d))}}catch(g){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",g)}}let e=[],o=[];t.forEach(s=>{let c=this.docService.getDocumentMetadata(s.documentId);c?.clientDocumentId?e.push({userId:this.authService.getUser()?.userId??"",resource:I({id:c.clientDocumentId,type:J.DOCUMENT,source:W.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""},c.folderId&&{parentFolderId:c.folderId})}):o.push(s.documentId)}),o.length&&(t=t.filter(s=>!o.includes(s.documentId)));let r=Ft();this.coreActionsService.triggerAction(At.PERMISSION_PROVIDER,{event:_.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:r,methodName:W.GET_NOTIFICATIONS,source:"internal",payload:{requests:e}});let a=yield this.userPermissionService?.onResourceAccessRequired({requests:e,uniqueId:r,methodName:W.GET_NOTIFICATIONS});return a?.success&&a?.data?.length?a.data.forEach(s=>{!s.hasAccess&&s.resourceId&&(t=t.filter(c=>c.documentId!==Pt(s.resourceId)))}):t=[],t}catch(i){return this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",i),[]}})}callGetNotificationsForDocuments(t){return D(this,null,function*(){if(this.adapterSelectorService?.isPortableBackendActive())return this.callPortableGetNotificationsForDocuments(t);let i=X(this.functions,Q({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),e=yield this.notificationUtilsService.handleNotificationEncryption({data:t}),o=yield i({veltData:e}),r=o?.data?.data?.veltData||{},a=o?.data?.data?.veltAdditionalData||{},s="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),c=yield gt(r,s),{userNotifications:n,userNotificationIdsInDocNotifications:l,permissionResults:g}=yield gt(a,s);return{notificationsByDocumentId:c,userNotifications:n,userNotificationIdsInDocNotifications:l,permissionResults:g}})}callPortableGetNotificationsForDocuments(t){return D(this,null,function*(){let i=yield this.adapterSelectorService.resolveDbAdapter().getNotificationsForDocuments({scope:"org",data:t});if(!i?.ok)throw new Error(`getNotificationsForDocuments failed on the portable gateway: ${i?.code??"unknown"}`);let e=i.data??{},o=e.veltData??{},{userNotifications:r,userNotificationIdsInDocNotifications:a,permissionResults:s}=e.veltAdditionalData??{};return{notificationsByDocumentId:o,userNotifications:r,userNotificationIdsInDocNotifications:a,permissionResults:s}})}invokePortableSdkProxyOp(t,i){return D(this,null,function*(){try{let e=yield this.adapterSelectorService.resolveDbAdapter()[t]({scope:"org",data:i});return e?.ok?e.data?.veltData:(this.loggingService.catch(`Error in NotificationService ${t} (portable gateway): `,e),i)}catch(e){return this.loggingService.catch(`Error in NotificationService ${t} (portable gateway): `,e),i}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,r)=>o===r.findIndex(a=>a.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 r=this.docService.getOrganizationConfig()?.organizationId??"",a=this.docService.getOrganizationMetadata(r);i||(i=this.getOwnDocumentMetadata(t)),a||(a=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{})));let s=this.notificationsByDocumentIdMap$.getValue(),c=s?.[t]?.notifications||[],n=this.docService.getLocationMetadatas(),l=e?.map(f=>{let h=f?.notification;return h?(h.metadata&&(h.metadata.documentName=i?.documentName||h.metadata.documentName,h.metadata.organizationMetadata=a||h.metadata.organizationMetadata,h.metadata.documentMetadata=hi(i,h.metadata.documentMetadata)),n&&(h=this.notificationUtilsService.mergeLocationWithNotification({notification:h},n)?.notification),h):null})?.filter(f=>!!f)||[],g=new Map(c.map(f=>[f.id,f]));l.forEach(f=>{g.set(f.id,f)});let d=Array.from(g.values()).sort((f,h)=>(h.timestamp||0)-(f.timestamp||0));this.notificationsByDocumentIdMap$.next(U(I({},s),{[t]:{notifications:d,documentMetadata:i||{}}}))}catch(r){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",r)}}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{return St(this.maxNotificationDays$.getValue())}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(y(t=>C(t).pipe(P(i=>!!i),p(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),r=this.notificationResolverService?.notificationDataProviderAvailable();if(r||e||o){let s=i?.reduce((c,n)=>(c[n.notificationId]=n,c),{});r&&(s=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s||[]})),e&&(s=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s||[]})),o&&(s=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s||[]})),i=Object.values(s??{})}return i.forEach(s=>{s.notification=this.getClientNotificationObject(s)}),i.sort((s,c)=>c.timestamp-s.timestamp),i.map(s=>s.notification).filter(s=>!!s)}),y(i=>{let e={data:i?.reduce((o,r)=>(o[r.id]={notification:r},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(p(o=>Object.values(o?.data||{}).map(r=>r?.notification)))}))),y(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(p(()=>t))}),y(t=>this.allowedDocumentMetadataMap$.pipe(p(()=>t))),p(t=>(t?.length&&(t=t.map(i=>{if(i?.metadata){let e=this.docService.getOrganizationConfig()?.organizationId??"",o=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),r=this.docService.getOrganizationMetadata(e);o||(o=this.getOwnDocumentMetadata(i.metadata.documentId)),r||(r=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=r||i.metadata.organizationMetadata,i.metadata.documentMetadata=hi(o,i.metadata.documentMetadata)}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),C(null)}}getNotificationsForYou(){try{return H([this.getCurrentOrgNotificationsForYou(),this.crossOrgNotifications$.asObservable()]).pipe(p(([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),C({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],r=c=>c?.id??c?.notificationId,a=new Set;o.forEach(c=>{let n=r(c);n!=null&&a.add(n)});let s=[...o];return e.forEach(c=>{let n=r(c);n!=null&&a.has(n)||(n!=null&&a.add(n),s.push(c))}),s.sort((c,n)=>(n?.timestamp||0)-(c?.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(U(I({},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(U(I({},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(r=>r==="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(p(t=>t?.userId),k(),P(t=>!!t),j(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),V))).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:F(t),isCollection:!1,useCollectionGroup:!1}}).pipe(j(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),V))).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(p(i=>i?.organizationId??""),k(),at(),P(([i])=>!!i),j(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),V))).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(r=>{typeof r=="string"&&r.length&&(i[r]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(r=>{if(typeof r=="string"&&r.length){let a=Number(o[r]);i[r]=Number.isFinite(a)?a: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=U(I({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:U(I({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return D(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 r=this.commonDbService?.isPortableSession?.()===!0,a=new Map;for(let c of t){let n=r?c?.metadata?.clientOrganizationId??"":c?.metadata?.clientOrganizationId??c?.metadata?.organizationId??"",l=a.get(n);l?l.push(c):a.set(n,[c])}let s=[];for(let[c,n]of a){if(r&&!c){s.push(...n);continue}let l=n.reduce((d,f,h)=>{let N=f?.notificationId??f?.id??`__cross_org_${h}`;return d[N]=f,d},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:l,organizationId:c||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let g=l;i&&(g=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:g??{}})),e&&(g=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:g??{}})),o&&(g=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:g??{}})),s.push(...Object.values(g??{}))}return s}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return D(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,r=this.crossOrgIndexTimestamps||{},a=o?[]:Object.keys(r).filter(d=>d!==e&&(r[d]??0)>(this.crossOrgSeenTimestamps[d]??-1));if(!o&&!a.length)return;let s=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:a}),c=yield this.callGetCrossOrgUserNotifications(s);if(t!==this.crossOrgGeneration)return;let n=Array.isArray(c?.pendingPermissionQueries)?c.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),g=!n.length||!l;if(yield this.processCrossOrgResponse(c,{fetchGeneration:t,currentOrg:e,isInitial:o,indexTimestamps:r,advanceCursors:g}),t!==this.crossOrgGeneration||g){g&&t===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry();return}yield this.runCrossOrgResolveRound(n,{fetchGeneration:t,config:i,currentOrg:e,isInitial:o,bumpedOrgs:a,indexTimestamps:r})}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 D(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 r=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(r,{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 D(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||[],r=l=>o.includes(l),a=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 d=r(g);return d||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),d}),s=yield this.resolveCrossOrgSelfHostedData(a);if(i.fetchGeneration!==this.crossOrgGeneration)return;let c=s.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),n;i.isInitial?n=c:n=this.mergeCrossOrgForYou(c,this.crossOrgNotifications$.getValue()).filter(l=>r(l?.metadata?.organizationId)),i.advanceCursors&&(Object.keys(i.indexTimestamps).forEach(l=>{this.crossOrgSeenTimestamps[l]=i.indexTimestamps[l]}),this.crossOrgInitialFetchDone=!0),this.crossOrgNotifications$.next(n)})}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 D(this,null,function*(){if(this.adapterSelectorService?.isPortableBackendActive())return this.invokePortableSdkProxyOp("getCrossOrgUserNotifications",I({type:"getCrossOrgUserNotifications"},t));let i=this.authService.getUser(),e=X(this.functions,Q({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ft({methodName:"getCrossOrgUserNotifications",data:I({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},r=e?.isInitial??!0,a=e?.bumpedOrgs??[],s=Array.isArray(o.organizationIds),c=s?o.organizationIds.filter(f=>!!f).map(f=>lt(f)):[],n=(o.excludeOrganizationIds||[]).filter(f=>!!f).map(f=>lt(f)),l=new Set(n);i&&l.add(i);let g=this.userPermissionService?.getPermissionsCache?.()?.filter(f=>f?.type===J.CONTEXT),d={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?.()&&(d.clientResolverAvailable=!0),r)s&&(d.organizationIds=this.dedupeIncludeOrgs(c,l));else{let f=a.filter(N=>!!N&&!l.has(N));if(s){let N=new Set(c);f=f.filter(A=>N.has(A))}f=Array.from(new Set(f)),d.organizationIds=f;let h={};f.forEach(N=>{h[N]=this.crossOrgSeenTimestamps[N]??this.getStartAtTimestamp()}),d.orgTimestamps=h}return d}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(s=>s?.id??s?.notificationId).filter(s=>s!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),r=!1,a=o?i.filter(s=>{let c=s?.id??s?.notificationId,n=c!=null&&e.has(c);return n&&(r=!0),!n}):i.map(s=>{let c=s?.id??s?.notificationId;return c!=null&&e.has(c)&&s?.isUnread!==!1?(r=!0,U(I({},s),{isUnread:!1})):s});r&&this.crossOrgNotifications$.next(a)}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=ct(t)),i&&typeof i=="object"){let r=Mt(i);e=ct(JSON.stringify(r))}}catch(r){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",r)}return this.authService.getAuthState$().pipe(P(r=>!!r),y(r=>this.isFeatureAllowed({firebaseUser:r})),y(r=>r.featureAllowed?this.iamService.isUserAllowed$().pipe(p(a=>(r.featureAllowed=a,r))):C(r)),y(r=>!r.featureAllowed||r?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),C([])):C(r).pipe(y(a=>this.docService.getDocumentPaths$().pipe(p(s=>(this.documentPaths=s,a.documentPaths=s,a)))),y(a=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(P(i=>!!i),p(i=>U(I({},t),{config:i})),y(i=>this.authService.getUser$().pipe(p(e=>U(I({},i),{user:e})))),y(i=>Rt(i.config,i.user,Tt.NOTIFICATION)?C(U(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),C(U(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(P(i=>!!i),y(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+=`/${R.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let o=this.realtimeAdapter.rtdbRef(this.db,`${t?e+"/"+R.FIREBASE_PARTIAL_PATH_DOCS+"/"+t+"/"+R.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return this.realtimeAdapter.rtdbObjectVal$("notification",o).pipe(j(r=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",r),C(null))),p(r=>{let a=[],s=new Map;r?.raw&&(Object.keys(r?.raw||{}).forEach(n=>{let l=r?.raw[n];l?.id&&a.push(l)}),a.forEach(n=>{n.id&&s.set(n.id,n)})),this.notifications$.next(a),this.rawNotificationsByIdMap$.next(s);let c=[];r?.processed&&Object.keys(r?.processed||{}).forEach(n=>{let l=r?.processed[n];l?.id&&c.push(l)}),this.processedNotifications$.next(c),this.setNotificationsByIdMap()}))}else return C(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=F(t?.email));let o;t?.userId&&(o=F(t?.userId));let r=new Map;this.processedNotifications$.getValue().forEach(s=>{if(s.id&&s?.displayHeadlineMessageTemplate){let c=!1;(e&&s.notifyUsers?.[e]||o&&s.notifyUsers?.[o])&&(c=!0);let n={id:s.id,notificationSource:s.notificationSource,actionType:s.actionType,actionUser:s.actionUser,timestamp:s.timestamp,targetAnnotationId:s.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:c,notificationSourceData:s.notificationSourceData},l=this.getRawNotificationById(n.id);if(l?.metadata&&(n.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}),n?.notificationSource==="comment"&&n?.targetAnnotationId){let g=this.commentService?.getAnnotationById(n.targetAnnotationId);g||l?.annotationData&&(g=l.annotationData),g&&(n.notificationSourceData=this.commentService?.getCommentAnnotationForClient(g))}r.set(s.id,n)}}),r.forEach((s,c)=>{s.isUnread=s?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[c]?.views?.[t?.userSnippylyId],r.set(c,s)}),this.notificationsByIdMap$.next(r)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:r}){try{let a=this.authService.getUser(),s=r||t;if(s.id&&s?.displayHeadlineMessageTemplate&&a){let c=null;a?.email&&(c=F(a?.email));let n=null;a?.userId&&(n=F(a?.userId));let l=!1,g=!0;(c&&s.notifyUsers?.[c]||n&&s.notifyUsersByUserId?.[n])&&(l=!0),n&&o?.[n]&&(g=!1);let d={id:s.id};if(r?d=U(I(I({},d),r),{displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),forYou:l,isUnread:g}):d={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},d?.notificationSource==="comment"&&d?.targetAnnotationId){let f=this.commentService?.getAnnotationById(d.targetAnnotationId);f||r?.notificationSourceData&&(f=r?.notificationSourceData),f||i?.annotationData&&(f=i.annotationData),f&&(d.notificationSourceData=this.commentService?.getCommentAnnotationForClient(f))}return i?.targetAnnotationData?.isCommentResolverUsed&&(d.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),r?.isNotificationResolverUsed&&(d.isNotificationResolverUsed=r.isNotificationResolverUsed),d}return}catch(a){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",a);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(p(t=>t?Object.keys(t??{}).map(i=>{let e=t[i].notifications||[],o=e.filter(a=>a.isUnread).length,r=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:r,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return H([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable(),this.getUserScopedAllTabRows$()]).pipe(p(([t,i,e])=>{let o=Array.isArray(i)?i:[],r=Array.isArray(e)?e:[],a=null;if(t&&(a=[],t.forEach(c=>{c.notifications.forEach(n=>{a?.push(n)})})),!o.length&&!r.length)return t?a.sort((c,n)=>n.timestamp-c.timestamp):null;if(!t)return null;let s=a||[];return r.length&&(s=this.mergeCrossOrgForYou(s,r)),o.length&&(s=this.mergeCrossOrgForYou(s,o)),s}))}getUserScopedAllTabRows$(){return H([this.userScopedNotifications$,this.userNotificationsFromServer$.asObservable()]).pipe(p(([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 r=i?.documentId?new mt({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=r?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=r?.clientOrganizationId||t.actionUser.clientOrganizationId);let a=this.docService.getLocation();a&&(t.location=a?.location,t.locationId=a?.locationId),this.loggingService.log(`[NOTIFICATION] ${t?.notificationSource} ${t?.actionType}`,t);let s=this.commonDbService.getServerTimestamp(),c=this.notificationUtilsService.formatNotification(t,s);return JSON.parse(JSON.stringify(c))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}reportDroppedHubPush(t){try{if(!this.notificationsHubDisabled)return;let i=String(t?.notificationSource??"comment");if(this.isCarriedByPortableDeleteOp(t)||this.reportedDroppedHubPushes.has(i))return;this.reportedDroppedHubPushes.add(i),this.loggingService.catch(`Velt [self-hosted]: a client-side notification-hub push (source '${i}') was dropped \u2014 the notifications hub is deliberately disabled on this deployment (no-egress). Whatever this push fed (in-app notification, email, or webhook fan-out) will not happen for this source.`,void 0,void 0,!0)}catch{}}isCarriedByPortableDeleteOp(t){try{return t?.notificationSource==="comment"&&t?.actionType===Ct.DELETED&&!t?.annotationData?.isDraft&&!!this.adapterSelectorService?.isPortableBackendActive()}catch{return!1}}updateNotificationDatabase(t){try{if(!this.notificationsDb){this.reportDroppedHubPush(t);return}let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=this.processNotificationData(t);try{ei(t,e)}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(y(i=>i?i.organizationId?this.getAllNotifications$().pipe(y(e=>this.notificationsForYou$.pipe(p(o=>{if(e||o){let r=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(a=>{a.id&&r.set(a.id,a)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(a=>{a.id&&!r.has(a.id)&&r.set(a.id,a)}),Array.from(r.values()).sort((a,s)=>(s.timestamp||0)-(a.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(p(e=>Array.from(e.values())),p(e=>e.sort((o,r)=>r.timestamp-o.timestamp)),Nt()):C(null)),k(Bt))}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,r=/\{(\w+)\}/g,a=e.replace(r,(s,c)=>(c==="actionUser"||c==="recipientUser")&&o[c]?i?.email&&o[c].email===i?.email||i?.userId&&o[c]?.userId===i?.userId?"You":o[c].name||o[c].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':o[c]?o[c]:s);return this.domService.sanitizeHtml(a)}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(R.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(t):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${R.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(t),t?this.analyticsService.trackEvent(_.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(_.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${R.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(R.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(_.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(_.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${R.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${R.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(t){return D(this,null,function*(){try{let i=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(t?.length){for(let a=0;a<t.length;a+=50){let c=t.slice(a,a+50).filter(g=>g?.id),n=c.map(g=>this.setNotificationAsRead({notification:g,userNotifications:JSON.parse(JSON.stringify(i))})),l=yield Promise.all(n);c.forEach((g,d)=>{let f=l[d];if(!f.some(N=>N.notificationId===g.id))i=i.filter(N=>N.notificationId!==g.id);else{let N=i.find($=>$.notificationId===g.id),A=f.find($=>$.notificationId===g.id);N&&A?.views&&(N.views=A.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(a=>{let s=a.metadata?.documentId;if(s&&o?.[s]){let c=o?.[s]?.notifications||[],n=c.find(l=>l.id===a.id);n&&(n.isUnread=!1),o[s].notifications=c}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!K(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return D(this,null,function*(){try{if(t?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(Y(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(p(t=>t?.filter(e=>e?.isUnread)?.length??null),y(t=>this.getNotifications$().pipe(p(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),C({forYou:null,all:null})}}setNotificationAsRead(e){return D(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let r=F(o?.userId),{metadata:a}=t;if(a){let{apiKey:s,organizationId:c,documentId:n}=a;if(s&&c&&n&&r){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:c,documentId:n,apiKey:s}});l?.notificationId&&(l?.views?.[r]||(l.views||(l.views={}),l.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:c,documentId:n,apiKey:s},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:r,documentId:n,organizationId:c}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:r,documentId:n,organizationId:c}}),i=i.filter(d=>d.notificationId!==t.id);else if(!g?.views?.[r]){g.views||(g.views={}),g.views[r]={timestamp:Date.now()};let d=i.find(f=>f.notificationId===t.id);d&&(d.views=g.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:t.id,userId:r,documentId:n,organizationId:c},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 D(this,null,function*(){try{this.getNotifications$().pipe(Y(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)}})}getOwnDocumentMetadata(t){try{let i=t==null||t===""?null:this.docService.getDocumentMetadata(String(t));return i?JSON.parse(JSON.stringify(i)):null}catch(i){return this.loggingService.catch("Error in NotificationService getOwnDocumentMetadata: ",i),null}}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{if(t&&typeof t=="object"&&t.enabled===!1){this.disableUserScopedNotifications();return}this.userScopedNotifications$.next({enabled:!0,limit:di(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 D(this,null,function*(){try{let i=this.authService.getUser(),e=F(i?.userId??""),o=this.docService.getDocumentPaths(),r=this.docService.getOrganizationConfig(),a=o?.organizationId??r?.organizationId,s=o?.clientOrganizationId??r?.clientOrganizationId,c={apiKey:this.configService.getApiKey(),organizationId:a,documentId:o?.documentId,clientOrganizationId:s,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:s??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:c}})))}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)(m(yt),m(Yt),m(tt),m(kt),m(si),m(ri),m(ot),m(et),m(rt),m(Qt),m(ni),m(ii),m(ai),m(Z),m(li),m(it),m(Dt),m(ci),m(ti),m(q),m(qt),m(Zt))},u.\u0275prov=G({token:u,factory:u.\u0275fac,providedIn:"root"});let S=u;return S})();export{li as a,ae as b};