import { Injectable, OnDestroy } from '@angular/core'; import { NavigationEnd, Router } from '@angular/router'; import { BehaviorSubject, Observable, Subject, Subscription, forkJoin, of } from 'rxjs'; import { catchError, distinctUntilChanged, filter, finalize, map, shareReplay, switchMap } from 'rxjs/operators'; import { JwtHelperService } from '@auth0/angular-jwt'; import { AuthService } from './_services/auth/auth.service'; import { WorkflowService } from './_services/workflow/workflow.service'; /** * SINGLE SOURCE OF TRUTH for ESS notification state. * * - fetch -> ensureLoaded() / refreshNotifications() * - state -> notifications$ (bell / panel list - "OtherNotifications") * hrNotifications$ (dashboard "Company Updates" feed - "HrNotifications") * - unread count -> unreadCount$ (DERIVED from notifications$, counts isRead !== true rows) * - mark read -> openNotifications() marks the currently visible rows read RIGHT AWAY * (optimistic: isRead flips locally so the badge clears instantly, the * rows stay on screen so the panel doesn't go blank while still open) * markVisibleAsReadThenRefresh() re-fetches on panel close, so a later * open only shows notifications that are genuinely still unread * - reset -> clear() (on logout) * * AppTopBarComponent and UserSSDashboardComponent are pure CONSUMERS: they * subscribe to the observables above and never fetch / count / mark-read * themselves. That is what keeps the two badges identical. No UI/template of * the existing notification panel changes - only the data flow behind it. * * Backend notes: * - /Workflow/getNotificationItemsESS returns a DataSet: { hrNotifications, otherNotifications }. * - otherNotifications is actually TWO different sources UNION'd together - they need * two different "mark read" calls: * 1. EmployeeNotification rows: real `employeeNotificationID` (> 0) + `isRead` column. * -> POST /Workflow/MarkNotificationsAsRead (batch of ids). Query already filters * IsRead = 0 and caps at TOP 15, so a fresh fetch after mark-read can surface * rows that were previously outside the window. * 2. WFMOVEMENTTASK "SysNotification" rows: `employeeNotificationID` is always 0 here, * there is NO IsRead column for these - they only have a WFMOVEMENTTASKID + a * Status flag. -> POST /Workflow/updateSysNotification per row (WFMovementTask.ID * = the row's WFMOVEMENTTASKID), which flips Status so the row drops out of the * next fetch's `WHERE Status = 0` filter. * Both kinds are treated as "unread" client-side via the same `isRead` flag on the row * object (that flag does not exist on the SysNotification rows server-side - it is only * ever set/read here, in this service). */ @Injectable() export class NotificationTriggerService implements OnDestroy { // -------- panel open trigger (unchanged public contract) -------- private notificationSource = new Subject(); notificationSource$ = this.notificationSource.asObservable(); // -------- notification state -------- private notificationsSource = new BehaviorSubject([]); /** Rows shown in the notification bell / panel dropdown. */ readonly notifications$ = this.notificationsSource.asObservable(); private hrNotificationsSource = new BehaviorSubject([]); /** Rows shown in the dashboard "Company Updates & Notification" feed. */ readonly hrNotifications$ = this.hrNotificationsSource.asObservable(); /** * Unread count DERIVED from the one list. Both the top-bar bell and the * dashboard tile ultimately read this same list, so they can never diverge. */ readonly unreadCount$ = this.notificationsSource.pipe( map(list => this.countUnread(list)), distinctUntilChanged(), shareReplay({ bufferSize: 1, refCount: false }) ); private jwtHelper = new JwtHelperService(); private loaded = false; private inFlight$: Observable | null = null; private activeSeq = 0; // sequence of the request that owns inFlight$ private reqSeq = 0; // guards against a stale response overwriting newer state private lastRefreshStartedAt = 0; private routerSub: Subscription; private logoutSub: Subscription; constructor(private authService: AuthService, private wfService: WorkflowService, private router: Router) { // Wipe notification state on logout so it never leaks into the next session. this.logoutSub = this.authService.logout$.subscribe(() => this.clear()); // Re-fetch when the user lands on an ESS dashboard - mirrors the app's // existing "refresh on dashboard entry" behaviour so notifications created // while the user was elsewhere become visible. De-duped in refreshNotifications(). // NOTE: must match the actual route segments in ess-routing.module.ts // ('self-dashboard', 'ess-dashboard', 'selfservice-dashboard') - this previously // only listed 'user-ss-dashboard' / 'ess-dashboard', neither of which appears in // the real URL '/ess/self-dashboard', so this trigger silently never fired for // the most-used ESS landing page: only the one-time ensureLoaded() fetch (right // after login) ever ran, and later visits to the page kept showing that same // stale snapshot (Company Updates included) instead of fetching again. this.routerSub = this.router.events.pipe( filter((e): e is NavigationEnd => e instanceof NavigationEnd) ).subscribe(e => { const url = e.urlAfterRedirects || e.url || ''; if (/self-dashboard|ess-dashboard|selfservice-dashboard/i.test(url)) { this.refreshNotifications().subscribe(); } }); } ngOnDestroy(): void { this.routerSub?.unsubscribe(); this.logoutSub?.unsubscribe(); } // ------------------------------------------------------------------ // Panel open trigger // ------------------------------------------------------------------ /** Opens (toggles) the shared notification panel that AppTopBarComponent renders. */ openNotifications(): void { this.notificationSource.next(); // The user is looking at these rows right now - mark them read immediately // so the badge/count clears without waiting for the panel to close. this.markVisibleAsRead(); } // ------------------------------------------------------------------ // Reads // ------------------------------------------------------------------ /** Count shown on the badge = number of rows not yet marked read. */ countUnread(notifications: any[]): number { return (notifications || []).filter(n => n && n.isRead !== true).length; } /** Back-compat alias for callers that pass an explicit list. */ getUnreadCount(notifications: any[]): number { return this.countUnread(notifications); } get snapshot(): any[] { return this.notificationsSource.value || []; } // ------------------------------------------------------------------ // Loading // ------------------------------------------------------------------ /** * Loads notifications once per session. Safe to call from every consumer's * ngOnInit / login handler - the first call with a valid session wins, the * rest are no-ops. Seeds instantly from localStorage for first paint, then * refreshes from the API. */ ensureLoaded(): void { if (this.loaded || this.inFlight$) { return; } if (!this.getEmployeeId()) { return; } // no session yet - a later trigger will retry this.seedFromCache(); this.refreshNotifications().subscribe(); } /** * Force a fresh fetch from the API and publish it to the store. * Concurrent callers share ONE HTTP request. A response is applied only if it * is still the newest request (stale responses are dropped). */ refreshNotifications(): Observable { if (this.inFlight$ && (Date.now() - this.lastRefreshStartedAt) < 1500) { return this.inFlight$; // de-dupe rapid successive triggers } const employeeId = this.getEmployeeId(); if (!employeeId) { return of(void 0); } const seq = ++this.reqSeq; this.activeSeq = seq; this.lastRefreshStartedAt = Date.now(); this.inFlight$ = this.wfService.getNotificationItemsESS(employeeId).pipe( map((resp: any) => { if (seq !== this.reqSeq) { return; } // superseded - ignore const hr = this.normalizeList(resp && resp.hrNotifications); let other = this.normalizeList(resp && resp.otherNotifications); // if (other.length === 0) { // other = [{ // type: 2, new: false, // description: 'Welcome to GOHR self Dashboard!', // sentTime: undefined, notificationUrl: '', isAttachment: 0 // }]; // } this.persist(other); this.hrNotificationsSource.next(hr); this.notificationsSource.next(other); this.loaded = true; }), catchError(err => { console.error('[Notifications] refresh failed', err); return of(void 0); }), finalize(() => { if (this.activeSeq === seq) { this.inFlight$ = null; } }), shareReplay({ bufferSize: 1, refCount: false }) ); return this.inFlight$; } // ------------------------------------------------------------------ // Mark as read // ------------------------------------------------------------------ /** Case-insensitive lookup - the raw DataTable's real column casing isn't guaranteed. */ private getTaskId(n: any): number { if (!n) { return 0; } const key = Object.keys(n).find(k => k.toLowerCase() === 'wfmovementtaskid'); const val = key ? n[key] : undefined; return val != null ? Number(val) : 0; } private isSysNotificationRow(n: any): boolean { return !!n && (n.employeeNotificationID == null || n.employeeNotificationID === 0) && this.getTaskId(n) > 0; } private getUnreadEmployeeNotificationIds(list: any[]): number[] { return (list || []) .filter(n => n && n.employeeNotificationID != null && n.employeeNotificationID > 0 && n.isRead !== true) .map(n => n.employeeNotificationID); } private getUnreadSysNotificationTaskIds(list: any[]): number[] { return (list || []) .filter(n => n && n.isRead !== true && this.isSysNotificationRow(n)) .map(n => this.getTaskId(n)); } private postMarkEmployeeNotificationsRead(ids: number[]): Observable { return ids.length === 0 ? of(null) : this.authService.markNotificationsAsRead(ids).pipe( catchError(err => { console.error('[Notifications] mark-as-read failed', err); return of(null); }) ); } /** No batch endpoint for WFMOVEMENTTASK rows - one POST per task id. */ private postMarkSysNotificationsRead(taskIds: number[]): Observable { if (taskIds.length === 0) { return of(null); } return forkJoin(taskIds.map(id => this.wfService.updateSysNotification({ id } as any).pipe( catchError(err => { console.error('[Notifications] sys-notification mark-as-read failed', err); return of(null); }) ) )); } /** * Fires the moment the notification panel opens (see openNotifications()). * Optimistic: flips `isRead` on the currently visible rows straight away, so * unreadCount$ - and every badge derived from it - drops instantly. The rows * themselves stay in the list (not removed) so the open panel keeps showing * what the user is looking at instead of going blank mid-read. */ private markVisibleAsRead(): void { const current = this.notificationsSource.value || []; const empIds = this.getUnreadEmployeeNotificationIds(current); const taskIds = this.getUnreadSysNotificationTaskIds(current); if (empIds.length === 0 && taskIds.length === 0) { return; } const empIdSet = new Set(empIds); const taskIdSet = new Set(taskIds); const updated = current.map(n => { const isTarget = (n.employeeNotificationID != null && empIdSet.has(n.employeeNotificationID)) || (this.isSysNotificationRow(n) && taskIdSet.has(this.getTaskId(n))); return isTarget ? { ...n, isRead: true } : n; }); this.notificationsSource.next(updated); this.persist(updated); this.postMarkEmployeeNotificationsRead(empIds).subscribe(); this.postMarkSysNotificationsRead(taskIds).subscribe(); } /** * The full "notification panel closed" pipeline - used by BOTH entry points: * 1. POST any still-unread ids (both kinds) -> wait for completion * 2. re-fetch the latest notifications from the API (NOT the local array) * 3. publish -> notifications$ / unreadCount$ emit -> both badges update * By the time the panel closes, openNotifications() has usually already marked * everything read, so this mainly re-syncs with the server (drops rows that are * now actually read, pulls in anything new that arrived while the panel was open). */ markVisibleAsReadThenRefresh(): Observable { const current = this.notificationsSource.value || []; const empIds = this.getUnreadEmployeeNotificationIds(current); const taskIds = this.getUnreadSysNotificationTaskIds(current); return forkJoin([ this.postMarkEmployeeNotificationsRead(empIds), this.postMarkSysNotificationsRead(taskIds) ]).pipe( switchMap(() => { // We need genuinely fresh data now - bypass the de-dupe window. this.inFlight$ = null; this.lastRefreshStartedAt = 0; return this.refreshNotifications(); }) ); } // ------------------------------------------------------------------ // Reset (logout) // ------------------------------------------------------------------ clear(): void { this.reqSeq++; // invalidate any in-flight response this.activeSeq = this.reqSeq; this.inFlight$ = null; this.loaded = false; this.lastRefreshStartedAt = 0; this.hrNotificationsSource.next([]); this.notificationsSource.next([]); try { localStorage.removeItem('notifications'); } catch { /* ignore */ } } // ------------------------------------------------------------------ // helpers // ------------------------------------------------------------------ private seedFromCache(): void { try { const cached = JSON.parse(localStorage.getItem('notifications') || 'null'); if (Array.isArray(cached) && cached.length) { this.notificationsSource.next(cached); } } catch { /* ignore bad cache */ } } private persist(list: any[]): void { try { localStorage.setItem('notifications', JSON.stringify(list || [])); } catch { /* ignore */ } } private normalizeList(list: any): any[] { const arr = Array.isArray(list) ? [...list] : []; arr.forEach(n => this.normalizeUrl(n)); return arr; } /** Same URL normalisation the dashboard applied when it first loaded notifications. */ private normalizeUrl(task: any): void { if (!task || !task.notificationUrl) { return; } const url = ('' + task.notificationUrl).trim(); if (!url.toLowerCase().startsWith('http://') && !url.toLowerCase().startsWith('https://')) { task.notificationUrl = 'http://' + url; } } private getEmployeeId(): number | null { try { const user = this.jwtHelper.decodeToken(localStorage.getItem('token')); return user && user.EmployeeID != null ? Number(user.EmployeeID) : null; } catch { return null; } } }