@veltdev/sdk-staging 6.0.0 → 6.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunk-26SHKRTG.js +1 -0
- package/{chunk-FXK7BWOQ.js → chunk-3YCIOKO7.js} +1 -1
- package/{chunk-OZMOWJWG.js → chunk-4O7F5WPS.js} +1 -1
- package/{chunk-EIIBHBQX.js → chunk-6MGKRXSY.js} +1 -1
- package/{chunk-S3KLTU2O.js → chunk-7M7HPFJW.js} +1 -1
- package/{chunk-UVG3AHTE.js → chunk-BP5ABAKN.js} +1 -1
- package/{chunk-RSPIT2S4.js → chunk-CMV6XYEA.js} +1 -1
- package/{chunk-4MGSKBFZ.js → chunk-CN3MG4V7.js} +1 -1
- package/{chunk-AVNXQEE2.js → chunk-DVLF6ZJF.js} +1 -1
- package/{chunk-YFYJFOMT.js → chunk-EWNEUCZN.js} +1 -1
- package/{chunk-62665UII.js → chunk-FXVG7I7B.js} +1 -1
- package/{chunk-6SB63H3W.js → chunk-JD2Q4WUT.js} +1 -1
- package/{chunk-5YVVMUVJ.js → chunk-JMH4W4CX.js} +1 -1
- package/{chunk-42DJQDO6.js → chunk-KPEMFTQE.js} +1 -1
- package/{chunk-OPJU6Y6N.js → chunk-LSGQWTXT.js} +1 -1
- package/{chunk-POBWY53V.js → chunk-MJHVVJAE.js} +1 -1
- package/{chunk-UGCJET7Y.js → chunk-NWDWX5YO.js} +1 -1
- package/{chunk-CI2JGL4P.js → chunk-O7QMGDXD.js} +1 -1
- package/{chunk-SYUQPGKV.js → chunk-OMM2AMDX.js} +1 -1
- package/{chunk-3CWPPM3P.js → chunk-OO7EO3BV.js} +1 -1
- package/{chunk-BPPXBXFT.js → chunk-P6UVM6B7.js} +1 -1
- package/{chunk-PVOJRXAC.js → chunk-PNALREKY.js} +1 -1
- package/{chunk-IE3AYTRD.js → chunk-Q3SFRIYZ.js} +1 -1
- package/{chunk-EPT5TVX4.js → chunk-QEJJ3QNA.js} +1 -1
- package/{chunk-WOT7KXUQ.js → chunk-QYUV5PXV.js} +1 -1
- package/{chunk-CVMNWHT4.js → chunk-RF3TL6SQ.js} +6 -6
- package/chunk-THHKSZTD.js +1 -0
- package/{chunk-UCTOPWFQ.js → chunk-W6OGMNHQ.js} +1 -1
- package/{chunk-AE6AKOBL.js → chunk-WQRY6Y6C.js} +1 -1
- package/{chunk-QD4B4F67.js → chunk-WW7AGQRC.js} +1 -1
- package/{chunk-ZOLCVAWT.js → chunk-XDHXV3V6.js} +1 -1
- package/{chunk-QX6IGTVL.js → chunk-YBCNVNZM.js} +1 -1
- package/{chunk-SKH4QRW2.js → chunk-YQEMM6AB.js} +1 -1
- package/package.json +1 -1
- package/velt-activity-log.js +1 -1
- package/velt-area.js +1 -1
- package/velt-arrow.js +1 -1
- package/velt-comment.js +6 -6
- package/velt-crdt.js +1 -1
- package/velt-cursor.js +1 -1
- package/velt-huddle.js +1 -1
- package/velt-live-state-sync.js +1 -1
- package/velt-notification.js +1 -1
- package/velt-presence.js +1 -1
- package/velt-reaction.js +1 -1
- package/velt-recorder.js +1 -1
- package/velt-rewriter.js +1 -1
- package/velt-selection.js +1 -1
- package/velt-tag.js +1 -1
- package/velt-user-invite.js +1 -1
- package/velt-user-request.js +1 -1
- package/velt-video-player.js +1 -1
- package/velt-views.js +1 -1
- package/velt.js +2 -2
- package/chunk-ADSEZJIT.js +0 -1
- package/chunk-PRGWBNVO.js +0 -1
package/velt-views.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as Re,c as qe,d as We}from"./chunk-UCTOPWFQ.js";import{a as mt}from"./chunk-UVG3AHTE.js";import{t as at}from"./chunk-3CWPPM3P.js";import"./chunk-CI2JGL4P.js";import"./chunk-RSPIT2S4.js";import{a as dt}from"./chunk-PRGWBNVO.js";import"./chunk-IE3AYTRD.js";import{a as rt}from"./chunk-UGCJET7Y.js";import"./chunk-POBWY53V.js";import"./chunk-BPPXBXFT.js";import{b as ot,d as st}from"./chunk-QX6IGTVL.js";import{a as lt}from"./chunk-42DJQDO6.js";import{a as ct}from"./chunk-4MGSKBFZ.js";import{a as Pe}from"./chunk-AE6AKOBL.js";import{A as ze,G as $e,H as Ne,I as Le,ca as it,ea as nt}from"./chunk-CVMNWHT4.js";import{$ as xe,Ai as et,Bf as he,Ch as ye,E as A,Ed as Fe,Ee as O,Fa as h,Fc as ke,Fh as Je,Fi as ue,Ga as re,Gc as le,Ib as se,J as ie,Kb as ae,L as J,M as Ie,Nb as E,Ob as H,Pa as I,Pb as R,Pc as Te,Pi as tt,Rb as Ae,S as Ce,T as S,Ta as Oe,Td as Me,Ua as Z,Ud as je,Uh as Ye,Va as Be,W as De,Y as pe,Yf as Ke,_a as z,a as m,aa as _e,ac as Ue,b as y,ca as T,fi as Qe,g as q,ha as P,ia as F,ii as de,ja as Y,ka as Q,kc as U,ki as D,l as $,lb as x,lc as k,li as Ze,mb as v,nb as w,ne as Ge,ob as M,pc as ce,qa as ne,qh as He,r as V,sb as W,sh as we,si as me,tb as G,ti as Xe,ua as Ee,ui as fe,v as f,vb as K,w as X,wa as oe,xb as j,zb as _,zi as N}from"./chunk-FXK7BWOQ.js";var L=(()=>{let c=class c{constructor(e,t,n,i,o,a,d,s,u,g){this.afAuth=e,this.authService=t,this.configService=n,this.databaseService=i,this.docService=o,this.commonDbService=a,this.iamService=d,this.loggingService=s,this.userPermissionService=u,this.serviceBook=g,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(Ye).subscribe(p=>{this.commentService=p??void 0}),this.serviceBook.observe(Je).subscribe(p=>{this.notificationService=p??null}),this.databaseService.getDb().pipe(A(p=>!!p),ie(1)).subscribe(p=>{p&&(this.subscribeViewsData().subscribe(),this.getNotificationFeatureViews$().subscribe(C=>{this.notificationService?.setNotificationViews(C)}),this.authService.getUser$().pipe(A(C=>!!C),S(C=>this.documentViewsEnabled$.pipe(A(b=>b),f(()=>C))),S(C=>this.docService.getDocumentPaths$().pipe(Ce(null),Ie(),f(([b,B])=>(b?.documentId!==B?.documentId&&this.views$.next({}),B)),f(b=>(this.documentPaths=b,this.setDocumentAsRead({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),{_user:C,_documentPaths:b})),S(b=>this.docService.getDocumentIds$().pipe(S(B=>(B?.length&&(B.find(te=>te.documentId===this.documentPaths?.documentId)||B.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),B.forEach(te=>{this.setDocumentAsRead({documentId:te.documentId,clientDocumentId:te.clientDocumentId})})),V(b))))))),S(C=>this.docService.getDocumentMetadata$().pipe(A(b=>!!b),f(b=>y(m({},C),{_documentMetadata:b}))))).subscribe(),this.authService.getUser$().pipe(A(C=>!!C),S(C=>this.documentViewsEnabled$.pipe(A(b=>b),f(()=>C))),S(C=>this.docService.getLocation$().pipe(A(b=>!!b))),S(C=>this.docService.getDocumentIds$().pipe(S(b=>(b.find(B=>B.documentId===this.documentPaths?.documentId)||b.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),b.forEach(B=>{this.setLocationAsRead({documentId:B.documentId,clientDocumentId:B.clientDocumentId})}),V(C)))))).subscribe())},p=>{this.loggingService.catch("Error in ViewsService getDb subscription: ",p)})}catch(p){this.loggingService.catch("Error in ViewsService constructor: ",p)}}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=he(e)),t&&typeof t=="object"){let o=Ke(t);n=he(JSON.stringify(o))}}catch(o){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",o)}return this.authService.getAuthState$().pipe(A(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(d=>(this.documentPaths=d,a.documentPaths=d,a)))),S(a=>i?this.getDataFromDocumentIds([i]):this.docService.getDocumentIds$().pipe(S(d=>{let s=d?.length>0?d.map(u=>u.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(s)})))):V([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(A(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}))),J((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?X([this.getCommentViewsDataFromDocuments(),this.getDocumentViewsDataFromDocuments(t),this.getLocationViewsDataFromDocuments(t)]):X([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(A(e=>!!e),De(e=>{this.getCommentViews(e)})):V([])}catch(e){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",e),V([])}}getDocumentViewsDataFromDocuments(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+=O.LISTENER_BATCH_SIZE)o.push(e?.slice(a,a+O.LISTENER_BATCH_SIZE)??[]);return n=X(o.map(a=>this.commonDbService.dbListener({feature:"allDocumentViews",properties:y(m({},i),{firestoreQuery:[fe(N("metadata.apiKey","==",this.configService?.getApiKey()),N("metadata.documentId","in",a),N("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[N("metadata.veltFolderId","==",t)]:[])]})}).pipe(pe()))).pipe(f(a=>we(a))),n.pipe(f(a=>({data:a?.data,operation:a?.operation})),f(({data:a,operation:d})=>{let s={};return e?(Object.entries(a??{}).forEach(([u,g])=>{let p=g.metadata?.documentId;p&&(s[p]||(s[p]={}),s[p][u]=g)}),{data:a,documentMap:s,operation:d}):{data:a,documentMap:s,operation:d}}),f(({data:a,documentMap:d,operation:s})=>{if(s?.type==="removed"){if(s?.ids?.length){let u=this.documentViews$.value;s?.ids?.forEach(g=>{delete u?.[g]}),this.documentViews$.next(u)}}else Object.entries(d??{}).forEach(([u,g])=>{this.setDocumentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:u,documentViews:g})})}))}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+=O.LISTENER_BATCH_SIZE)o.push(e?.slice(a,a+O.LISTENER_BATCH_SIZE)??[]);return n=X(o.map(a=>this.commonDbService.dbListener({feature:"allLocationViews",properties:y(m({},i),{firestoreQuery:[fe(N("metadata.apiKey","==",this.configService?.getApiKey()),N("metadata.documentId","in",a),N("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[N("metadata.veltFolderId","==",t)]:[])]})}).pipe(pe()))).pipe(f(a=>we(a))),n.pipe(f(a=>({data:a?.data,operation:a?.operation})),f(({data:a,operation:d})=>{let s={};return e?(Object.entries(a??{}).forEach(([u,g])=>{let p=g.metadata?.documentId;p&&(s[p]||(s[p]={}),s[p][u]=g)}),{data:a,documentMap:s,operation:d}):{data:a,documentMap:s,operation:d}}),f(({data:a,documentMap:d,operation:s})=>{if(s?.type==="removed"){if(s?.ids?.length){let u=this.locationViews$.value;s?.ids?.forEach(g=>{delete u?.[g]}),this.locationViews$.next(u)}}else Object.entries(d??{}).forEach(([u,g])=>{this.setLocationViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:u,locationViews:g})})}))}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=O.NO_ORGANIZATION_ID),i||(i=O.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=O.NO_ORGANIZATION_ID),i||(i=O.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=O.NO_ORGANIZATION_ID),i||(i=O.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(J((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}setCommentAnnotationAsRead(e){return q(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 q(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 d=new Set(e.comments?.map(s=>s.commentId+""));if(Object.keys(o??{}).forEach(s=>{d.has(s)||delete o[s]}),e.comments?.length){let s=o[e.comments[0].commentId]?.views||{},u=Object.keys(s??{}).filter(g=>e.comments?.every(p=>o[p.commentId]?.views?.[g]));u.forEach(g=>{i[g]={timestamp:s[g].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(d=>{o[d.commentId]?.views?.[t.userSnippylyId]&&delete o[d.commentId].views[t.userSnippylyId]});let a=new Set(e.comments?.map(d=>d.commentId+""));if(Object.keys(o??{}).forEach(d=>{a.has(d)||delete o[d]}),e.comments?.length){let d=o[e.comments[0].commentId]?.views||{},s=Object.keys(d??{}).filter(u=>e.comments?.every(g=>o[g.commentId]?.views?.[u]));s.forEach(u=>{i[u]={timestamp:d[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(J((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(J((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||{}:{}})))),J(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 q(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],d=this.getDocumentViewsById(e);if(d){let s=new Date().toISOString().split("T")[0];d?.users[i.userSnippylyId]||(d.users[i.userSnippylyId]={}),d.users[i.userSnippylyId][s]={timestamp:this.timestamp},d?.day[s]||(d.day[s]={}),d.day[s][i.userSnippylyId]={timestamp:this.timestamp},d.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:d})}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(A(s=>s!==null),ie(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(ie(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(Ge.FIRST_VIEWED,{documentViews:{emails:i}})}}})}catch(t){this.loggingService.catch("Error in checkAndTriggerNotification:",t)}}setLocationAsRead(n){return q(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let i=this.authService.getUser(),o=this.docService.getLocation(),a=o?.locationId,d=o?.location;if(i&&a&&d){let s=new Date().getTime()+this.commonDbService.getOffset(),u=new Date().toISOString().split("T")[0],g=this.getLocationViewsById(a);if(g){let p=new Date().toISOString().split("T")[0];g?.users[i.userSnippylyId]||(g.users[i.userSnippylyId]={}),g.users[i.userSnippylyId][p]={timestamp:this.timestamp},g?.day[p]||(g.day[p]={}),g.day[p][i.userSnippylyId]={timestamp:this.timestamp},g.metadata=this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"location",data:g,properties:{id:a,documentId:e,organizationId:this.documentPaths?.organizationId??""}})}else{this.commonDbService.updateData({feature:"locationViews",data:d,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 p={day:{[u]:{[i.userSnippylyId]:{timestamp:s}}},users:{[i.userSnippylyId]:{[u]:{timestamp:s}}},metadata:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),location:d};this.commonDbService.updateData({feature:"location",data:p,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)(T(Fe),T(Xe),T(Ze),T(et),T(ue),T(tt),T(ct),T(D),T(dt),T(de))},c.\u0275prov=xe({token:c,factory:c.\u0275fac,providedIn:"root"});let l=c;return l})();function wt(l,c){if(l&1&&(W(0),v(1,"div",21)(2,"div",22),M(3,"snippyly-user-avatar",23),w(),v(4,"div",24)(5,"div",25),E(6),U(7,"translate"),w()(),v(8,"div",26),E(9),U(10,"timeAgo"),w()(),G()),l&2){let r=c.$implicit;h(3),x("user",r==null?null:r.user)("size",32),h(3),R(" ",k(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),h(3),R(" ",k(10,6,r==null?null:r.timestamp)," ")}}function yt(l,c){if(l&1&&(v(0,"div",19),z(1,wt,11,8,"ng-container",20),w()),l&2){let r=_(2).ngIf;h(),x("ngForOf",r.userViews)}}function ft(l,c){if(l&1){let r=K();W(0),v(1,"div",4)(2,"button",5),j("click",function(){P(r);let t=_(2);return F(t.closeTrendDialog())}),Y(),v(3,"svg",6),M(4,"path",7),w(),Q(),v(5,"span"),E(6),U(7,"translate"),w()()(),v(8,"div",8)(9,"div",9)(10,"div",10),E(11),w(),v(12,"div",11),Y(),v(13,"svg",12),M(14,"path",13)(15,"path",14),w(),Q(),v(16,"span"),E(17),U(18,"translate"),w()()(),v(19,"div",15)(20,"div",16),E(21),w(),v(22,"div",17)(23,"span"),E(24),U(25,"translate"),w()()()(),z(26,yt,2,1,"div",18),G()}if(l&2){let r=_().ngIf;h(6),H(k(7,6,"Go Back")),h(5),R(" ",r.totalUniqueViewsCount," "),h(6),H(k(18,8,"Total Views")),h(4),R(" ",r.todayViewsCount," "),h(3),H(k(25,10,"Views Today")),h(2),x("ngIf",r.userViews==null?null:r.userViews.length)}}function St(l,c){if(l&1&&(W(0),v(1,"div",21)(2,"div",22),M(3,"snippyly-user-avatar",23),w(),v(4,"div",24)(5,"div",25),E(6),U(7,"translate"),w(),v(8,"div",26),E(9),U(10,"timeAgo"),w()()(),G()),l&2){let r=c.$implicit;h(3),x("user",r==null?null:r.user)("size",32),h(3),R(" ",k(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),h(3),R(" ",k(10,6,r==null?null:r.timestamp)," ")}}function bt(l,c){if(l&1&&(v(0,"div",29)(1,"div",19),z(2,St,11,8,"ng-container",20),w()()),l&2){let r=_(2).ngIf;h(2),x("ngForOf",r.userViews)}}function Vt(l,c){if(l&1&&(v(0,"div",27)(1,"div",9)(2,"div",10),E(3),w(),v(4,"div",11),Y(),v(5,"svg",12),M(6,"path",13)(7,"path",14),w(),Q(),v(8,"span"),E(9),U(10,"translate"),w()()(),v(11,"div",15),E(12),U(13,"translate"),U(14,"translate"),U(15,"translate"),w()(),z(16,bt,3,1,"div",28)),l&2){let r=_().ngIf;h(3),R(" ",r.totalUniqueViewsCount," "),h(6),H(k(10,6,"Total Views")),h(3),Ae(" ",r.todayViewsCount," ",r.todayViewsCount===1?k(13,8,"View"):k(14,10,"Views")," ",k(15,12,"Today")," "),h(4),x("ngIf",r.userViews==null?null:r.userViews.length)}}function It(l,c){if(l&1){let r=K();W(0),v(1,"div",2),j("clickOutside",function(){P(r);let t=_();return F(t.closeTrendDialog())}),z(2,ft,27,12,"ng-container",3)(3,Vt,17,14,"ng-template",null,0,ce),w(),G()}if(l&2){let r=c.ngIf,e=se(4);h(),ae("bottom-sheet",r.bottomSheetMode),h(),x("ngIf",r.bottomSheetMode)("ngIfElse",e)}}var ee=(()=>{let c=class c{constructor(e,t,n,i,o,a,d){this.contactService=e,this.loggingService=t,this.viewsService=n,this.themeService=i,this.elementRef=o,this.domService=a,this.bottomSheetData=d,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{d&&(this.componentConfigSignal.update(s=>(s=y(m({},s),{bottomSheetMode:!0}),s)),this.clientLocationId=d.clientLocationId,this.closeBottomSheetFn=d.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(it),I(D),I(L),I(nt),I(oe),I(me),I(Re,8))},c.\u0275cmp=Z({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&&z(0,It,5,4,"ng-container",1),t&2&&x("ngIf",n.componentConfigSignal())},dependencies:[ke,le,rt,st,ot,mt],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{a as Re,c as qe,d as We}from"./chunk-W6OGMNHQ.js";import{a as mt}from"./chunk-BP5ABAKN.js";import{t as at}from"./chunk-OO7EO3BV.js";import"./chunk-O7QMGDXD.js";import"./chunk-CMV6XYEA.js";import{a as dt}from"./chunk-26SHKRTG.js";import"./chunk-Q3SFRIYZ.js";import{a as rt}from"./chunk-NWDWX5YO.js";import"./chunk-MJHVVJAE.js";import"./chunk-P6UVM6B7.js";import{b as ot,d as st}from"./chunk-YBCNVNZM.js";import{a as lt}from"./chunk-KPEMFTQE.js";import{a as ct}from"./chunk-CN3MG4V7.js";import{a as Pe}from"./chunk-WQRY6Y6C.js";import{A as ze,G as $e,H as Ne,I as Le,ca as it,ea as nt}from"./chunk-RF3TL6SQ.js";import{$ as xe,Ai as et,Bf as he,Ch as ye,E as A,Ed as Fe,Ee as O,Fa as h,Fc as ke,Fh as Je,Fi as ue,Ga as re,Gc as le,Ib as se,J as ie,Kb as ae,L as J,M as Ie,Nb as E,Ob as H,Pa as I,Pb as R,Pc as Te,Pi as tt,Rb as Ae,S as Ce,T as S,Ta as Oe,Td as Me,Ua as Z,Ud as je,Uh as Ye,Va as Be,W as De,Y as pe,Yf as Ke,_a as z,a as m,aa as _e,ac as Ue,b as y,ca as T,fi as Qe,g as q,ha as P,ia as F,ii as de,ja as Y,ka as Q,kc as U,ki as D,l as $,lb as x,lc as k,li as Ze,mb as v,nb as w,ne as Ge,ob as M,pc as ce,qa as ne,qh as He,r as V,sb as W,sh as we,si as me,tb as G,ti as Xe,ua as Ee,ui as fe,v as f,vb as K,w as X,wa as oe,xb as j,zb as _,zi as N}from"./chunk-3YCIOKO7.js";var L=(()=>{let c=class c{constructor(e,t,n,i,o,a,d,s,u,g){this.afAuth=e,this.authService=t,this.configService=n,this.databaseService=i,this.docService=o,this.commonDbService=a,this.iamService=d,this.loggingService=s,this.userPermissionService=u,this.serviceBook=g,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(Ye).subscribe(p=>{this.commentService=p??void 0}),this.serviceBook.observe(Je).subscribe(p=>{this.notificationService=p??null}),this.databaseService.getDb().pipe(A(p=>!!p),ie(1)).subscribe(p=>{p&&(this.subscribeViewsData().subscribe(),this.getNotificationFeatureViews$().subscribe(C=>{this.notificationService?.setNotificationViews(C)}),this.authService.getUser$().pipe(A(C=>!!C),S(C=>this.documentViewsEnabled$.pipe(A(b=>b),f(()=>C))),S(C=>this.docService.getDocumentPaths$().pipe(Ce(null),Ie(),f(([b,B])=>(b?.documentId!==B?.documentId&&this.views$.next({}),B)),f(b=>(this.documentPaths=b,this.setDocumentAsRead({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),{_user:C,_documentPaths:b})),S(b=>this.docService.getDocumentIds$().pipe(S(B=>(B?.length&&(B.find(te=>te.documentId===this.documentPaths?.documentId)||B.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),B.forEach(te=>{this.setDocumentAsRead({documentId:te.documentId,clientDocumentId:te.clientDocumentId})})),V(b))))))),S(C=>this.docService.getDocumentMetadata$().pipe(A(b=>!!b),f(b=>y(m({},C),{_documentMetadata:b}))))).subscribe(),this.authService.getUser$().pipe(A(C=>!!C),S(C=>this.documentViewsEnabled$.pipe(A(b=>b),f(()=>C))),S(C=>this.docService.getLocation$().pipe(A(b=>!!b))),S(C=>this.docService.getDocumentIds$().pipe(S(b=>(b.find(B=>B.documentId===this.documentPaths?.documentId)||b.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),b.forEach(B=>{this.setLocationAsRead({documentId:B.documentId,clientDocumentId:B.clientDocumentId})}),V(C)))))).subscribe())},p=>{this.loggingService.catch("Error in ViewsService getDb subscription: ",p)})}catch(p){this.loggingService.catch("Error in ViewsService constructor: ",p)}}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=he(e)),t&&typeof t=="object"){let o=Ke(t);n=he(JSON.stringify(o))}}catch(o){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",o)}return this.authService.getAuthState$().pipe(A(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(d=>(this.documentPaths=d,a.documentPaths=d,a)))),S(a=>i?this.getDataFromDocumentIds([i]):this.docService.getDocumentIds$().pipe(S(d=>{let s=d?.length>0?d.map(u=>u.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(s)})))):V([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(A(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}))),J((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?X([this.getCommentViewsDataFromDocuments(),this.getDocumentViewsDataFromDocuments(t),this.getLocationViewsDataFromDocuments(t)]):X([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(A(e=>!!e),De(e=>{this.getCommentViews(e)})):V([])}catch(e){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",e),V([])}}getDocumentViewsDataFromDocuments(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+=O.LISTENER_BATCH_SIZE)o.push(e?.slice(a,a+O.LISTENER_BATCH_SIZE)??[]);return n=X(o.map(a=>this.commonDbService.dbListener({feature:"allDocumentViews",properties:y(m({},i),{firestoreQuery:[fe(N("metadata.apiKey","==",this.configService?.getApiKey()),N("metadata.documentId","in",a),N("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[N("metadata.veltFolderId","==",t)]:[])]})}).pipe(pe()))).pipe(f(a=>we(a))),n.pipe(f(a=>({data:a?.data,operation:a?.operation})),f(({data:a,operation:d})=>{let s={};return e?(Object.entries(a??{}).forEach(([u,g])=>{let p=g.metadata?.documentId;p&&(s[p]||(s[p]={}),s[p][u]=g)}),{data:a,documentMap:s,operation:d}):{data:a,documentMap:s,operation:d}}),f(({data:a,documentMap:d,operation:s})=>{if(s?.type==="removed"){if(s?.ids?.length){let u=this.documentViews$.value;s?.ids?.forEach(g=>{delete u?.[g]}),this.documentViews$.next(u)}}else Object.entries(d??{}).forEach(([u,g])=>{this.setDocumentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:u,documentViews:g})})}))}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+=O.LISTENER_BATCH_SIZE)o.push(e?.slice(a,a+O.LISTENER_BATCH_SIZE)??[]);return n=X(o.map(a=>this.commonDbService.dbListener({feature:"allLocationViews",properties:y(m({},i),{firestoreQuery:[fe(N("metadata.apiKey","==",this.configService?.getApiKey()),N("metadata.documentId","in",a),N("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[N("metadata.veltFolderId","==",t)]:[])]})}).pipe(pe()))).pipe(f(a=>we(a))),n.pipe(f(a=>({data:a?.data,operation:a?.operation})),f(({data:a,operation:d})=>{let s={};return e?(Object.entries(a??{}).forEach(([u,g])=>{let p=g.metadata?.documentId;p&&(s[p]||(s[p]={}),s[p][u]=g)}),{data:a,documentMap:s,operation:d}):{data:a,documentMap:s,operation:d}}),f(({data:a,documentMap:d,operation:s})=>{if(s?.type==="removed"){if(s?.ids?.length){let u=this.locationViews$.value;s?.ids?.forEach(g=>{delete u?.[g]}),this.locationViews$.next(u)}}else Object.entries(d??{}).forEach(([u,g])=>{this.setLocationViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:u,locationViews:g})})}))}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=O.NO_ORGANIZATION_ID),i||(i=O.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=O.NO_ORGANIZATION_ID),i||(i=O.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=O.NO_ORGANIZATION_ID),i||(i=O.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(J((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}setCommentAnnotationAsRead(e){return q(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 q(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 d=new Set(e.comments?.map(s=>s.commentId+""));if(Object.keys(o??{}).forEach(s=>{d.has(s)||delete o[s]}),e.comments?.length){let s=o[e.comments[0].commentId]?.views||{},u=Object.keys(s??{}).filter(g=>e.comments?.every(p=>o[p.commentId]?.views?.[g]));u.forEach(g=>{i[g]={timestamp:s[g].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(d=>{o[d.commentId]?.views?.[t.userSnippylyId]&&delete o[d.commentId].views[t.userSnippylyId]});let a=new Set(e.comments?.map(d=>d.commentId+""));if(Object.keys(o??{}).forEach(d=>{a.has(d)||delete o[d]}),e.comments?.length){let d=o[e.comments[0].commentId]?.views||{},s=Object.keys(d??{}).filter(u=>e.comments?.every(g=>o[g.commentId]?.views?.[u]));s.forEach(u=>{i[u]={timestamp:d[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(J((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(J((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||{}:{}})))),J(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 q(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],d=this.getDocumentViewsById(e);if(d){let s=new Date().toISOString().split("T")[0];d?.users[i.userSnippylyId]||(d.users[i.userSnippylyId]={}),d.users[i.userSnippylyId][s]={timestamp:this.timestamp},d?.day[s]||(d.day[s]={}),d.day[s][i.userSnippylyId]={timestamp:this.timestamp},d.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:d})}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(A(s=>s!==null),ie(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(ie(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(Ge.FIRST_VIEWED,{documentViews:{emails:i}})}}})}catch(t){this.loggingService.catch("Error in checkAndTriggerNotification:",t)}}setLocationAsRead(n){return q(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let i=this.authService.getUser(),o=this.docService.getLocation(),a=o?.locationId,d=o?.location;if(i&&a&&d){let s=new Date().getTime()+this.commonDbService.getOffset(),u=new Date().toISOString().split("T")[0],g=this.getLocationViewsById(a);if(g){let p=new Date().toISOString().split("T")[0];g?.users[i.userSnippylyId]||(g.users[i.userSnippylyId]={}),g.users[i.userSnippylyId][p]={timestamp:this.timestamp},g?.day[p]||(g.day[p]={}),g.day[p][i.userSnippylyId]={timestamp:this.timestamp},g.metadata=this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"location",data:g,properties:{id:a,documentId:e,organizationId:this.documentPaths?.organizationId??""}})}else{this.commonDbService.updateData({feature:"locationViews",data:d,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 p={day:{[u]:{[i.userSnippylyId]:{timestamp:s}}},users:{[i.userSnippylyId]:{[u]:{timestamp:s}}},metadata:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),location:d};this.commonDbService.updateData({feature:"location",data:p,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)(T(Fe),T(Xe),T(Ze),T(et),T(ue),T(tt),T(ct),T(D),T(dt),T(de))},c.\u0275prov=xe({token:c,factory:c.\u0275fac,providedIn:"root"});let l=c;return l})();function wt(l,c){if(l&1&&(W(0),v(1,"div",21)(2,"div",22),M(3,"snippyly-user-avatar",23),w(),v(4,"div",24)(5,"div",25),E(6),U(7,"translate"),w()(),v(8,"div",26),E(9),U(10,"timeAgo"),w()(),G()),l&2){let r=c.$implicit;h(3),x("user",r==null?null:r.user)("size",32),h(3),R(" ",k(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),h(3),R(" ",k(10,6,r==null?null:r.timestamp)," ")}}function yt(l,c){if(l&1&&(v(0,"div",19),z(1,wt,11,8,"ng-container",20),w()),l&2){let r=_(2).ngIf;h(),x("ngForOf",r.userViews)}}function ft(l,c){if(l&1){let r=K();W(0),v(1,"div",4)(2,"button",5),j("click",function(){P(r);let t=_(2);return F(t.closeTrendDialog())}),Y(),v(3,"svg",6),M(4,"path",7),w(),Q(),v(5,"span"),E(6),U(7,"translate"),w()()(),v(8,"div",8)(9,"div",9)(10,"div",10),E(11),w(),v(12,"div",11),Y(),v(13,"svg",12),M(14,"path",13)(15,"path",14),w(),Q(),v(16,"span"),E(17),U(18,"translate"),w()()(),v(19,"div",15)(20,"div",16),E(21),w(),v(22,"div",17)(23,"span"),E(24),U(25,"translate"),w()()()(),z(26,yt,2,1,"div",18),G()}if(l&2){let r=_().ngIf;h(6),H(k(7,6,"Go Back")),h(5),R(" ",r.totalUniqueViewsCount," "),h(6),H(k(18,8,"Total Views")),h(4),R(" ",r.todayViewsCount," "),h(3),H(k(25,10,"Views Today")),h(2),x("ngIf",r.userViews==null?null:r.userViews.length)}}function St(l,c){if(l&1&&(W(0),v(1,"div",21)(2,"div",22),M(3,"snippyly-user-avatar",23),w(),v(4,"div",24)(5,"div",25),E(6),U(7,"translate"),w(),v(8,"div",26),E(9),U(10,"timeAgo"),w()()(),G()),l&2){let r=c.$implicit;h(3),x("user",r==null?null:r.user)("size",32),h(3),R(" ",k(7,4,(r==null||r.user==null?null:r.user.name)||(r==null||r.user==null?null:r.user.email))," "),h(3),R(" ",k(10,6,r==null?null:r.timestamp)," ")}}function bt(l,c){if(l&1&&(v(0,"div",29)(1,"div",19),z(2,St,11,8,"ng-container",20),w()()),l&2){let r=_(2).ngIf;h(2),x("ngForOf",r.userViews)}}function Vt(l,c){if(l&1&&(v(0,"div",27)(1,"div",9)(2,"div",10),E(3),w(),v(4,"div",11),Y(),v(5,"svg",12),M(6,"path",13)(7,"path",14),w(),Q(),v(8,"span"),E(9),U(10,"translate"),w()()(),v(11,"div",15),E(12),U(13,"translate"),U(14,"translate"),U(15,"translate"),w()(),z(16,bt,3,1,"div",28)),l&2){let r=_().ngIf;h(3),R(" ",r.totalUniqueViewsCount," "),h(6),H(k(10,6,"Total Views")),h(3),Ae(" ",r.todayViewsCount," ",r.todayViewsCount===1?k(13,8,"View"):k(14,10,"Views")," ",k(15,12,"Today")," "),h(4),x("ngIf",r.userViews==null?null:r.userViews.length)}}function It(l,c){if(l&1){let r=K();W(0),v(1,"div",2),j("clickOutside",function(){P(r);let t=_();return F(t.closeTrendDialog())}),z(2,ft,27,12,"ng-container",3)(3,Vt,17,14,"ng-template",null,0,ce),w(),G()}if(l&2){let r=c.ngIf,e=se(4);h(),ae("bottom-sheet",r.bottomSheetMode),h(),x("ngIf",r.bottomSheetMode)("ngIfElse",e)}}var ee=(()=>{let c=class c{constructor(e,t,n,i,o,a,d){this.contactService=e,this.loggingService=t,this.viewsService=n,this.themeService=i,this.elementRef=o,this.domService=a,this.bottomSheetData=d,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{d&&(this.componentConfigSignal.update(s=>(s=y(m({},s),{bottomSheetMode:!0}),s)),this.clientLocationId=d.clientLocationId,this.closeBottomSheetFn=d.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(it),I(D),I(L),I(nt),I(oe),I(me),I(Re,8))},c.\u0275cmp=Z({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&&z(0,It,5,4,"ng-container",1),t&2&&x("ngIf",n.componentConfigSignal())},dependencies:[ke,le,rt,st,ot,mt],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 l=c;return l})();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 q(this,null,function*(){try{this.bottomSheetRef=this.bottomSheet.open(ee,{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(qe),I(D))},c.\u0275cmp=Z({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 l=c;return l})();var xt=()=>["snippyly-overlay-panel","v-view-analytics-overlay-panel","velt-overlay-panel"];function _t(l,c){if(l&1){let r=K();v(0,"velt-view-analytics-dialog",11),j("close",function(){P(r);let t=_(2);return F(t.toggleTrends())}),w()}if(l&2){let r=_(2);x("clientLocationId",r.clientLocationId)}}function Et(l,c){if(l&1){let r=K();v(0,"velt-view-analytics-bottom-sheet-internal",11),j("close",function(){P(r);let t=_(2);return F(t.closeTrends())}),w()}if(l&2){let r=_(2);x("clientLocationId",r.clientLocationId)}}function Ot(l,c){if(l&1){let r=K();W(0),v(1,"div",3,0),j("click",function(t){return P(r),_().toggleTrends(),F(t.stopPropagation())}),v(3,"slot",4),j("slotchange",function(){P(r);let t=_();return F(t.onButtonSlotChange())}),v(4,"div",5),Y(),v(5,"svg",6),M(6,"path",7),w(),Q(),v(7,"span",8),E(8),w()()()(),z(9,_t,1,1,"ng-template",9,1,ce)(11,Et,1,1,"velt-view-analytics-bottom-sheet-internal",10),G()}if(l&2){let r=c.ngIf,e=se(2),t=_();h(4),ae("active",r.treadsVisible),h(4),H(r.totalUniqueViewsCount),h(),x("cdkConnectedOverlayOrigin",e)("cdkConnectedOverlayOpen",!r.isPhone&&r.treadsVisible)("cdkConnectedOverlayPanelClass",Ue(11,xt))("cdkConnectedOverlayBackdropClass","snippyly-overlay-backdrop")("cdkConnectedOverlayGrowAfterOpen",!0)("cdkConnectedOverlayPositions",t.positions)("cdkConnectedOverlayDisableClose",!0),h(2),x("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=O.OVERLAY_POSITIONS.map(d=>new ze({originX:d.originX,originY:d.originY},{overlayX:d.overlayX,overlayY:d.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(Me),I(ue),I(D),I(L),I(oe),I(me))},c.\u0275cmp=Z({type:c,selectors:[["velt-view-analytics-internal"]],inputs:{type:"type",clientLocationId:[0,"locationId","clientLocationId"]},standalone:!1,features:[Ee],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&&z(0,Ot,12,12,"ng-container",2),t&2&&x("ngIf",n.componentConfigSignal())},dependencies:[le,Ne,$e,ee,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 l=c;return l})();var ve=class extends lt{constructor(c){super(c),this.getService(D).log("%c[WB] Creating CLASS: ViewsElement","color: blue;"),this.getUniqueViewsByUser=this._getUniqueViewsByUser,this.getUniqueViewsByDate=this._getUniqueViewsByDate}_getUniqueViewsByUser(c){this.getService(D).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(L).getUniqueViewsByUser(c)}catch(r){return this.getService(D).catch("Error in getUniqueViewsByUser: ",r),V({})}}_getUniqueViewsByDate(c){this.getService(D).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(L).getUniqueViewsByDate(c)}catch(r){return this.getService(D).catch("Error in getUniqueViewsByDate: ",r),V({})}}};var gt=(()=>{let c=class c{};c.\u0275fac=function(t){return new(t||c)},c.\u0275mod=Be({type:c}),c.\u0275inj=_e({imports:[Te,Le,We,at]});let l=c;return l})();function Bt(l){l.get(D).log("%c[WB] Loading view feature chunk","color: blue;"),l.get(de).set(Qe,l.get(L));let t=Oe(gt,l).injector;return At(t,O.TAGS.VELT_VIEW_ANALYTICS,Ve),new ve(l)}function At(l,c,r){if(customElements.get(c))return;let e=Pe(r,{injector:l});customElements.define(c,e)}export{Bt as default};
|
package/velt.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var SNIPPYLY_VERSION = '6.0.
|
|
1
|
+
var SNIPPYLY_VERSION = '6.0.1';
|
|
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 Ms}from"./chunk-
|
|
4
|
+
import{a as Ms}from"./chunk-LSGQWTXT.js";import{d as T}from"./chunk-4O7F5WPS.js";import{a as Ps}from"./chunk-PNALREKY.js";import{b as Oo,d as re}from"./chunk-EWNEUCZN.js";import"./chunk-7M7HPFJW.js";import{a as qo,d as Bo}from"./chunk-6MGKRXSY.js";import"./chunk-DVLF6ZJF.js";import"./chunk-QEJJ3QNA.js";import{d as So}from"./chunk-FXVG7I7B.js";import{d as Yo}from"./chunk-W6OGMNHQ.js";import"./chunk-WW7AGQRC.js";import"./chunk-BP5ABAKN.js";import"./chunk-JD2Q4WUT.js";import{b as As,c as Rs,j as ks,q as di,t as xs}from"./chunk-OO7EO3BV.js";import"./chunk-O7QMGDXD.js";import{l as Vo,m as Go,o as $o,r as Qo,s as Xo,u as Jo,v as Zo,w as es}from"./chunk-CMV6XYEA.js";import{a as ui}from"./chunk-26SHKRTG.js";import{a as Ds}from"./chunk-Q3SFRIYZ.js";import"./chunk-NWDWX5YO.js";import{A as xe,B as Se,a as Ye,b as si,c as fs,d as ct,e as vs,f as ai,g as li,h as ci,i as Rt,j as ys,k as _s,l as Cs,m as bs,n as Es,t as Ss,u as Ts,v as Os,w as Is,x as Pr}from"./chunk-MJHVVJAE.js";import{a as gs}from"./chunk-P6UVM6B7.js";import{a as Ke,b as De,c as kt,d as hi}from"./chunk-YBCNVNZM.js";import{a as Pe}from"./chunk-KPEMFTQE.js";import{a as dt}from"./chunk-CN3MG4V7.js";import{a as xr}from"./chunk-WQRY6Y6C.js";import{I as ii,M as Wo,S as Et,ba as Ko,ca as Z,ea as At,l as Co,o as bo,p as Eo,v as To,y as Dr}from"./chunk-RF3TL6SQ.js";import{$ as le,$b as ke,Aa as lo,Ab as Ve,Af as ns,Bb as Ge,Bd as Do,Bi as cs,Ca as co,Cd as xo,Cf as ni,Ch as g,Ci as ds,Da as ho,Db as Kt,Dd as Po,Di as hs,E as to,Eb as Xt,Ee as A,Ei as us,Fa as X,Fb as Jt,Fc as Zt,Fi as D,Ga as uo,Gc as $e,Gd as Mo,Gi as It,Ha as Er,Hd as No,Ib as Tr,Id as wo,Ie as ri,Ii as ms,J as io,Je as rs,Kb as _t,Kd as Lo,Ke as Tt,L as ro,Lc as bt,Mi as ps,Na as mo,Nb as je,Ob as Or,Pa as R,Pb as Ct,Pd as Fo,Qc as ei,Qd as zo,Rc as fo,Rd as Uo,Sc as vo,Tc as ti,Td as jo,Ua as j,Ud as Ho,Va as Re,Vc as yo,Vd as St,Wc as _o,Wd as Qe,Ya as Sr,Z as I,_a as ge,_b as Ir,a as k,aa as Ae,ac as po,b as G,ba as no,be as ts,c as Kn,ca as U,cc as Ar,d as ml,da as Fe,db as Ue,e as jt,f as Xn,fb as qe,g as L,gb as Be,ha as st,i as Wt,ia as at,ja as Ht,ji as Ot,kc as We,ki as l,l as Jn,la as be,lb as W,lc as He,li as B,m as M,ma as Cr,mb as $,md as Io,mi as as,nb as te,ni as ls,oa as oo,ob as J,oe as C,pc as Rr,pg as os,qa as so,qc as go,qi as oi,r as x,re as is,sb as Qt,si as fe,tb as Yt,ti as ie,ua as $t,v as Zn,va as ao,vb as lt,w as eo,wa as ze,xb as Ee,xc as kr,xd as Ao,yd as Ro,yh as ss,za as br,zb as q,zd as ko}from"./chunk-3YCIOKO7.js";var jn=ml((fv,Gn)=>{"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-ADSEZJIT.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as Zt}from"./chunk-PRGWBNVO.js";import{a as Qt}from"./chunk-4MGSKBFZ.js";import{$ as K,$e as q,Ai as Wt,Bf as gt,Bi as st,Cf as z,Ch as L,Df as At,Dh as tt,E as F,Ed as Nt,Ee as P,Ef as ft,Fh as Ft,Fi as kt,G as V,Gi as rt,Hh as Pt,Hi as nt,J as k,Ki as mt,L as J,M as lt,Mi as at,Ni as Jt,O as St,Od as It,Oi as Kt,Pi as qt,Qf as Ut,Rf as Tt,Sh as zt,T as I,Uf as Et,Uh as Bt,Vf as $t,W as vt,Yf as Rt,a as D,af as Q,b as T,be as Ot,bg as wt,ca as m,cg as dt,da as pt,g as E,hg as Z,ii as it,ji as xt,ki as et,l as O,li as jt,oe as yt,oi as Ht,p as G,q as ct,qh as Mt,qi as Vt,r as C,si as Lt,ti as ot,uf as bt,ui as Yt,v as N,vi as _t,w as W,xh as ht,xi as Gt,yf as Dt,zf as Ct,zh as X,zi as ut}from"./chunk-FXK7BWOQ.js";var Xt=(()=>{let A=class A{constructor(t,i,e,o,s,n,r){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=s,this.notificationResolverService=n,this.serviceBook=r,this.serviceBook.set(Pt,this)}getUserIdsToResolveFromNotifications(t){try{let i=new Set;for(let e of t){let{notification:o}=e;switch(o?.actionUser?.userId&&i.add(o?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.recipientUser?.userId),o?.notificationSource){case"comment":if(o?.notificationSourceData){let s=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let n of s)i.add(n)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.notification?.targetAnnotationId),e=t?.raw?.targetAnnotationData?.commentId,o=i?.comments?.[e]?.commentText,s=i?.comments?.[e]?.commentHtml;return o&&s&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=s),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),t}}mergeLocationWithNotification(t,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let e=t?.notification?.notificationSourceData?.location?.id,o=t?.notification?.notificationSourceData?.metadata?.documentId;if(!e||!o)return t;let s=i?.[o]?.[e];return s&&(t.notification.notificationSourceData.location=s?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=s?.location)),t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",e),t}}mergeNotificationWithUser(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=t;if(i?.actionUser?.userId){let e=this.usersService.getUserById(i?.actionUser?.userId);e&&(i.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);e&&(i.displayHeadlineMessageTemplateData.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);e&&(i.displayHeadlineMessageTemplateData.recipientUser=e)}return i?.notificationSource==="comment"&&i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),t}}formatNotification(t,i){try{switch(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData);break;case"recorder":this.serviceBook.get(zt)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),t}}getTargetAnnotationIdsFromNotifications(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(t).forEach(e=>{e?.notification?.targetAnnotationId&&e?.raw?.notificationSource==="comment"&&i.push(e.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return E(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 wt(t,e)}catch(e){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",e),t}})}getCustomNotificationIdsToResolve(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let i=new Set,e=Array.isArray(t)?t:Object.values(t||{});for(let o of e)if(o?.raw?.notificationSource==="custom"){let s=o?.notification?.id||o?.notificationId;s&&i.add(s)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",i),[]}}mergeResolvedNotificationData(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||t?.raw?.notificationSource!=="custom")return t;let i=t?.notification?.id||t?.notificationId;if(!i)return t;let e=this.notificationResolverService.getNotificationById(i);if(!e)return t;let o=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let s of o)e[s]!==void 0&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]));return Object.keys(e).forEach(s=>{!o.includes(s)&&s!=="notificationId"&&(t.notification&&(t.notification[s]=e[s]),t.raw&&(t.raw[s]=e[s]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};A.\u0275fac=function(i){return new(i||A)(m(nt),m(et),m(rt),m(ot),m(st),m(at),m(it))},A.\u0275prov=K({token:A,factory:A.\u0275fac,providedIn:"root"});let j=A;return j})();var ji=(()=>{let A=class A{constructor(t,i,e,o,s,n,r,a,c,l,g,f,d,h,p,$,M,S,U,R,w){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=s,this.commonDbUtilsService=n,this.commentUtilsService=r,this.commentAnnotationsResolverService=a,this.notificationResolverService=c,this.databaseService=l,this.docService=g,this.domService=f,this.iamService=d,this.loggingService=h,this.notificationUtilsService=p,this.usersService=$,this.functions=M,this.userPermissionService=S,this.coreActionsService=U,this.serviceBook=R,this.realtimeAdapter=w,this.endpointsService=pt(Ht),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new O([]),this.rawNotificationsByIdMap$=new O(new Map),this.processedNotifications$=new O([]),this.userNotificationsFromServer$=new O(null),this.readNotificationsOnForYouTab$=new O(!1),this.currentDocumentOnly$=new O(!1),this.notificationViews$=new O({}),this.notificationsByIdMap$=new O(new Map),this.historyPanelVisible$=new O(!1),this.notificationsForYou$=new O(null),this.notificationsByDocumentIdMap$=new O(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new O(null),this.maxNotificationDays$=new O(15),this.tabConfig$=new O({people:{enable:!1}}),this.settingsConfig$=new O(null),this.setSettingsConfigByOrganization$=new O(!1),this.muteAllNotifications$=new O(!1),this.enableSettings$=new O(!1),this.selfNotifications$=new O(!1),this.settingsInitialConfig$=new O([{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 O(!1),this.crossOrganizationConfig$=new O({enabled:!1}),this.crossOrgNotifications$=new O([]),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(Ft,this),this.serviceBook.observe(Bt).subscribe(v=>{this.commentService=v??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(F(v=>!!v),k(1)).subscribe(v=>{if(v){this.db=v;try{let u=this.configService.getProxyConfig(),b=this.endpointsService.getNotificationsDbUrl();Dt(b)?this.notificationsDb=null:(u?.v1DbHost&&b&&(b=Ct(b,u.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance(b),u?.v1DbHost&&b&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(u){this.loggingService.catch("Error initializing notifications DB, using default: ",u),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(u=>{this.notificationsByDocumentIdSubscription[u]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(v=>{if(v){let u=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(v||{}).forEach(b=>{let x=u?.[b]?.notifications;x?.length&&x.forEach(y=>{this.notificationUtilsService.mergeLocationWithNotification({notification:y},v)?.notification})}),this.notificationsByDocumentIdMap$.next(u)}})}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 E(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=z(this.authService.getUser()?.userId??""),o=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:t?.documentId,organizationId:t?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:e}});if(i!==this.settingsConfigGeneration)return;if(o?.notificationsConfig)this.setDBConfigDataToInitialConfig(o?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let s={};this.settingsInitialConfig$.getValue().forEach(r=>{if(r.enable){let a=r?.values?.find(c=>c.id===r.default);s[r.id]=a||r?.values?.[0]||{id:"NONE",name:"None"}}});let n={};Object.keys(s).forEach(r=>{n[r]=s[r].id}),yield this.updateSettingsConfigToDb(n)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=z(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(F(i=>i===!0),I(()=>W([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(F(([i,e,o])=>(e||!!i)&&!!o?.organizationId),I(([i,e,o])=>ct(this.getInitialConfigFromDB(i)).pipe(I(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(N(s=>{s?.data?.notificationsConfig&&!Z(s?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(s?.data?.notificationsConfig)})))))))).subscribe()}catch(t){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",t)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null),this.resetCrossOrgForUser()}catch(t){this.loggingService.catch("Error in NotificationService resetCacheData: ",t)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",t)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(I(()=>this.getCurrentDocumentOnly$().pipe(I(t=>t?this.docService.getDocumentPaths$().pipe(N(i=>{})):C(void 0)))),vt(()=>{this.notificationsByDocumentIdMap$.next(null)}),I(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(lt(),N(([t,i])=>{let e=t?.map(a=>a.documentId),o=i?.map(a=>a.documentId),s=e?.filter(a=>!o?.includes(a)),n=o?.map(a=>({documentId:a,timestamp:i?.find(c=>c.documentId===a)?.timestamp})).filter(a=>!e?.includes(a.documentId)),r=o?.map(a=>{let c=i?.find(l=>l.documentId===a)?.timestamp;return{documentId:a,timestamp:c}}).filter(a=>{let c=t?.find(l=>l.documentId===a.documentId)?.timestamp;return c&&a.timestamp&&c!==a.timestamp});n?.length&&this.fetchNotificationsForDocumentIds(n),r?.length&&this.fetchNotificationsForDocumentIds(r,1),s?.forEach(a=>{this.removeNotificationsForDocumentId(a)}),i&&!i?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}getDocumentIdsByLastNotificationTimestamp(t=15){try{return this.authService.getUser$().pipe(I(i=>this.docService.getOrganizationConfig$().pipe(N(e=>{let o=null,s=this.configService.getApiKey(),n=e?.organizationId||i?.organizationId,r=e?.clientOrganizationId||i?.clientOrganizationId||"";return s&&n&&(o=new mt({apiKey:s,organizationId:n})),{user:i,documentPaths:o,clientOrganizationId:r}}))),I(i=>{let{user:e,documentPaths:o,clientOrganizationId:s}=i;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return C(null);if(e&&o?.organizationNotificationsLastNotificationTimestamp){let n=new Date,r=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;n.setDate(n.getDate()-r);let a=n.getTime(),c=[Yt(ut("timestamp",">=",a),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ut("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];this.getCurrentDocumentOnly()||(c.push(Gt("timestamp","desc")),c.push(_t(t)));let l=e?.userId??"";return ct(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:s})??Promise.resolve({})).pipe(I(g=>l&&s&&g?.[l]?.organization?.[s]?.errorCode===bt.PERMISSION_DENIED?C(null):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:o?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:c}}).pipe(N(f=>f?.data),N(f=>{let d=[];return Object.keys(f||{}).forEach(h=>{let p=this.commonDbService.shouldUseFirestore()?f[h]?.timestamp??0:f[h],$=this.commonDbService.shouldUseFirestore()?f[h]?.deletedNotification??!1:!1;if($&&$.id&&$?.timestamp===p){let M=$.id,S=f[h]?.metadata?.documentId,U=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),R=U?.[S]??{documentMetadata:null,notifications:[]},w=R.notifications??[],v=w?.findIndex(u=>u.id===M);v!==-1&&(w.splice(v,1),this.notificationsByDocumentIdMap$.next(T(D({},U),{[S]:T(D({},R),{notifications:w})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(M)&&this.notificationResolverService.deleteNotification(M,this.docService.getDocumentPaths()?.clientOrganizationId??"")}d.push({documentId:h,timestamp:p})}),d}),V(f=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",f),C([]))))))}return C(null)}))}catch(i){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",i),C([])}}resolveAndUpdateDocumentNotifications(t,i){try{Object.keys(t).forEach(e=>{let o=t[e]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[e]||{},s;if(i==="user")s=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[e]?.notifications||[]});else if(i==="notification"){let n=t[e]?.notifications?.reduce((a,c)=>(a[c.notificationId]=c,a),{}),r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:n});s=Object.values(r??{})}else{let n=t[e]?.notifications?.reduce((a,c)=>(a[c.notificationId]=c,a),{}),r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:n});s=Object.values(r??{})}s.forEach(n=>{n.notification=this.getClientNotificationObject(n)}),this.setNotificationForDocumentIdInCache(e,o,s)})}catch(e){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",e)}}resolveAndMergeUserNotifications(t,i,e=!1){try{let o=t;if(e&&i==="comment"){let c=this.getUserNotificationsFromServer()??[],l=new Set(t.map(g=>g.notificationId));o=c.filter(g=>l.has(g.notificationId)).concat(t.filter(g=>!c.some(f=>f.notificationId===g.notificationId)))}let s=o.reduce((c,l)=>(c[l.notificationId]=l,c),{}),n;if(i==="user"){let c=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}else if(i==="notification"){let c=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}else{let c=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s});n=Object.values(c??{})}n.forEach(c=>{c.notification=this.getClientNotificationObject(c)});let r=this.getUserNotificationsFromServer()??[],a=new Map(r.map(c=>[c.notificationId,c]));n.forEach(c=>{a.set(c.notificationId,c)}),this.setUserNotificationsFromServer(Array.from(a.values()))}catch(o){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",o)}}fetchNotificationsForDocumentIds(t,i=15){return E(this,null,function*(){try{if(t?.length){let e=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),o=this.docService.getOrganizationConfig()?.organizationId??"";if(!o)return[];let s=this.getStartAtTimestamp(),n={};if(t.forEach(S=>{if(S?.documentId){let U=this.getAllowedDocumentMetadataByDocumentId(S.documentId);U&&(n[S.documentId]=U)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let S=[];if(t.forEach(u=>{this.docService.getDocumentMetadata(u.documentId)||S.push(u.documentId)}),S.length){let u=this.authService.getUser(),b=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let x=yield ht({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:u?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:S},getSdkProxy:b,userId:u?.userId??""});if(x?.data?.length){let y={};x.data.forEach(H=>{H?.documentId&&(y[H.documentId]=H)}),this.docService.setAllDocumentMetadata(D(D({},this.docService.getAllDocumentMetadataMap()),y))}}catch(x){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",x)}}let U=[],R=[];t.forEach(u=>{let b=this.docService.getDocumentMetadata(u.documentId);b?.clientDocumentId?U.push({userId:this.authService.getUser()?.userId??"",resource:{id:b.clientDocumentId,type:Q.DOCUMENT,source:q.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""}}):R.push(u.documentId)}),R.length&&(t=t.filter(u=>!R.includes(u.documentId)));let w=$t();this.coreActionsService.triggerAction(Ot.PERMISSION_PROVIDER,{event:L.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:w,methodName:q.GET_NOTIFICATIONS,source:"internal",payload:{requests:U}});let v=yield this.userPermissionService?.onResourceAccessRequired({requests:U,uniqueId:w,methodName:q.GET_NOTIFICATIONS});v?.success&&v?.data?.length?v.data.forEach(u=>{!u.hasAccess&&u.resourceId&&(t=t.filter(b=>b.documentId!==At(u.resourceId)))}):t=[]}catch(S){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",S),t=[]}if(!t.length)return this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),[];let r=this.userPermissionService?.getPermissionsCache()?.filter(S=>S.type===Q.CONTEXT),a={organizationId:o,documentIds:t.filter(S=>!!S.documentId&&!!S.timestamp).map(S=>({documentId:S.documentId,timestamp:S.timestamp??0})),timestamp:s,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:r,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},c=yield this.notificationUtilsService.handleNotificationEncryption({data:a}),l=yield e({veltData:c}),g=l?.data?.data?.veltData||{},f=l?.data?.data?.veltAdditionalData||{},d="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),h=yield dt(g,d),{userNotifications:p=[],userNotificationIdsInDocNotifications:$=[],permissionResults:M=[]}=yield dt(f,d);if(this.userPermissionService?.getIsContextEnabled()){let S=[...this.userPermissionService?.getPermissionsCache()??[],...M??[]];this.userPermissionService?.setPermissionsCache(S)}if(h&&typeof h=="object"){let S=this.usersService.userDataProviderAvailable(),U=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),R=this.notificationResolverService.notificationDataProviderAvailable(),w=[],v=[],u=[];Object.keys(h).forEach((y,H)=>{let _=h[y].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[y];if(_){let B=this.allowedDocumentMetadataMap$.value||{};(!B?.[y]||!Z(B?.[y],_))&&this.allowedDocumentMetadataMap$.next(T(D({},B),{[y]:_}))}let Y=h[y].notifications||[];Y.forEach(B=>{$.includes(B.notificationId)&&!p.find(ti=>ti.notificationId===B.notificationId)&&p.push(JSON.parse(JSON.stringify(B))),B.notification=this.getClientNotificationObject(B)}),this.setNotificationForDocumentIdInCache(y,_,Y),S&&(w.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Y,shouldAwait:!0,forceResolve:!0})),w.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldAwait:!0,forceResolve:!0}))),U&&(v.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Y,shouldCommentAnnotationsResolverAwait:!0})),v.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldCommentAnnotationsResolverAwait:!0}))),R&&(u.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:Y,shouldNotificationResolverAwait:!0})),u.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:p,shouldNotificationResolverAwait:!0})))});let b=JSON.parse(JSON.stringify(p));this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...p]),(R||S||U)&&(()=>{let y=Promise.resolve();if(R&&(y=y.then(()=>Promise.allSettled(u)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"notification"),this.resolveAndMergeUserNotifications(b,"notification")})),S&&(y=y.then(()=>Promise.allSettled(w)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"user"),this.resolveAndMergeUserNotifications(b,"user")})),U){let H=R||S;y=y.then(()=>Promise.allSettled(v)).then(()=>{this.resolveAndUpdateDocumentNotifications(h,"comment"),this.resolveAndMergeUserNotifications(b,"comment",H)})}return y})().catch(y=>{this.loggingService.catch("Error in NotificationService resolveChain: ",y)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,s)=>o===s.findIndex(n=>n.notificationId===e.notificationId)),this.userNotificationsFromServer$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",i)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(t,i,e,o){try{let s=this.docService.getOrganizationConfig()?.organizationId??"",n=this.docService.getOrganizationMetadata(s);i||(i=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),n||(n=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(s)||{})));let r=this.notificationsByDocumentIdMap$.getValue(),a=r?.[t]?.notifications||[],c=this.docService.getLocationMetadatas(),l=e?.map(d=>{let h=d?.notification;return h?(h.metadata&&(h.metadata.documentName=i?.documentName||h.metadata.documentName,h.metadata.organizationMetadata=n||h.metadata.organizationMetadata,h.metadata.documentMetadata=i||h.metadata.documentMetadata),c&&(h=this.notificationUtilsService.mergeLocationWithNotification({notification:h},c)?.notification),h):null})?.filter(d=>!!d)||[],g=new Map(a.map(d=>[d.id,d]));l.forEach(d=>{g.set(d.id,d)});let f=Array.from(g.values()).sort((d,h)=>(h.timestamp||0)-(d.timestamp||0));this.notificationsByDocumentIdMap$.next(T(D({},r),{[t]:{notifications:f,documentMetadata:i}}))}catch(s){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",s)}}removeNotificationsForDocumentId(t){try{this.notificationsByDocumentIdSubscription[t]&&this.notificationsByDocumentIdSubscription[t].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[t],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getStartAtTimestamp(){try{let t=new Date,i=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return t.setDate(t.getDate()-i),t.getTime()}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(I(t=>C(t).pipe(F(i=>!!i),N(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),s=this.notificationResolverService?.notificationDataProviderAvailable();if(s||e||o){let r=i?.reduce((a,c)=>(a[c.notificationId]=c,a),{});s&&(r=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:r||[]})),e&&(r=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:r||[]})),o&&(r=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:r||[]})),i=Object.values(r??{})}return i.forEach(r=>{r.notification=this.getClientNotificationObject(r)}),i.sort((r,a)=>a.timestamp-r.timestamp),i.map(r=>r.notification).filter(r=>!!r)}),I(i=>{let e={data:i?.reduce((o,s)=>(o[s.id]={notification:s},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(N(o=>Object.values(o?.data||{}).map(s=>s?.notification)))}))),I(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(N(()=>t))}),I(t=>this.allowedDocumentMetadataMap$.pipe(N(()=>t))),N(t=>(t?.length&&(t=t.map(i=>{if(i?.metadata){let e=this.docService.getOrganizationConfig()?.organizationId??"",o=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),s=this.docService.getOrganizationMetadata(e);o||(o=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),s||(s=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=s||i.metadata.organizationMetadata,i.metadata.documentMetadata=o||i.metadata.documentMetadata}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),C(null)}}getNotificationsForYou(){try{return W([this.getCurrentOrgNotificationsForYou(),this.crossOrgNotifications$.asObservable()]).pipe(N(([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:[],s=a=>a?.id??a?.notificationId,n=new Set;o.forEach(a=>{let c=s(a);c!=null&&n.add(c)});let r=[...o];return e.forEach(a=>{let c=s(a);c!=null&&n.has(c)||(c!=null&&n.add(c),r.push(a))}),r.sort((a,c)=>(c?.timestamp||0)-(a?.timestamp||0))}catch(e){return this.loggingService.catch("Error in NotificationService mergeCrossOrgForYou: ",e),t}}enableCrossOrganization(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableCrossOrganization();return}this.setCrossOrganizationConfig(T(D({},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(T(D({},t||{}),{enabled:!1}))}catch(t){this.loggingService.catch("Error in NotificationService disableCrossOrganization: ",t)}}setCrossOrganizationConfig(t){try{let i=t||{},e=Array.isArray(i.feeds)&&i.feeds.length?i.feeds:["forYou"];e.includes("all")&&this.loggingService.warn('NotificationService: cross-organization notifications only support the "forYou" feed; ignoring "all".'),e=e.filter(s=>s==="forYou"),e.length||(e=["forYou"]);let o={enabled:i.enabled??!0,organizationIds:i.organizationIds,excludeOrganizationIds:i.excludeOrganizationIds,feeds:e};this.crossOrganizationConfig$.next(o)}catch(i){this.loggingService.catch("Error in NotificationService setCrossOrganizationConfig: ",i)}}getCrossOrganizationConfig(){return this.crossOrganizationConfig$.getValue()}getCrossOrganizationConfig$(){return this.crossOrganizationConfig$.asObservable()}attachCrossOrgIndexListener(){try{this.teardownCrossOrgUserWatcher(),this.crossOrgUserSubscription=this.authService.getUser$().pipe(N(t=>t?.userId),J(),F(t=>!!t),V(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),G))).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:z(t),isCollection:!1,useCollectionGroup:!1}}).pipe(V(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),G))).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(N(i=>i?.organizationId??""),J(),lt(),F(([i])=>!!i),V(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),G))).subscribe(()=>{this.crossOrgInitialFetchDone=!1,this.crossOrgSeenTimestamps={},this.scheduleCrossOrgFetch()})}extractIndexOrgTimestamps(t){let i={};try{let e=t?.data??t,o=e?.organizationIds??e?.orgs;return Array.isArray(o)?(o.forEach(s=>{typeof s=="string"&&s.length&&(i[s]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(s=>{if(typeof s=="string"&&s.length){let n=Number(o[s]);i[s]=Number.isFinite(n)?n:0}}),i)}catch(e){return this.loggingService.catch("Error in NotificationService extractIndexOrgTimestamps: ",e),i}}scheduleCrossOrgFetch(){try{let t=Date.now();t-this.lastCrossOrgFetchTime>=this.CROSS_ORG_FETCH_WINDOW_MS?(this.lastCrossOrgFetchTime=t,this.crossOrgFetchPending=!1,this.fetchCrossOrgUserNotifications(),this.armCrossOrgTrailingTimer()):this.crossOrgFetchPending=!0}catch(t){this.loggingService.catch("Error in NotificationService scheduleCrossOrgFetch: ",t)}}pruneCrossOrgBufferToAllowedOrgs(){try{let t=this.crossOrgNotifications$.getValue();if(!t.length)return;let i=this.crossOrgIndexOrgs||[];if(!i.length){this.crossOrgNotifications$.next([]);return}let e=t.filter(o=>i.includes(o?.metadata?.organizationId));e.length!==t.length&&this.crossOrgNotifications$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService pruneCrossOrgBufferToAllowedOrgs: ",t)}}armCrossOrgTrailingTimer(){this.crossOrgFetchTimer&&clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=setTimeout(()=>{this.crossOrgFetchPending&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())},this.CROSS_ORG_FETCH_WINDOW_MS)}toCrossOrgClientNotification(t){try{if(!t)return null;if(t.notification){let e=this.getClientNotificationObject(t);if(!e)return null;let o=t?.metadata?.organizationId??e?.metadata?.organizationId;return o!=null&&(e.metadata=T(D({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:T(D({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return E(this,null,function*(){try{if(!t?.length)return t;let i=!!this.notificationResolverService?.notificationDataProviderAvailable?.(),e=!!this.usersService?.userDataProviderAvailable?.(),o=!!this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable?.();if(!i&&!e&&!o)return t;let s=new Map;for(let r of t){let a=r?.metadata?.clientOrganizationId??r?.metadata?.organizationId??"",c=s.get(a);c?c.push(r):s.set(a,[r])}let n=[];for(let[r,a]of s){let c=a.reduce((g,f,d)=>{let h=f?.notificationId??f?.id??`__cross_org_${d}`;return g[h]=f,g},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:c,organizationId:r||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let l=c;i&&(l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l??{}})),e&&(l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l??{}})),o&&(l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l??{}})),n.push(...Object.values(l??{}))}return n}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return E(this,null,function*(){let t=this.crossOrgGeneration;if(this.crossOrgResolveRoundInFlight){this.crossOrgFetchPending=!0;return}this.crossOrgResolveRoundInFlight=!0;try{let i=this.crossOrganizationConfig$.getValue(),e=this.docService.getOrganizationConfig()?.organizationId??"",o=!this.crossOrgInitialFetchDone,s=this.crossOrgIndexTimestamps||{},n=o?[]:Object.keys(s).filter(f=>f!==e&&(s[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!n.length)return;let r=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:n}),a=yield this.callGetCrossOrgUserNotifications(r);if(t!==this.crossOrgGeneration)return;let c=Array.isArray(a?.pendingPermissionQueries)?a.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),g=!c.length||!l;if(yield this.processCrossOrgResponse(a,{fetchGeneration:t,currentOrg:e,isInitial:o,indexTimestamps:s,advanceCursors:g}),t!==this.crossOrgGeneration||g){g&&t===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry();return}yield this.runCrossOrgResolveRound(c,{fetchGeneration:t,config:i,currentOrg:e,isInitial:o,bumpedOrgs:n,indexTimestamps:s})}catch(i){this.loggingService.catch("Error in NotificationService fetchCrossOrgUserNotifications: ",i)}finally{this.crossOrgResolveRoundInFlight=!1,this.crossOrgFetchPending&&t===this.crossOrgGeneration&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())}})}runCrossOrgResolveRound(t,i){return E(this,null,function*(){try{let e=yield this.userPermissionService.resolveClientSidePermissions(t);if(i.fetchGeneration!==this.crossOrgGeneration)return;let o=this.buildCrossOrgRequestData(i.config,i.currentOrg,{isInitial:i.isInitial,bumpedOrgs:i.bumpedOrgs});o.clientResolvedResults=e;let s=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(s,{fetchGeneration:i.fetchGeneration,currentOrg:i.currentOrg,isInitial:i.isInitial,indexTimestamps:i.indexTimestamps,advanceCursors:!0}),i.fetchGeneration===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry()}catch(e){this.loggingService.catch("Error in NotificationService runCrossOrgResolveRound: ",e),this.armCrossOrgStragglerRetry(i.fetchGeneration)}})}processCrossOrgResponse(t,i){return E(this,null,function*(){if(this.userPermissionService?.getIsContextEnabled?.()&&t?.permissionResults?.length){let l=[...this.userPermissionService?.getPermissionsCache?.()??[],...t.permissionResults];this.userPermissionService?.setPermissionsCache?.(l)}let e=Array.isArray(t?.forYou)?t.forYou:[],o=this.crossOrgIndexOrgs||[],s=l=>o.includes(l),n=e.filter(l=>{let g=l?.metadata?.organizationId;if(g===i.currentOrg)return this.loggingService.log("%c[WB] Cross-org: dropping current-org echo: "+g,"color: orange;"),!1;let f=s(g);return f||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),f}),r=yield this.resolveCrossOrgSelfHostedData(n);if(i.fetchGeneration!==this.crossOrgGeneration)return;let a=r.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=a:c=this.mergeCrossOrgForYou(a,this.crossOrgNotifications$.getValue()).filter(l=>s(l?.metadata?.organizationId)),i.advanceCursors&&(Object.keys(i.indexTimestamps).forEach(l=>{this.crossOrgSeenTimestamps[l]=i.indexTimestamps[l]}),this.crossOrgInitialFetchDone=!0),this.crossOrgNotifications$.next(c)})}armCrossOrgStragglerRetry(t){this.crossOrgStragglerRetryUsed||(this.crossOrgStragglerRetryUsed=!0,this.crossOrgStragglerRetryTimer&&clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=setTimeout(()=>{this.crossOrgStragglerRetryTimer=void 0,t===this.crossOrgGeneration&&this.fetchCrossOrgUserNotifications()},this.CROSS_ORG_STRAGGLER_RETRY_MS))}clearCrossOrgStragglerRetry(){this.crossOrgStragglerRetryUsed=!1,this.crossOrgStragglerRetryTimer&&(clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=void 0)}callGetCrossOrgUserNotifications(t){return E(this,null,function*(){let i=this.authService.getUser(),e=tt(this.functions,X({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ht({methodName:"getCrossOrgUserNotifications",data:D({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},s=e?.isInitial??!0,n=e?.bumpedOrgs??[],r=Array.isArray(o.organizationIds),a=r?o.organizationIds.filter(d=>!!d).map(d=>ft(d)):[],c=(o.excludeOrganizationIds||[]).filter(d=>!!d).map(d=>ft(d)),l=new Set(c);i&&l.add(i);let g=this.userPermissionService?.getPermissionsCache?.()?.filter(d=>d?.type===Q.CONTEXT),f={organizationId:i,excludeOrganizationIds:Array.from(l),timestamp:this.getStartAtTimestamp(),limitToLast:this.CROSS_ORG_PAGE_SIZE,isContextEnabled:this.userPermissionService?.getIsContextEnabled?.(),cachedData:g,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig?.()};if(this.userPermissionService?.isClientDevResolverActive?.()&&(f.clientResolverAvailable=!0),s)r&&(f.organizationIds=this.dedupeIncludeOrgs(a,l));else{let d=n.filter(p=>!!p&&!l.has(p));if(r){let p=new Set(a);d=d.filter($=>p.has($))}d=Array.from(new Set(d)),f.organizationIds=d;let h={};d.forEach(p=>{h[p]=this.crossOrgSeenTimestamps[p]??this.getStartAtTimestamp()}),f.orgTimestamps=h}return f}dedupeIncludeOrgs(t,i){let e=new Set;return t.filter(o=>o==null||i.has(o)||e.has(o)?!1:(e.add(o),!0))}teardownCrossOrgPerUserListeners(){this.crossOrgGeneration++,this.crossOrgIndexSubscription&&(this.crossOrgIndexSubscription.unsubscribe(),this.crossOrgIndexSubscription=void 0),this.crossOrgOrgSwitchSubscription&&(this.crossOrgOrgSwitchSubscription.unsubscribe(),this.crossOrgOrgSwitchSubscription=void 0),this.crossOrgFetchTimer&&(clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=void 0),this.crossOrgFetchPending=!1,this.clearCrossOrgStragglerRetry()}teardownCrossOrgUserWatcher(){this.teardownCrossOrgPerUserListeners(),this.crossOrgUserSubscription&&(this.crossOrgUserSubscription.unsubscribe(),this.crossOrgUserSubscription=void 0)}resetCrossOrgDeltaState(){this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1}resetCrossOrgForUser(){this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.getValue().length&&this.crossOrgNotifications$.next([])}teardownCrossOrg(){this.teardownCrossOrgUserWatcher(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([])}markCrossOrgEntriesRead(t){try{let i=this.crossOrgNotifications$.getValue();if(!i?.length)return;let e=new Set((t||[]).map(r=>r?.id??r?.notificationId).filter(r=>r!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),s=!1,n=o?i.filter(r=>{let a=r?.id??r?.notificationId,c=a!=null&&e.has(a);return c&&(s=!0),!c}):i.map(r=>{let a=r?.id??r?.notificationId;return a!=null&&e.has(a)&&r?.isUnread!==!1?(s=!0,T(D({},r),{isUnread:!1})):r});s&&this.crossOrgNotifications$.next(n)}catch(i){this.loggingService.catch("Error in NotificationService markCrossOrgEntriesRead: ",i)}}subscribeNotificationsData(t,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let e,o;try{if(t&&(o=gt(t)),i&&typeof i=="object"){let s=Rt(i);e=gt(JSON.stringify(s))}}catch(s){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",s)}return this.authService.getAuthState$().pipe(F(s=>!!s),I(s=>this.isFeatureAllowed({firebaseUser:s})),I(s=>s.featureAllowed?this.iamService.isUserAllowed$().pipe(N(n=>(s.featureAllowed=n,s))):C(s)),I(s=>!s.featureAllowed||s?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),C([])):C(s).pipe(I(n=>this.docService.getDocumentPaths$().pipe(N(r=>(this.documentPaths=r,n.documentPaths=r,n)))),I(n=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(F(i=>!!i),N(i=>T(D({},t),{config:i})),I(i=>this.authService.getUser$().pipe(N(e=>T(D({},i),{user:e})))),I(i=>Et(i.config,i.user,yt.NOTIFICATION)?C(T(D({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),C(T(D({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(F(i=>!!i),I(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let e=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(e+=`/${P.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let o=this.realtimeAdapter.rtdbRef(this.db,`${t?e+"/"+P.FIREBASE_PARTIAL_PATH_DOCS+"/"+t+"/"+P.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return this.realtimeAdapter.rtdbObjectVal$("notification",o).pipe(V(s=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",s),C(null))),N(s=>{let n=[],r=new Map;s?.raw&&(Object.keys(s?.raw||{}).forEach(c=>{let l=s?.raw[c];l?.id&&n.push(l)}),n.forEach(c=>{c.id&&r.set(c.id,c)})),this.notifications$.next(n),this.rawNotificationsByIdMap$.next(r);let a=[];s?.processed&&Object.keys(s?.processed||{}).forEach(c=>{let l=s?.processed[c];l?.id&&a.push(l)}),this.processedNotifications$.next(a),this.setNotificationsByIdMap()}))}else return C(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=z(t?.email));let o;t?.userId&&(o=z(t?.userId));let s=new Map;this.processedNotifications$.getValue().forEach(r=>{if(r.id&&r?.displayHeadlineMessageTemplate){let a=!1;(e&&r.notifyUsers?.[e]||o&&r.notifyUsers?.[o])&&(a=!0);let c={id:r.id,notificationSource:r.notificationSource,actionType:r.actionType,actionUser:r.actionUser,timestamp:r.timestamp,targetAnnotationId:r.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),forYou:a,notificationSourceData:r.notificationSourceData},l=this.getRawNotificationById(c.id);if(l?.metadata&&(c.metadata={apiKey:l.metadata.apiKey,organizationId:l.metadata.organizationId,clientOrganizationId:l.metadata.clientOrganizationId,documentId:l.metadata.documentId,clientDocumentId:l.metadata.clientDocumentId,location:l?.location,locationId:l?.locationId}),c?.notificationSource==="comment"&&c?.targetAnnotationId){let g=this.commentService?.getAnnotationById(c.targetAnnotationId);g||l?.annotationData&&(g=l.annotationData),g&&(c.notificationSourceData=this.commentService?.getCommentAnnotationForClient(g))}s.set(r.id,c)}}),s.forEach((r,a)=>{r.isUnread=r?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[a]?.views?.[t?.userSnippylyId],s.set(a,r)}),this.notificationsByIdMap$.next(s)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:s}){try{let n=this.authService.getUser(),r=s||t;if(r.id&&r?.displayHeadlineMessageTemplate&&n){let a=null;n?.email&&(a=z(n?.email));let c=null;n?.userId&&(c=z(n?.userId));let l=!1,g=!0;(a&&r.notifyUsers?.[a]||c&&r.notifyUsersByUserId?.[c])&&(l=!0),c&&o?.[c]&&(g=!1);let f={id:r.id};if(s?f=T(D(D({},f),s),{displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:l,isUnread:g}):f={id:t.id,notificationSource:t.notificationSource,actionType:t.actionType,actionUser:t.actionUser,timestamp:t.timestamp,targetAnnotationId:t.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(t),displayBodyMessage:this.getNotificationBodyMessage(t),forYou:l,isUnread:g,metadata:e},f?.notificationSource==="comment"&&f?.targetAnnotationId){let d=this.commentService?.getAnnotationById(f.targetAnnotationId);d||s?.notificationSourceData&&(d=s?.notificationSourceData),d||i?.annotationData&&(d=i.annotationData),d&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(d))}return i?.targetAnnotationData?.isCommentResolverUsed&&(f.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),s?.isNotificationResolverUsed&&(f.isNotificationResolverUsed=s.isNotificationResolverUsed),f}return}catch(n){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",n);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(N(t=>t?Object.keys(t??{}).map(i=>{let e=t[i].notifications||[],o=e.filter(n=>n.isUnread).length,s=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:s,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return W([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable()]).pipe(N(([t,i])=>{let e=Array.isArray(i)?i:[],o=null;return t&&(o=[],t.forEach(s=>{s.notifications.forEach(n=>{o?.push(n)})})),e.length?t?this.mergeCrossOrgForYou(o||[],e):null:t?o.sort((s,n)=>n.timestamp-s.timestamp):null}))}processNotificationData(t){try{let i=t?.annotationData?.metadata,e=this.docService.getOrganizationConfig()?.organizationId;t.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t.metadata||(t.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete t.metadata.locations,t.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t?.metadata?.documentMetadata?.clientDocumentId&&t?.metadata?.documentMetadata?.documentId&&(t.metadata.documentMetadata.documentId=t?.metadata?.documentMetadata?.clientDocumentId),delete t.metadata.documentMetadata.locations,t.metadata.organizationMetadata=JSON.parse(JSON.stringify(e?this.docService.getOrganizationMetadata(e)||{}:{})),t?.metadata?.organizationMetadata?.clientOrganizationId&&t?.metadata?.organizationMetadata?.organizationId&&(t.metadata.organizationMetadata.organizationId=t?.metadata?.organizationMetadata?.clientOrganizationId);let o=this.configService.getApiKey();t.metadata.apiKey=o,t.platform=this.configService.getSF()?"sf":"sdk",t.actionUser=this.authService.getUser();let s=i?.documentId?new mt({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=s?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=s?.clientOrganizationId||t.actionUser.clientOrganizationId);let n=this.docService.getLocation();n&&(t.location=n?.location,t.locationId=n?.locationId),this.loggingService.log(`[NOTIFICATION] ${t?.notificationSource} ${t?.actionType}`,t);let r=this.commonDbService.getServerTimestamp(),a=this.notificationUtilsService.formatNotification(t,r);return JSON.parse(JSON.stringify(a))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}updateNotificationDatabase(t){try{if(!this.notificationsDb)return;let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=this.processNotificationData(t);try{let o=Ut(t?.annotationData);if(o&&e&&typeof e=="object"){e.visibility=o;let s=Object.values(t?.annotationData?.subscribedUsers||{}).map(r=>r?.user?.userId).filter(r=>!!r),n=Tt(t?.annotationData,s);n.length&&(e.deniedForYouUsers=[...new Set([...e.deniedForYouUsers??[],...n])])}}catch(o){this.loggingService.catch("Error applying notification visibility in updateNotificationDatabase: ",o)}this.realtimeAdapter.rtdbPush("notificationIndex",i,JSON.parse(JSON.stringify(e)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(t){return this.authService.getUser$().pipe(I(i=>i?i.organizationId?this.getAllNotifications$().pipe(I(e=>this.notificationsForYou$.pipe(N(o=>{if(e||o){let s=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(n=>{n.id&&s.set(n.id,n)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(n=>{n.id&&!s.has(n.id)&&s.set(n.id,n)}),Array.from(s.values()).sort((n,r)=>(r.timestamp||0)-(n.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(N(e=>Array.from(e.values())),N(e=>e.sort((o,s)=>s.timestamp-o.timestamp)),St()):C(null)),J(Mt))}getRawNotificationById(t){try{return this.rawNotificationsByIdMap$.getValue()?.get(t)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(t){try{this.notificationViews$.next(t),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(t){try{let i=this.authService.getUser();if(t?.displayHeadlineMessageTemplate&&t?.displayHeadlineMessageTemplateData){let e=t.displayHeadlineMessageTemplate,o=t.displayHeadlineMessageTemplateData,s=/\{(\w+)\}/g,n=e.replace(s,(r,a)=>(a==="actionUser"||a==="recipientUser")&&o[a]?i?.email&&o[a].email===i?.email||i?.userId&&o[a]?.userId===i?.userId?"You":o[a].name||o[a].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':o[a]?o[a]:r);return this.domService.sanitizeHtml(n)}return this.domService.sanitizeHtml(t.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(t){try{if(t?.displayBodyMessageTemplate&&t?.displayBodyMessageTemplateData){let i=t?.displayBodyMessageTemplate;return t?.displayBodyMessageTemplateData&&t?.displayBodyMessageTemplateData?.users?.forEach(e=>{if(e?.userId){let o=this.usersService.getUserById(e?.userId);i=i?.replaceAll(`{{${e.userId}}}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),i=i?.replaceAll(`@User ${e.userId}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(t.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(t,i=!1,e=!1){try{t?document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(t):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(t),t?this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.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(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(L.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(t){return E(this,null,function*(){try{let i=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(t?.length){for(let n=0;n<t.length;n+=50){let a=t.slice(n,n+50).filter(g=>g?.id),c=a.map(g=>this.setNotificationAsRead({notification:g,userNotifications:JSON.parse(JSON.stringify(i))})),l=yield Promise.all(c);a.forEach((g,f)=>{let d=l[f];if(!d.some(p=>p.notificationId===g.id))i=i.filter(p=>p.notificationId!==g.id);else{let p=i.find(M=>M.notificationId===g.id),$=d.find(M=>M.notificationId===g.id);p&&$?.views&&(p.views=$.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(n=>{let r=n.metadata?.documentId;if(r&&o?.[r]){let a=o?.[r]?.notifications||[],c=a.find(l=>l.id===n.id);c&&(c.isUnread=!1),o[r].notifications=a}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!Z(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return E(this,null,function*(){try{if(t?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(k(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(N(t=>t?.filter(e=>e?.isUnread)?.length??null),I(t=>this.getNotifications$().pipe(N(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 E(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let s=z(o?.userId),{metadata:n}=t;if(n){let{apiKey:r,organizationId:a,documentId:c}=n;if(r&&a&&c&&s){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:a,documentId:c,apiKey:r}});l?.notificationId&&(l?.views?.[s]||(l.views||(l.views={}),l.views[s]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:a,documentId:c,apiKey:r},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:a}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:s,documentId:c,organizationId:a}}),i=i.filter(f=>f.notificationId!==t.id);else if(!g?.views?.[s]){g.views||(g.views={}),g.views[s]={timestamp:Date.now()};let f=i.find(d=>d.notificationId===t.id);f&&(f.views=g.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:t.id,userId:s,documentId:c,organizationId:a},data:g})}}}}}return i}catch(o){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",o),i}})}setMaxDays(t){try{t>0?this.maxNotificationDays$.next(t):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(t){try{t&&this.tabConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",t)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",t)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(t){return E(this,null,function*(){try{this.getNotifications$().pipe(k(1)).subscribe(i=>{if(i){let e=i.filter(o=>o.id===t);this.setNotificationsAsRead(e)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getAllowedDocumentMetadataByDocumentId(t){try{return this.allowedDocumentMetadataMap$.value?.[t]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(t){try{this.enableSettings$.value&&this.settingsConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(t){try{this.enableSettings$.value&&(this.settingsConfig$.next(t),this.updateSettingsConfigToDb())}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",t)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettings: ",t)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",t)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",t)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",t)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",t)}}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 E(this,null,function*(){try{let i=this.authService.getUser(),e=z(i?.userId??""),o=this.docService.getDocumentPaths(),s=this.docService.getOrganizationConfig(),n=o?.organizationId??s?.organizationId,r=o?.clientOrganizationId??s?.clientOrganizationId,a={apiKey:this.configService.getApiKey(),organizationId:n,documentId:o?.documentId,clientOrganizationId:r,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:r??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:o?.documentId,userId:e},data:{id:o?.documentId,notificationsConfig:t||this.settingsConfig$.getValue(),metadata:a}})))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",t)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",t)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};A.\u0275fac=function(i){return new(i||A)(m(Nt),m(xt),m(ot),m(jt),m(qt),m(Jt),m(nt),m(st),m(at),m(Wt),m(kt),m(Lt),m(Qt),m(et),m(Xt),m(rt),m(It),m(Zt),m(Vt),m(it),m(Kt))},A.\u0275prov=K({token:A,factory:A.\u0275fac,providedIn:"root"});let j=A;return j})();export{Xt as a,ji as b};
|
package/chunk-PRGWBNVO.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{ca as ie}from"./chunk-CVMNWHT4.js";import{$ as K,$e as R,Cf as $,Ch as E,Df as _,Dh as V,Ee as N,Ef as A,Ff as T,Fi as Q,Gi as ee,Hi as re,L as w,Mf as L,Od as W,Pi as se,Vf as M,_e as U,a as f,af as I,b as y,be as v,ca as P,da as x,g,ki as X,l as D,li as q,oi as H,qh as b,qi as Y,tf as S,th as j,ti as Z,uf as l,uh as B,v as G,wh as J,xh as z,zh as F}from"./chunk-FXK7BWOQ.js";var p="public",ye=(()=>{let O=class O{constructor(e,r,s,i,t,o,c,a,n,d){this.authService=e,this.docService=r,this.loggingService=s,this.commonDbService=i,this.usersService=t,this.commentUtilsService=o,this.coreActionsService=c,this.functions=a,this.configService=n,this.contactService=d,this.endpointsService=x(H),this.currentUserPermissions$=new D(null),this.permissionsCache$=new D(null),this.permissionProvider$=new D(null),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.requestKeyedPermissionsCache=new Map,this.inFlightPermissionsRequests=new Map,this.permissionsCacheGeneration=0,this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="";try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(h){this.loggingService.catch("Error in UserPermissionService constructor:",h)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,r,s,i,t,o){try{return e.find(a=>a.resourceId===s&&a.type===i&&a.organizationId===t&&a.userId===o)?(r.push({userId:o,resourceId:s,organizationId:t,type:i,hasAccess:!1}),e.filter(a=>!(a.resourceId===s&&a.type===i&&a.organizationId===t&&a.userId===o))):e}catch(c){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",c),e}}hasUserContextAccess({userId:e,accessFields:r}){try{if(!this.getIsContextEnabled()||r.includes(N.DEFAULT_VELT_CONTEXT))return!0;let s=r.filter(t=>!L(t));if(!s.length){if(r.some(c=>c.startsWith(N.VISIBILITY_ORG_PREFIX)))return!0;let o=`${N.VISIBILITY_SELF_PREFIX}${$(e).toString()}`;return r.includes(o)}let i=this.contactService.getUserAccessFieldsByUserId(e);return i?s.every(t=>i.includes(t)):!0}catch(s){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",s),!1}}organizationDetails(e){return g(this,null,function*(){try{let r=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e,suppressError:!0}});return r&&r?.errorCode?{errorCode:l.PERMISSION_DENIED,error:!0}:r&&!r?.metadata?{errorCode:l.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(r){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",r),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(s){return g(this,arguments,function*({documentId:e,organizationId:r}){try{let i=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:r,suppressError:!0}});if(i&&i?.errorCode)return{errorCode:l.PERMISSION_DENIED,error:!0};if(i&&!i?.metadata)return{errorCode:l.DOES_NOT_EXIST,error:!0};let t=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,f(f({},t),i?.metadata??{}));let o,c=i?.metadata?.veltFolderId;if(c)try{o=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:c,organizationId:r}}))?.folderIamConfig?.accessType}catch(a){this.loggingService.catch("Error fetching folder accessType for document:",a)}return o||(o=i?.docIamConfig?.accessType),{error:!1,accessType:o}}catch(i){return this.loggingService.catch("Error in UserPermissionService documentDetails:",i),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(s){return g(this,arguments,function*({folderId:e,organizationId:r}){try{let i=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:r,suppressError:!0}});return i&&i?.errorCode?{errorCode:l.PERMISSION_DENIED,error:!0}:i&&!i?.metadata?{errorCode:l.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:i?.folderIamConfig?.accessType}}catch(i){return this.loggingService.catch("Error in UserPermissionService folderDetails:",i),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return g(this,null,function*(){let r=this.permissionsCacheGeneration;try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let s=this.authService.getUser()?.userId,i=this.extractResourceIds(e);if(!i.clientOrganizationId||!i.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let t=yield this.validateResources(i),[o,c]=yield this.fetchUserPermissionsFromDB(i),a=this.authService.getUser()?.userId;if(s!==a)return{};let n=this.buildPermissionsResponse(i,t,o,c);if(Object.keys(n).length>0){if(!e)this.setCurrentUserPermissions(n);else if(this.permissionsCacheGeneration===r){let d=this.buildPermissionsCacheKey(e);d!==null&&this.requestKeyedPermissionsCache.set(d,JSON.parse(JSON.stringify(n)))}}return n}catch(s){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",s),{}}})}getUserPermissionsFromCacheOrFetch(e){return g(this,null,function*(){try{if(!e)return yield this.getUserPermissions(e);let r=this.buildPermissionsCacheKey(e);if(r===null)return yield this.getUserPermissions(e);let s=this.permissionsCacheGeneration,i=this.requestKeyedPermissionsCache.get(r);if(i)return JSON.parse(JSON.stringify(i));let t=this.inFlightPermissionsRequests.get(r);if(t){let a=yield t;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(a))}let o=this.getUserPermissions(e);this.inFlightPermissionsRequests.set(r,o),o.finally(()=>{this.inFlightPermissionsRequests.get(r)===o&&this.inFlightPermissionsRequests.delete(r)}).catch(()=>{});let c=yield o;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(c))}catch(r){return this.loggingService.catch("Error in UserPermissionService getUserPermissionsFromCacheOrFetch:",r),{}}})}clearRequestKeyedPermissionsCache(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService clearRequestKeyedPermissionsCache:",e)}}invalidateAllPermissionsState(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService invalidateAllPermissionsState:",e)}}buildPermissionsCacheKey(e){try{let r={};return Object.keys(e).sort().forEach(s=>{let i=e[s];i!==void 0&&(r[s]=Array.isArray(i)?[...i].sort():i)}),r.__userId=this.authService.getUser()?.userId??null,JSON.stringify(r)}catch(r){return this.loggingService.catch("Error in UserPermissionService buildPermissionsCacheKey:",r),null}}extractResourceIds(e){let r=this.docService.getDocumentPaths(),s=this.docService.getDocumentIds();if(e){let o=e.organizationId??r?.clientOrganizationId;return{folderIds:e.folderIds??[],documentIds:e.documentIds??[],clientOrganizationId:o,organizationId:o?A(o):void 0}}let i=r?.clientOrganizationId;return{folderIds:r?.folderId?[r.folderId]:[],documentIds:s.map(o=>o.clientDocumentId),clientOrganizationId:i,organizationId:i?A(i):void 0}}validateResources(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i,clientOrganizationId:t}=e,o=[],c=[],a=r.length>0||s.length>0;i&&!a&&(o.push(this.organizationDetails(i)),c.push({id:t??"",type:"organization"})),r.forEach(u=>{o.push(this.folderDetails({folderId:T(u),organizationId:i??""})),c.push({id:u,type:"folder"})}),s.forEach(u=>{o.push(this.documentDetails({documentId:_(u),organizationId:i??""})),c.push({id:u,type:"document"})});let[n,d]=yield Promise.all([Promise.allSettled(o),this.getDefaultDocumentAccessType()]),h=this.processValidationResults(n,c);return y(f({},this.suppressResolverGrantedFailures(h,t)),{defaultDocumentAccessType:d})})}suppressResolverGrantedFailures(e,r){try{let s=this.authService.getUser()?.userId;if(!s)return e;let i=this.getPermissionsCache()??[];if(i.length===0)return e;let t=(n,d,h)=>i.some(u=>u?.userId===s&&u?.resourceId===n&&u?.type===d&&(!h||u?.organizationId===h)&&u?.hasAccess===!0),o=e.failedDocumentIds.filter(n=>!(n.errorCode===l.PERMISSION_DENIED&&t(n.id,I.DOCUMENT,r))),c=e.failedFolderIds.filter(n=>!(n.errorCode===l.PERMISSION_DENIED&&t(n.id,I.FOLDER,r))),a=e.failedOrganizationId;return a&&a.errorCode===l.PERMISSION_DENIED&&r&&t(r,I.ORGANIZATION,r)&&(a=void 0),{failedFolderIds:c,failedDocumentIds:o,failedOrganizationId:a,folderAccessTypes:e.folderAccessTypes,documentAccessTypes:e.documentAccessTypes}}catch(s){return this.loggingService.catch("Error in UserPermissionService suppressResolverGrantedFailures:",s),e}}getDefaultDocumentAccessType(){return g(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,r){let s=[],i=[],t,o={},c={};for(let a=0;a<e.length;a++){let n=e[a],d=r[a];if(n.status==="rejected"||n.status==="fulfilled"&&n.value.error){let u=n.status==="fulfilled"?n.value.errorCode??l.SOMETHING_WENT_WRONG:l.SOMETHING_WENT_WRONG,m={id:d.id,errorCode:u};switch(d.type){case"organization":if(t=m,u===l.DOES_NOT_EXIST)throw new Error(`Organization with id '${d.id}' does not exist`);break;case"folder":s.push(m);break;case"document":i.push(m);break}}else if(n.status==="fulfilled")switch(d.type){case"folder":n.value.accessType&&(o[d.id]=n.value.accessType);break;case"document":n.value.accessType&&(c[d.id]=n.value.accessType);break}}return{failedFolderIds:s,failedDocumentIds:i,failedOrganizationId:t,folderAccessTypes:o,documentAccessTypes:c}}fetchUserPermissionsFromDB(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i}=e,t=[this.authService.getUser()?.userId??""],o=[...r.map(n=>T(n)),...s.map(n=>_(n)),i??""],[c,a]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:t,organizationId:i}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:t,organizationId:i,resourceIds:o})]);return[c.status==="fulfilled"?c.value:[],a.status==="fulfilled"?a.value:[]]})}buildPermissionsResponse(e,r,s,i){let{folderIds:t,documentIds:o,clientOrganizationId:c,organizationId:a}=e,{failedFolderIds:n,failedDocumentIds:d,failedOrganizationId:h}=r,u={};return this.processRegularUserPermissions(u,s,t,o,c??"",a??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.ensureCurrentUserFailuresRecorded(u,c??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.processTemporaryUserPermissions(u,i),this.processContextPermissions(u),u}processContextPermissions(e){try{let r=this.authService.getUser()?.userId;if(r){let s=this.contactService.getUserAccessFieldsByUserId(r);s?.length&&(e[r]||(e[r]={}),e[r].context={accessFields:s})}}catch(r){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",r);return}}processRegularUserPermissions(e,r,s,i,t,o,c,a,n,d,h,u){for(let m of r)for(let C of m)C?.user?.userId&&(e[C.user.userId]=y(f({},s.length&&{folders:this.buildFolderPermissions(s,C,c,d,u)}),{documents:this.buildDocumentPermissions(i,C,a,h,u),organization:{[t]:this.buildOrganizationPermission(o,C,n)}}))}ensureCurrentUserFailuresRecorded(e,r,s,i,t,o,c,a){try{let n=this.authService.getUser()?.userId;if(!n)return;let d=!!t&&!!r,h=(s?.length??0)>0,u=(i?.length??0)>0;if(!d&&!h&&!u)return;if(e[n]||(e[n]={}),d&&(e[n].organization||(e[n].organization={}),e[n].organization[r]||(e[n].organization[r]={error:this.getErrorMessage(t.errorCode,"organization"),errorCode:t.errorCode})),h){e[n].folders||(e[n].folders={});for(let m of s)e[n].folders[m.id]||(e[n].folders[m.id]=f({error:this.getErrorMessage(m.errorCode,"folder"),errorCode:m.errorCode},m.errorCode===l.PERMISSION_DENIED&&{accessType:o[m.id]??a??p}))}if(u){e[n].documents||(e[n].documents={});for(let m of i)e[n].documents[m.id]||(e[n].documents[m.id]=f({error:this.getErrorMessage(m.errorCode,"document"),errorCode:m.errorCode},m.errorCode===l.PERMISSION_DENIED&&{accessType:c[m.id]??a??p}))}}catch(n){this.loggingService.catch("Error in UserPermissionService ensureCurrentUserFailuresRecorded:",n)}}getErrorMessage(e,r){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${r}`),e){case l.DOES_NOT_EXIST:return`${r} does not exist`;case l.PERMISSION_DENIED:return`User does not have access to ${r}`;case l.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(s){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",s),"Something went wrong"}}buildFolderPermissions(e,r,s,i,t){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=f({error:this.getErrorMessage(a.errorCode,"folder"),errorCode:a.errorCode},a.errorCode===l.PERMISSION_DENIED&&{accessType:i[c]??t??p}):o[c]={accessRole:r.viewerFolderIds?.includes(T(c))?S.VIEWER:S.EDITOR,accessType:i[c]??t??p},o},{})}buildDocumentPermissions(e,r,s,i,t){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=f({error:this.getErrorMessage(a.errorCode,"document"),errorCode:a.errorCode},a.errorCode===l.PERMISSION_DENIED&&{accessType:i[c]??t??p}):o[c]={accessRole:r.viewerDocumentIds?.includes(_(c))?S.VIEWER:S.EDITOR,accessType:i[c]??t??p},o},{})}buildOrganizationPermission(e,r,s){return s?{error:this.getErrorMessage(s.errorCode,"organization"),errorCode:s.errorCode}:{accessRole:r.viewerOrganizationIds?.includes(e)?S.VIEWER:S.EDITOR}}processTemporaryUserPermissions(e,r){for(let s of r)if(s?.userId)switch(this.ensureUserPermissionStructure(e,s.userId),s.type){case"folder":this.addTemporaryFolderPermission(e,s);break;case"document":this.addTemporaryDocumentPermission(e,s);break;case"organization":this.addTemporaryOrganizationPermission(e,s);break}}ensureUserPermissionStructure(e,r){e[r]||(e[r]={})}addTemporaryFolderPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].folders||(e[s].folders={}),e[s].folders[i]={accessRole:t??S.EDITOR,expiresAt:o}}addTemporaryDocumentPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].documents||(e[s].documents={}),e[s].documents[i]={accessRole:t??S.EDITOR,expiresAt:o}}addTemporaryOrganizationPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].organization||(e[s].organization={}),e[s].organization[i]={accessRole:t??S.EDITOR,expiresAt:o}}hasEditAccess({organizationId:e,folderId:r,documentId:s}){try{let i=!0,t=this.getCurrentUserPermissionsWithServerIds(),o=this.authService.getUser()?.userId??"";return t&&(e&&typeof e=="string"&&t?.[o]?.organization?.[e]&&(t?.[o]?.organization?.[e]?.accessRole===S.VIEWER||t?.[o]?.organization?.[e]?.errorCode===l.PERMISSION_DENIED)&&(i=!1),r&&typeof r=="string"&&t?.[o]?.folders?.[r]&&(t?.[o]?.folders?.[r]?.accessRole===S.VIEWER||t?.[o]?.folders?.[r]?.errorCode===l.PERMISSION_DENIED)&&(i=!1),s&&typeof s=="string"&&t?.[o]?.documents?.[s]&&(t?.[o]?.documents?.[s]?.accessRole===S.VIEWER||t?.[o]?.documents?.[s]?.errorCode===l.PERMISSION_DENIED)&&(i=!1)),i}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(w(b))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let r=JSON.parse(JSON.stringify(e??{})),s=this.authService.getUser()?.userId??"";if(r?.[s]){let i=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(r?.[s]?.organization?.[i]){let t=A(i);r[s].organization&&(r[s].organization[t]=r[s].organization[i],delete r[s].organization[i])}r?.[s]?.folders&&(r[s].folders=Object.fromEntries(Object.entries(r?.[s]?.folders??{}).map(([t,o])=>[T(t),o]))),r?.[s]?.documents&&(r[s].documents=Object.fromEntries(Object.entries(r?.[s]?.documents??{}).map(([t,o])=>[_(t),o])))}return r}catch(r){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",r),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(G(e=>this.refactorPermissionsWithServerIds(e)),w(b))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let r=null;e&&(r=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(r)}catch(r){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",r)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.permissionProvider$.next(e)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",r)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return g(this,null,function*(){let e=M();try{if(this.isRevokeAccessOnUserLogoutEnabled){let r=[],s=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(t=>{t.userId===s&&t.hasAccess&&(t.type===I.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&r.push(y(f({},t),{hasAccess:!1})):r.push(y(f({},t),{hasAccess:!1})))}),r.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}}),this.setPermissionsCache([]),this.clearRequestKeyedPermissionsCache(),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}});let t=yield this.revokeAccess({requests:r,userId:this.authService.getUser()?.userId??""});t.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:t,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:t,success:!1,statusCode:500}}})}}}catch(r){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:r}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",r)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(r){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",r),""}}cancelPendingRevokes(e){try{e.forEach(r=>{let s=this.getRevokeKey({userId:r.userId,resourceId:r.resource.id,type:r.resource.type,organizationId:r.resource.organizationId});this.pendingRevokeRequests.has(s)&&this.pendingRevokeRequests.delete(s)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(r){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",r)}}flushPendingRevokes(){return g(this,null,function*(){let e=this.pendingRevokeUniqueId,r=this.pendingRevokeUserId;try{let s=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",s.length===0)return;let i=this.getPermissionsCache()??[];s.forEach(c=>{i=i.filter(a=>!(a.resourceId===c.resourceId&&a.type===c.type&&a.organizationId===c.organizationId&&a.userId===c.userId))}),this.setPermissionsCache(i);let t=this.docService.getDocContext(),o=yield this.revokeAccess({requests:s,userId:r,currentContext:t});o.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!1,statusCode:500}}})}catch(s){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:s}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",s)}})}revokeAccessOnDocumentUnset(i){return g(this,arguments,function*({documentIds:e,folderId:r,context:s}){let t=M();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let o=[],c=this.docService.getOrganizationConfig()?.clientOrganizationId??"",a=this.authService.getUser()?.userId??"",n=this.getPermissionsCache()??[];e.forEach(d=>{n=this.collectRevokeRequest(n,o,d.clientDocumentId,I.DOCUMENT,c,a)}),r&&(n=this.collectRevokeRequest(n,o,r,I.FOLDER,c,a)),c&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(n=this.collectRevokeRequest(n,o,c,I.ORGANIZATION,c,a)),s&&this.getIsContextEnabled()&&J({input:s}).forEach(h=>{let u=JSON.stringify(h.access);n=this.collectRevokeRequest(n,o,u,I.CONTEXT,c,a)}),this.setPermissionsCache(n),o.length>0&&(this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),o.forEach(d=>{this.pendingRevokeRequests.set(this.getRevokeKey(d),d)}),this.pendingRevokeUniqueId=t,this.pendingRevokeUserId=a,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(o){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:o}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",o)}})}getAccess(s){return g(this,arguments,function*({requests:e,userId:r}){let i={retryConfig:this.getPermissionProviderRetryConfig()};return this.isClientDevResolverActive()?i.clientResolvedResults=yield this.resolveClientSide(e):this.getPermissionProvider()?.dev&&this.warnNoResolverOnce(),this.sendGetAccessToProxy({requests:e,userId:r,metadata:i})})}sendGetAccessToProxy(i){return g(this,arguments,function*({requests:e,userId:r,metadata:s}){let t=V(this.functions,F({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield z({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:s},getSdkProxy:t,userId:r})})}isClientDevResolverActive(){return!!this.getPermissionProvider()?.dev&&this.isClientDevResolverConfigured()}resolveClientSidePermissions(e){return g(this,null,function*(){if(!this.isClientDevResolverActive())throw new Error("Client-side dev permission resolver is not active");return this.resolveClientSide(e)})}isClientDevResolverConfigured(){let e=this.getPermissionProvider();return e?!!e.endpointConfig?.url?.trim()||typeof e.resolvePermissions=="function":!1}resolveClientSide(e){return g(this,null,function*(){this.warnClientResolverEnabledOnce();let r=this.getPermissionProvider(),s=this.getPermissionProviderRetryConfig(),i=r?.resolveTimeout??6e4,t=yield j(()=>this.withResolverTimeout(()=>this.invokeResolver(e,r),i),"clientPermissionResolver",{retryCount:s?.retryCount??0,retryDelay:s?.retryDelay??0});if(!t||!t.success||t.statusCode!==200)throw new Error(t?.message??"Client permission resolver failed");let o=t.data;if(!Array.isArray(o))throw new Error("Client permission resolver returned a malformed payload");return o})}invokeResolver(e,r){return g(this,null,function*(){let s={data:{requests:e}},i=r.endpointConfig?.url?.trim();if(i)return B(i,r.endpointConfig?.headers,s,!0,r.endpointConfig?.credentials);let t=yield r.resolvePermissions(s);if(Array.isArray(t))return{data:t,success:!0,statusCode:200};let o=t,c=o?.statusCode??(o?.success===!1?500:200),a=o?.success!==!1&&c===200;return{data:Array.isArray(o?.data)?o.data:void 0,success:a,statusCode:a?200:c===200?500:c,message:o?.message}})}withResolverTimeout(e,r){return g(this,null,function*(){if(!r||r<=0)return e();let s,i=new Promise((t,o)=>{s=setTimeout(()=>o(new Error("Client permission resolver timed out")),r)});try{return yield Promise.race([e(),i])}finally{s&&clearTimeout(s)}})}warnClientResolverEnabledOnce(){this.clientResolverProdWarned||(this.clientResolverProdWarned=!0,console.warn("[Velt] Client-side dev permission resolver is enabled (dev: true). Permissions are resolved in the browser for local development only \u2014 DO NOT use this in production. Production API keys ignore browser-resolved results and fall back to the server-side permission provider."))}warnNoResolverOnce(){this.clientResolverNoResolverWarned||(this.clientResolverNoResolverWarned=!0,console.warn("[Velt] setPermissionProvider was called with dev: true but no endpointConfig.url or resolvePermissions callback was provided. Falling back to the server-side permission provider."))}revokeAccess(i){return g(this,arguments,function*({requests:e,userId:r,currentContext:s}){let t=V(this.functions,F({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield z({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:f({retryConfig:this.getPermissionProviderRetryConfig()},s?.access&&{currentContext:s})},getSdkProxy:t,userId:r})})}onResourceAccessRequired(o){return g(this,arguments,function*({requests:e,uniqueId:r,methodName:s,userId:i,fromCache:t=!0}){try{if(!e?.length)return;let c=[],a=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&t&&(e.forEach(n=>{let d=a?.find(h=>h.resourceId===n.resource.id&&h.type===n.resource.type&&h.userId===n.userId&&h.organizationId===n.resource.organizationId);d&&c.push(d)}),c.length>0&&(e=e.filter(n=>!c.find(d=>d.resourceId===n.resource.id&&d.type===n.resource.type&&d.userId===n.userId&&d.organizationId===n.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{requests:e,fromCache:t,clientResolved:this.isClientDevResolverActive()}});let n=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??i??""});return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{result:n,clientResolved:this.isClientDevResolverActive()}}),n?.success&&n?.data?.length&&(this.setPermissionsCache([...a,...n.data]),n.data=[...c,...n.data]),n}else if(c.length>0)return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{results:{data:c,success:!0,statusCode:200}}}),{data:c,success:!0,statusCode:200};return}catch(c){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",c),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{error:c,requests:e,fromCache:t}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let r=new Map;e.forEach(i=>{let t=`${i.userId}_${i.resourceId}_${i.organizationId}_${i.type}`;r.set(t,i)});let s=JSON.parse(JSON.stringify(Array.from(r.values())));this.permissionsCache$.next(s)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",r)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};O.\u0275fac=function(r){return new(r||O)(P(Z),P(Q),P(X),P(se),P(ee),P(re),P(Y),P(W),P(q),P(ie))},O.\u0275prov=K({token:O,factory:O.\u0275fac,providedIn:"root"});let k=O;return k})();export{ye as a};
|