@tech4good/angular-schematics 21.4.0 → 21.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/package.json +1 -1
  3. package/src/entity/files/__name@dasherize__/__name@dasherize__.mock.ts.template +2 -1
  4. package/src/entity/files/__name@dasherize__/__name@dasherize__.model.ts.template +2 -1
  5. package/src/entity/index.js +57 -0
  6. package/src/entity/index.js.map +1 -1
  7. package/src/entity/schema.json +4 -0
  8. package/src/ng-add/files/.firebaserc.template +2 -1
  9. package/src/ng-add/files/.gitignore.template +2 -0
  10. package/src/ng-add/files/bigquery/queries/active_time_by_route.sql.template +34 -0
  11. package/src/ng-add/files/bigquery/scripts/export_entities.py.template +143 -0
  12. package/src/ng-add/files/bigquery/scripts/run_query.py.template +167 -0
  13. package/src/ng-add/files/bigquery/views/events_flat.sql.template +60 -0
  14. package/src/ng-add/files/bigquery/views/logs_latest.sql.template +34 -0
  15. package/src/ng-add/files/docs-infra/analytics-guide.md.template +170 -0
  16. package/src/ng-add/files/docs-infra/authentication-architecture.md.template +270 -0
  17. package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +16 -10
  18. package/src/ng-add/files/firebase.json.template +6 -0
  19. package/src/ng-add/files/firebase.logs.json.template +5 -0
  20. package/src/ng-add/files/firestore.indexes.json.template +112 -0
  21. package/src/ng-add/files/firestore.logs.rules.spec.ts.template +100 -0
  22. package/src/ng-add/files/firestore.logs.rules.template +8 -0
  23. package/src/ng-add/files/firestore.rules.spec.ts.template +84 -15
  24. package/src/ng-add/files/firestore.rules.template +29 -17
  25. package/src/ng-add/files/functions/.gitignore.template +3 -0
  26. package/src/ng-add/files/functions/package.json.template +12 -0
  27. package/src/ng-add/files/functions/src/index.ts.template +44 -0
  28. package/src/ng-add/files/functions/tsconfig.json.template +13 -0
  29. package/src/ng-add/files/jest.config.ts.template +1 -1
  30. package/src/ng-add/files/package.json.template +7 -4
  31. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.html.template +3 -1
  32. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +6 -8
  33. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.ts.template +2 -0
  34. package/src/ng-add/files/src/app/app.component.html.template +2 -2
  35. package/src/ng-add/files/src/app/app.component.ts.template +2 -0
  36. package/src/ng-add/files/src/app/app.routes.ts.template +6 -0
  37. package/src/ng-add/files/src/app/auth-routing.spec.ts.template +9 -4
  38. package/src/ng-add/files/src/app/core/analytics/log.service.ts.template +26 -4
  39. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.spec.ts.template +145 -2
  40. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.ts.template +355 -149
  41. package/src/ng-add/files/src/app/core/auth/auth.service.ts.template +6 -1
  42. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.spec.ts.template +38 -0
  43. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.ts.template +3 -2
  44. package/src/ng-add/files/src/app/core/auth/guards/require-auth-and-consent.guard.ts.template +10 -3
  45. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +11 -5
  46. package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +34 -17
  47. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.spec.ts.template +59 -0
  48. package/src/ng-add/files/src/app/core/firebase/email-link-context.service.ts.template +147 -0
  49. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +104 -17
  50. package/src/ng-add/files/src/app/core/firebase/firebase.service.spec.ts.template +116 -0
  51. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +367 -70
  52. package/src/ng-add/files/src/app/core/store/app.store.ts.template +4 -1
  53. package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +52 -66
  54. package/src/ng-add/files/src/app/core/store/auth/auth.store.spec.ts.template +127 -0
  55. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +216 -147
  56. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +2 -4
  57. package/src/ng-add/files/src/app/core/store/user/user.model.ts.template +1 -1
  58. package/src/ng-add/files/src/app/core/store/user-private/user-private.model.ts.template +1 -0
  59. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.html.template +4 -0
  60. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.scss.template +1 -0
  61. package/src/ng-add/files/src/app/first-time/auth-action/auth-action.component.ts.template +38 -0
  62. package/src/ng-add/files/src/app/first-time/consent/consent.component.html.template +172 -48
  63. package/src/ng-add/files/src/app/first-time/consent/consent.component.scss.template +31 -0
  64. package/src/ng-add/files/src/app/first-time/consent/consent.component.spec.ts.template +31 -3
  65. package/src/ng-add/files/src/app/first-time/consent/consent.component.ts.template +12 -11
  66. package/src/ng-add/files/src/app/first-time/consent/consent.guard.ts.template +5 -7
  67. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +12 -1
  68. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +93 -48
  69. package/src/ng-add/files/src/app/first-time/early-access/early-access.guard.ts.template +12 -2
  70. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.html.template +18 -0
  71. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.scss.template +2 -0
  72. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.spec.ts.template +40 -0
  73. package/src/ng-add/files/src/app/first-time/email-link/email-link.component.ts.template +76 -0
  74. package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +14 -8
  75. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.html.template +19 -7
  76. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.scss.template +51 -0
  77. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +29 -5
  78. package/src/ng-add/files/src/app/first-time/landing/landing.component.html.template +2 -1
  79. package/src/ng-add/files/src/app/first-time/landing/landing.component.scss.template +12 -8
  80. package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +31 -10
  81. package/src/ng-add/files/src/app/first-time/landing/landing.component.ts.template +6 -19
  82. package/src/ng-add/files/src/app/first-time/login/login.component.html.template +58 -6
  83. package/src/ng-add/files/src/app/first-time/login/login.component.scss.template +151 -22
  84. package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +18 -38
  85. package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +59 -31
  86. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.html.template +12 -0
  87. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.scss.template +39 -0
  88. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.spec.ts.template +68 -0
  89. package/src/ng-add/files/src/app/main/account-profile/account-profile.component.ts.template +20 -0
  90. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.html.template +24 -0
  91. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.scss.template +50 -0
  92. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.spec.ts.template +65 -0
  93. package/src/ng-add/files/src/app/main/account-profile/delete-guest-card/delete-guest-card.component.ts.template +59 -0
  94. package/src/ng-add/files/src/app/main/account-profile/guest-deletion-dialog.component.ts.template +51 -0
  95. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.html.template +50 -0
  96. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.scss.template +137 -0
  97. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.spec.ts.template +57 -0
  98. package/src/ng-add/files/src/app/main/account-profile/profile-details-card/profile-details-card.component.ts.template +59 -0
  99. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.html.template +133 -0
  100. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.scss.template +207 -0
  101. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.spec.ts.template +74 -0
  102. package/src/ng-add/files/src/app/main/account-profile/sign-in-methods-card/sign-in-methods-card.component.ts.template +130 -0
  103. package/src/ng-add/files/src/app/main/home/home.component.ts.template +0 -5
  104. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.html.template +15 -0
  105. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.scss.template +79 -0
  106. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.spec.ts.template +59 -0
  107. package/src/ng-add/files/src/app/shared/guest-warning-bar/guest-warning-bar.component.ts.template +44 -0
  108. package/src/ng-add/files/src/app/shared/navbar/navbar.component.html.template +45 -15
  109. package/src/ng-add/files/src/app/shared/navbar/navbar.component.scss.template +103 -19
  110. package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +73 -9
  111. package/src/ng-add/files/src/app/shared/navbar/navbar.component.ts.template +46 -18
  112. package/src/ng-add/files/src/environments/environment.prod.ts.template +1 -0
  113. package/src/ng-add/files/src/environments/environment.test.ts.template +1 -0
  114. package/src/ng-add/files/src/environments/environment.ts.template +1 -1
  115. package/src/ng-add/index_spec.d.ts +1 -0
  116. package/src/ng-add/index_spec.js +108 -0
  117. package/src/ng-add/index_spec.js.map +1 -0
  118. package/tsconfig.json +2 -2
@@ -1,7 +1,21 @@
1
- import { Injectable, Inject } from '@angular/core';
1
+ import { Injectable, Inject, Signal, Injector, DestroyRef } from '@angular/core';
2
+ import { toObservable } from '@angular/core/rxjs-interop';
2
3
  import { Router, NavigationEnd } from '@angular/router';
3
- import { Subject, Observable, fromEvent, merge, combineLatest } from 'rxjs';
4
- import { startWith, withLatestFrom, tap, takeUntil, switchMap, debounceTime, mergeMap, shareReplay, filter, map, pairwise, scan } from 'rxjs/operators';
4
+ import { Subject, Observable, BehaviorSubject, fromEvent, merge, combineLatest, of, asapScheduler } from 'rxjs';
5
+ import {
6
+ startWith,
7
+ withLatestFrom,
8
+ tap,
9
+ takeUntil,
10
+ switchMap,
11
+ debounceTime,
12
+ mergeMap,
13
+ shareReplay,
14
+ filter,
15
+ map,
16
+ pairwise,
17
+ scan,
18
+ } from 'rxjs/operators';
5
19
  import { LOG_SERVICE, LogService } from './log.service';
6
20
  import { DATABASE_SERVICE, DatabaseService } from '../firebase/database.service';
7
21
  import { SessionLocalStorageService } from '../local-storage/session-local-storage.service';
@@ -12,8 +26,9 @@ export interface TimeAtRoute {
12
26
  __sessionId: string; // unique for a given session/tab
13
27
  __deviceId: string; // unique for the device
14
28
  route: string;
29
+ state?: Record<string, string | null>;
15
30
  startTime: number;
16
- time: Array<{ type: string, total: number }>;
31
+ time: Array<{ type: string; total: number }>;
17
32
  }
18
33
 
19
34
  // We use this typing since Firebase doesn't accept nested arrays
@@ -33,15 +48,16 @@ export interface Interaction {
33
48
  * - add an eventlistener for "visibilitychange" to sendBeacon when user leaves
34
49
  * - define the event stream (this.eventTimestamps$),
35
50
  * - define the route stream (this.currentRoute$),
36
- * - define a stream to track the active time at each route (this.runningTimeAtRoute$)
37
- * by combining the event and route streams, updating the time increment with
51
+ * - define the combined route+state stream (this.routeAndState$),
52
+ * - define a stream to track the active time at each route/state (this.runningTimeAtRoute$)
53
+ * by combining the event and route/state streams, updating the time increment with
38
54
  * each event, and adding in __userId, __sessionId, __deviceId
39
55
  *
40
56
  * Then when startTimeLogging is called in the app init, we:
41
57
  * - first handle any logs in localStorage that never got saved to the DB due to
42
58
  * refresh/close/etc. and clear localStorage
43
59
  * - subscribe to this.runningTimeAtRoute$, saving latest to localStorage, then
44
- * filtering to only when the route or user changes and when total time is
60
+ * filtering to only when the route, user, or state changes and when total time is
45
61
  * non-zero to log to the DB. When saving, reset the interactionsAtRoute and
46
62
  * remove interactions from localStorage
47
63
  *
@@ -51,6 +67,11 @@ export interface Interaction {
51
67
  * local variable as well as in localStorage. The local variable is used when
52
68
  * saving to the DB on route/user changes and the localStorage variable is used
53
69
  * when retrieving and saving prior logs on a new session.
70
+ *
71
+ * When registerState is called by a component, we:
72
+ * - convert the signal to an observable (auto-cleaned up via DestroyRef) and track
73
+ * it in registeredState$. When state values or routes change, routeAndState$
74
+ * triggers log flushes on state changes.
54
75
  */
55
76
  @Injectable({
56
77
  providedIn: 'root',
@@ -66,7 +87,61 @@ export class TimeAnalyticsService {
66
87
  /** The current route a user is visiting. */
67
88
  private currentRoute$: Observable<string>;
68
89
 
69
- /** The running update of time analytics for each route. */
90
+ /**
91
+ * Map storing active registered state key-value streams.
92
+ * Key: state dimension name (e.g. 'problemId')
93
+ * Value: Observable emitting the current string/null state value
94
+ */
95
+ private registeredStatesMap = new Map<string, Observable<string | null>>();
96
+
97
+ /** Subject triggered whenever state streams are added or removed from registeredStatesMap. */
98
+ private stateRegistrySubject$ = new BehaviorSubject<void>(undefined);
99
+
100
+ /**
101
+ * Reactive stream emitting a combined key-value record of all currently registered UI states.
102
+ *
103
+ * How it works:
104
+ * 1. Whenever `stateRegistrySubject$` emits (on state add/remove), `switchMap` rebuilds the stream.
105
+ * 2. If no states are registered, it returns an empty object `{}`.
106
+ * 3. Otherwise, it maps each registered stream to `{ key, val }` with `startWith({ key, val: null })`.
107
+ * 4. `combineLatest` combines all state streams into a single `{ [key]: val }` object, omitting null/undefined values.
108
+ * 5. `shareReplay(1)` ensures late subscribers receive the latest combined state snapshot immediately.
109
+ */
110
+ private registeredState$: Observable<Record<string, string | null>> =
111
+ this.stateRegistrySubject$.pipe(
112
+ switchMap(() => {
113
+ const keys = Array.from(this.registeredStatesMap.keys());
114
+ if (keys.length === 0) {
115
+ return of({});
116
+ }
117
+ const obsArray = keys.map((key) =>
118
+ this.registeredStatesMap.get(key).pipe(
119
+ map((val) => ({ key, val })),
120
+ startWith({ key, val: null as string | null }),
121
+ ),
122
+ );
123
+ return combineLatest(obsArray).pipe(
124
+ map((entries) => {
125
+ const stateObj: Record<string, string | null> = {};
126
+ for (const { key, val } of entries) {
127
+ if (val !== null && val !== undefined) {
128
+ stateObj[key] = val;
129
+ }
130
+ }
131
+ return stateObj;
132
+ }),
133
+ );
134
+ }),
135
+ shareReplay(1),
136
+ );
137
+
138
+ /** Coalesced stream emitting `{ route: string, state: Record<string, string | null> }`. */
139
+ private routeAndState$: Observable<{
140
+ route: string;
141
+ state: Record<string, string | null>;
142
+ }>;
143
+
144
+ /** The running update of time analytics for each route/state. */
70
145
  private runningTimeAtRoute$: Observable<TimeAtRoute>;
71
146
 
72
147
  /** Events representing different registered interactions. */
@@ -75,6 +150,27 @@ export class TimeAnalyticsService {
75
150
  /** Interactions data at latest route. */
76
151
  private interactionsAtRoute: Interaction[] = null;
77
152
 
153
+ /**
154
+ * Compares two state records for shallow equality.
155
+ * Treats null, undefined, and empty objects `{}` as equal (empty state).
156
+ *
157
+ * @param a Previous state object (or undefined)
158
+ * @param b Current state object (or undefined)
159
+ * @returns `true` if state keys and values match, `false` otherwise
160
+ */
161
+ private isEqualState(
162
+ a?: Record<string, string | null>,
163
+ b?: Record<string, string | null>,
164
+ ): boolean {
165
+ const keysA = a ? Object.keys(a) : [];
166
+ const keysB = b ? Object.keys(b) : [];
167
+ if (keysA.length !== keysB.length) return false;
168
+ for (const key of keysA) {
169
+ if (a[key] !== b[key]) return false;
170
+ }
171
+ return true;
172
+ }
173
+
78
174
  /** Helper function for saving log to DB given timeAtRoute, interactionsAtRoute. */
79
175
  private saveLogToDB(timeAtRoute: TimeAtRoute, interactionsAtRoute: Interaction[]) {
80
176
  if (timeAtRoute) {
@@ -103,11 +199,15 @@ export class TimeAnalyticsService {
103
199
  // console.log('GET PRIOR SESSION LOG', timeAtRoute);
104
200
 
105
201
  // Safety check that it really is our data
106
- if (Object.prototype.hasOwnProperty.call(timeAtRoute, '__sessionId') &&
202
+ if (
203
+ Object.prototype.hasOwnProperty.call(timeAtRoute, '__sessionId') &&
107
204
  Object.prototype.hasOwnProperty.call(timeAtRoute, 'route') &&
108
205
  Object.prototype.hasOwnProperty.call(timeAtRoute, 'startTime')
109
206
  ) {
110
- const interactionsAtRoute = this.local.getItemForSession(this.IX_KEY, timeAtRoute.__sessionId);
207
+ const interactionsAtRoute = this.local.getItemForSession(
208
+ this.IX_KEY,
209
+ timeAtRoute.__sessionId,
210
+ );
111
211
  // console.log('SAVE PRIOR SESSION LOG', timeAtRoute, interactionsAtRoute);
112
212
  this.saveLogToDB(timeAtRoute, interactionsAtRoute);
113
213
  }
@@ -125,54 +225,90 @@ export class TimeAnalyticsService {
125
225
  // Handle any unstored logs from prior session
126
226
  this.handlePriorSessionLogs();
127
227
 
128
- // Filters down to only the times when we need to record, i.e. when route or user changes and when total time is non-zero, log to DB, and reset interactions array
129
- this.runningTimeAtRoute$.pipe(
130
- pairwise(),
131
- // Save the latest timeAtRoute to localStorage in case we're interrupted
132
- tap(([timeAtRoute1, timeAtRoute2]) => {
133
- // console.log('SET SESSION LOG', timeAtRoute2);
134
- this.local.setItemForSession(this.TIME_KEY, timeAtRoute2);
135
- }),
136
- filter(([timeAtRoute1, timeAtRoute2]) => {
137
- return timeAtRoute2.route !== timeAtRoute1.route || timeAtRoute2.__userId !== timeAtRoute1.__userId;
138
- }),
139
- filter(([timeAtRoute1, timeAtRoute2]) => {
140
- const total = timeAtRoute1.time.reduce((x, y) => {
141
- return x + y.total;
142
- }, 0);
143
- return total > 0;
144
- }),
145
- ).subscribe(([timeAtRoute1, timeAtRoute2]) => {
146
- // Log the completed log (currently only for logged in users)
147
- // console.log('SAVE LOG TO DB', timeAtRoute1, this.interactionsAtRoute);
148
- this.saveLogToDB(timeAtRoute1, this.interactionsAtRoute);
149
-
150
- // Reset the interactions. Note we do null rather than empty array
151
- // so that we don't add that field when there are no interactions
152
- this.interactionsAtRoute = null;
153
- this.local.removeItemForSession(this.IX_KEY);
228
+ // Filters down to only the times when we need to record, i.e. when route, user, or state changes and when total time is non-zero, log to DB, and reset interactions array
229
+ this.runningTimeAtRoute$
230
+ .pipe(
231
+ pairwise(),
232
+ // Save the latest timeAtRoute to localStorage in case we're interrupted
233
+ tap(([timeAtRoute1, timeAtRoute2]) => {
234
+ // console.log('SET SESSION LOG', timeAtRoute2);
235
+ this.local.setItemForSession(this.TIME_KEY, timeAtRoute2);
236
+ }),
237
+ filter(([timeAtRoute1, timeAtRoute2]) => {
238
+ return (
239
+ timeAtRoute2.route !== timeAtRoute1.route ||
240
+ timeAtRoute2.__userId !== timeAtRoute1.__userId ||
241
+ !this.isEqualState(timeAtRoute1.state, timeAtRoute2.state)
242
+ );
243
+ }),
244
+ filter(([timeAtRoute1, timeAtRoute2]) => {
245
+ const total = timeAtRoute1.time.reduce((x, y) => {
246
+ return x + y.total;
247
+ }, 0);
248
+ return total > 0;
249
+ }),
250
+ )
251
+ .subscribe(([timeAtRoute1, timeAtRoute2]) => {
252
+ // Log the completed log (currently only for logged in users)
253
+ // console.log('SAVE LOG TO DB', timeAtRoute1, this.interactionsAtRoute);
254
+ this.saveLogToDB(timeAtRoute1, this.interactionsAtRoute);
255
+
256
+ // Reset the interactions. Note we do null rather than empty array
257
+ // so that we don't add that field when there are no interactions
258
+ this.interactionsAtRoute = null;
259
+ this.local.removeItemForSession(this.IX_KEY);
260
+ });
261
+ }
262
+
263
+ /**
264
+ * Registers a UI state dimension (Signal) to be tracked alongside route analytics.
265
+ *
266
+ * When the registered state signal value changes (e.g., advancing from `prob1` to `prob2`),
267
+ * `TimeAnalyticsService` flushes the active log document to Firestore and begins a new
268
+ * segment for the new state value.
269
+ *
270
+ * @param key State dimension key (e.g. `'problemId'`)
271
+ * @param valueSignal Signal emitting the current state value string or null
272
+ * @param injector Component's Injector instance (used for `toObservable` and `DestroyRef`)
273
+ *
274
+ * Lifecycle & Cleanup:
275
+ * - Converts `valueSignal` to an RxJS stream using `toObservable(valueSignal, { injector })`.
276
+ * - Automatically unregisters the state key when the component is destroyed via `DestroyRef.onDestroy()`.
277
+ */
278
+ public registerState(
279
+ key: string,
280
+ valueSignal: Signal<string | null>,
281
+ injector: Injector,
282
+ ): void {
283
+ const destroyRef = injector.get(DestroyRef);
284
+ const value$ = toObservable(valueSignal, { injector });
285
+
286
+ this.registeredStatesMap.set(key, value$);
287
+ this.stateRegistrySubject$.next();
288
+
289
+ destroyRef.onDestroy(() => {
290
+ this.registeredStatesMap.delete(key);
291
+ this.stateRegistrySubject$.next();
154
292
  });
155
293
  }
156
294
 
157
295
  /** Function that can be called by a container to register interactions. */
158
296
  public registerInteractions(
159
- interactions: Array<{ 0: string, 1: string, 2: Observable<any> }>,
297
+ interactions: Array<{ 0: string; 1: string; 2: Observable<any> }>,
160
298
  unsubscribe$: Subject<void>,
161
299
  ) {
162
300
  for (const ix of interactions) {
163
301
  // Subscribe to each interaction until unsubscribe, and register that the event occured
164
302
  // console.log('REGISTER INTERACTION', `${ix[0]}-${ix[1]}`);
165
- ix[2].pipe(
166
- takeUntil(unsubscribe$),
167
- ).subscribe((data) => {
303
+ ix[2].pipe(takeUntil(unsubscribe$)).subscribe((data) => {
168
304
  let ixLog = { 0: null, 1: null, 2: null, 3: null };
169
- if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') {
170
- ixLog = { 0: Date.now(), 1: String(ix[0]), 2: String(ix[1]), 3: String(data) };
305
+ if (data !== null && data !== undefined) {
306
+ ixLog = { 0: Date.now(), 1: String(ix[0]), 2: String(ix[1]), 3: typeof data === 'object' ? JSON.stringify(data) : String(data) };
171
307
  } else {
172
308
  ixLog = { 0: Date.now(), 1: String(ix[0]), 2: String(ix[1]), 3: null };
173
309
  }
174
310
  if (!this.interactionsAtRoute) {
175
- const newInteractions: Array<{ 0: number, 1: string, 2: string, 3: string }> = [ixLog];
311
+ const newInteractions: Array<{ 0: number; 1: string; 2: string; 3: string }> = [ixLog];
176
312
  this.interactionsAtRoute = newInteractions;
177
313
  this.local.setItemForSession(this.IX_KEY, this.interactionsAtRoute);
178
314
  // console.log('UPDATE INTERACTIONS', this.interactionsAtRoute);
@@ -188,8 +324,8 @@ export class TimeAnalyticsService {
188
324
  /** Function that can be called by any component to log an interaction event imperatively. */
189
325
  public trackInteraction(category: string, action: string, data: any = null) {
190
326
  let ixLog: Interaction = { 0: null, 1: null, 2: null, 3: null };
191
- if (typeof data === 'string' || typeof data === 'number' || typeof data === 'boolean') {
192
- ixLog = { 0: Date.now(), 1: String(category), 2: String(action), 3: String(data) };
327
+ if (data !== null && data !== undefined) {
328
+ ixLog = { 0: Date.now(), 1: String(category), 2: String(action), 3: typeof data === 'object' ? JSON.stringify(data) : String(data) };
193
329
  } else {
194
330
  ixLog = { 0: Date.now(), 1: String(category), 2: String(action), 3: null };
195
331
  }
@@ -213,28 +349,32 @@ export class TimeAnalyticsService {
213
349
  // On visibility change to hidden, get latest stuff from session and
214
350
  // save it to the backend. Note that we are not deleting from localStorage
215
351
  // so that there is a backup.
216
- document.addEventListener('visibilitychange', () => {
217
- if (document.visibilityState === 'hidden') {
218
- const timeAtRoute = this.local.getItemForSession(this.TIME_KEY);
219
- // console.log('VISIBILITY CHANGE', timeAtRoute);
220
- if (timeAtRoute &&
221
- Object.prototype.hasOwnProperty.call(timeAtRoute, '__sessionId') &&
222
- Object.prototype.hasOwnProperty.call(timeAtRoute, 'route') &&
223
- Object.prototype.hasOwnProperty.call(timeAtRoute, 'startTime')
224
- ) {
225
- const interactionsAtRoute = this.local.getItemForSession(this.IX_KEY);
226
- if (!interactionsAtRoute) {
227
- this.log.rawLogOnBeaconEvent(timeAtRoute);
228
- } else {
229
- this.log.rawLogOnBeaconEvent({
230
- ...timeAtRoute,
231
- interactions: interactionsAtRoute,
232
- });
352
+ document.addEventListener(
353
+ 'visibilitychange',
354
+ () => {
355
+ if (document.visibilityState === 'hidden') {
356
+ const timeAtRoute = this.local.getItemForSession(this.TIME_KEY);
357
+ // console.log('VISIBILITY CHANGE', timeAtRoute);
358
+ if (
359
+ timeAtRoute &&
360
+ Object.prototype.hasOwnProperty.call(timeAtRoute, '__sessionId') &&
361
+ Object.prototype.hasOwnProperty.call(timeAtRoute, 'route') &&
362
+ Object.prototype.hasOwnProperty.call(timeAtRoute, 'startTime')
363
+ ) {
364
+ const interactionsAtRoute = this.local.getItemForSession(this.IX_KEY);
365
+ if (!interactionsAtRoute) {
366
+ this.log.rawLogOnBeaconEvent(timeAtRoute);
367
+ } else {
368
+ this.log.rawLogOnBeaconEvent({
369
+ ...timeAtRoute,
370
+ interactions: interactionsAtRoute,
371
+ });
372
+ }
233
373
  }
234
374
  }
235
- }
236
- }, { capture: true });
237
-
375
+ },
376
+ { capture: true },
377
+ );
238
378
 
239
379
  /** Event timestamps from the user. */
240
380
  this.eventTimestamps$ = merge(
@@ -247,9 +387,7 @@ export class TimeAnalyticsService {
247
387
  fromEvent(document, 'mousewheel').pipe(debounceTime(100)),
248
388
  fromEvent(document, 'touchmove').pipe(debounceTime(100)),
249
389
  fromEvent(document, 'MSPointerMove').pipe(debounceTime(100)),
250
- ).pipe(
251
- map(() => Date.now()),
252
- );
390
+ ).pipe(map(() => Date.now()));
253
391
 
254
392
  /** Tracks the current route in your app. */
255
393
  this.currentRoute$ = this.router.events.pipe(
@@ -261,100 +399,168 @@ export class TimeAnalyticsService {
261
399
  // Subscribe to make sure it gets the first one
262
400
  this.currentRoute$.subscribe();
263
401
 
264
- /** Tracks the active time at the current route. */
265
- this.runningTimeAtRoute$ = combineLatest([this.eventTimestamps$, this.currentRoute$, this.db.afUser()]).pipe(
402
+ /** Tracks the combined route and registered state. */
403
+ this.routeAndState$ = combineLatest([
404
+ this.currentRoute$,
405
+ this.registeredState$,
406
+ ]).pipe(
407
+ map(([route, state]) => ({ route, state })),
408
+ shareReplay(1),
409
+ );
410
+
411
+ /** Tracks the active time at the current route and registered state. */
412
+ this.runningTimeAtRoute$ = combineLatest([
413
+ this.eventTimestamps$,
414
+ this.routeAndState$,
415
+ this.db.afUser(),
416
+ ]).pipe(
266
417
  pairwise(),
267
- scan((timeAtRoute, [[timestamp1, route1, user1], [timestamp2, route2, user2]]) => {
268
- // Amount of inactive time that indicates not working
269
- // We're using 1 minute for now. Could probably use longer
270
- // cause people are likely to search for things online, and
271
- // that shouldn't count as 'inactive' time
272
- const BREAK_THRESHOLD = 1 * 60 * 1000;
273
- const interval = timestamp2 - timestamp1;
274
- const timeToRecord = interval > BREAK_THRESHOLD ? 0 : interval;
275
- const restToRecord = interval - timeToRecord;
276
-
277
- if (!timeAtRoute) {
278
- // If this is the very first event pair
279
- if (route1 === route2 && ((!user1 && !user2) || (user1 && user2 && user1.uid === user2.uid))) {
280
- return {
281
- ...(user1 && user1.uid ? { __userId: user1.uid } : {}),
282
- route: route1,
283
- startTime: timestamp1,
284
- time: [{
285
- type: 'active',
286
- total: timeToRecord,
287
- }],
288
- };
289
- } else {
290
- return {
291
- ...(user2 && user2.uid ? { __userId: user2.uid } : {}),
292
- route: route2,
293
- startTime: timestamp2,
294
- time: [{
295
- type: 'active',
296
- total: 0,
297
- }],
298
- };
299
- }
300
- } else {
301
- // For the remainder of events: look at the case when route and user are the same, and when there is a difference
302
- if (timeAtRoute.route === route2 && ((!timeAtRoute.__userId && !user2) || (user2 && timeAtRoute.__userId === user2.uid))) {
303
- const recentTimeEntry = timeAtRoute.time[timeAtRoute.time.length - 1];
304
-
305
- if (interval === 0) {
306
- // Some edge cases where the interval could actually be 0
307
- return timeAtRoute;
308
- } else if (recentTimeEntry.type === 'active' && timeToRecord > 0) {
309
- // If this is additional active time, add it to the previous count
310
- const newRecentTimeEntry = {
311
- type: 'active', total: recentTimeEntry.total + timeToRecord,
312
- };
313
- const newTimeArr = [...timeAtRoute.time.slice(0, timeAtRoute.time.length - 1), newRecentTimeEntry];
418
+ scan(
419
+ (
420
+ timeAtRoute,
421
+ [
422
+ [timestamp1, { route: route1, state: state1 }, user1],
423
+ [timestamp2, { route: route2, state: state2 }, user2],
424
+ ],
425
+ ) => {
426
+ // Amount of inactive time that indicates not working
427
+ // We're using 1 minute for now. Could probably use longer
428
+ // cause people are likely to search for things online, and
429
+ // that shouldn't count as 'inactive' time
430
+ const BREAK_THRESHOLD = 1 * 60 * 1000;
431
+ const interval = timestamp2 - timestamp1;
432
+ const timeToRecord = interval > BREAK_THRESHOLD ? 0 : interval;
433
+ const restToRecord = interval - timeToRecord;
434
+
435
+ const isSameRouteUserAndState =
436
+ route1 === route2 &&
437
+ this.isEqualState(state1, state2) &&
438
+ ((!user1 && !user2) || (user1 && user2 && user1.uid === user2.uid));
439
+
440
+ const hasState1 = state1 && Object.keys(state1).length > 0;
441
+ const hasState2 = state2 && Object.keys(state2).length > 0;
314
442
 
443
+ if (!timeAtRoute) {
444
+ // If this is the very first event pair
445
+ if (isSameRouteUserAndState) {
315
446
  return {
316
- ...(timeAtRoute.__userId ? { __userId: timeAtRoute.__userId } : {}),
317
- route: route2,
318
- startTime: timeAtRoute.startTime,
319
- time: newTimeArr,
447
+ ...(user1 && user1.uid ? { __userId: user1.uid } : {}),
448
+ route: route1,
449
+ ...(hasState1 ? { state: state1 } : {}),
450
+ startTime: timestamp1,
451
+ time: [
452
+ {
453
+ type: 'active',
454
+ total: timeToRecord,
455
+ },
456
+ ],
320
457
  };
321
- } else if (recentTimeEntry.type === 'rest' && timeToRecord > 0) {
322
- // If this is new active time, make a new entry
323
- const newTimeArr = [...timeAtRoute.time, {
324
- type: 'active', total: timeToRecord,
325
- }];
326
-
458
+ } else {
327
459
  return {
328
- ...(timeAtRoute.__userId ? { __userId: timeAtRoute.__userId } : {}),
460
+ ...(user2 && user2.uid ? { __userId: user2.uid } : {}),
329
461
  route: route2,
330
- startTime: timeAtRoute.startTime,
331
- time: newTimeArr,
462
+ ...(hasState2 ? { state: state2 } : {}),
463
+ startTime: timestamp2,
464
+ time: [
465
+ {
466
+ type: 'active',
467
+ total: 0,
468
+ },
469
+ ],
332
470
  };
333
- } else {
334
- // If this is rest time, make a new entry
335
- const newTimeArr = [...timeAtRoute.time, {
336
- type: 'rest', total: restToRecord,
337
- }];
471
+ }
472
+ } else {
473
+ // For the remainder of events: look at the case when route, state, and user are the same, and when there is a difference
474
+ const isSameAsCurrent =
475
+ timeAtRoute.route === route2 &&
476
+ this.isEqualState(timeAtRoute.state, state2) &&
477
+ ((!timeAtRoute.__userId && !user2) ||
478
+ (user2 && timeAtRoute.__userId === user2.uid));
479
+
480
+ if (isSameAsCurrent) {
481
+ const recentTimeEntry =
482
+ timeAtRoute.time[timeAtRoute.time.length - 1];
338
483
 
484
+ if (interval === 0) {
485
+ // Some edge cases where the interval could actually be 0
486
+ return timeAtRoute;
487
+ } else if (recentTimeEntry.type === 'active' && timeToRecord > 0) {
488
+ // If this is additional active time, add it to the previous count
489
+ const newRecentTimeEntry = {
490
+ type: 'active',
491
+ total: recentTimeEntry.total + timeToRecord,
492
+ };
493
+ const newTimeArr = [
494
+ ...timeAtRoute.time.slice(0, timeAtRoute.time.length - 1),
495
+ newRecentTimeEntry,
496
+ ];
497
+
498
+ return {
499
+ ...(timeAtRoute.__userId ?
500
+ { __userId: timeAtRoute.__userId } :
501
+ {}),
502
+ route: route2,
503
+ ...(hasState2 ? { state: state2 } : {}),
504
+ startTime: timeAtRoute.startTime,
505
+ time: newTimeArr,
506
+ };
507
+ } else if (recentTimeEntry.type === 'rest' && timeToRecord > 0) {
508
+ // If this is new active time, make a new entry
509
+ const newTimeArr = [
510
+ ...timeAtRoute.time,
511
+ {
512
+ type: 'active',
513
+ total: timeToRecord,
514
+ },
515
+ ];
516
+
517
+ return {
518
+ ...(timeAtRoute.__userId ?
519
+ { __userId: timeAtRoute.__userId } :
520
+ {}),
521
+ route: route2,
522
+ ...(hasState2 ? { state: state2 } : {}),
523
+ startTime: timeAtRoute.startTime,
524
+ time: newTimeArr,
525
+ };
526
+ } else {
527
+ // If this is rest time, make a new entry
528
+ const newTimeArr = [
529
+ ...timeAtRoute.time,
530
+ {
531
+ type: 'rest',
532
+ total: restToRecord,
533
+ },
534
+ ];
535
+
536
+ return {
537
+ ...(timeAtRoute.__userId ?
538
+ { __userId: timeAtRoute.__userId } :
539
+ {}),
540
+ route: route2,
541
+ ...(hasState2 ? { state: state2 } : {}),
542
+ startTime: timeAtRoute.startTime,
543
+ time: newTimeArr,
544
+ };
545
+ }
546
+ } else {
339
547
  return {
340
- ...(timeAtRoute.__userId ? { __userId: timeAtRoute.__userId } : {}),
548
+ ...(user2 && user2.uid ? { __userId: user2.uid } : {}),
341
549
  route: route2,
342
- startTime: timeAtRoute.startTime,
343
- time: newTimeArr,
550
+ ...(hasState2 ? { state: state2 } : {}),
551
+ startTime: timestamp2,
552
+ time: [
553
+ {
554
+ type: 'active',
555
+ total: 0,
556
+ },
557
+ ],
344
558
  };
345
559
  }
346
- } else {
347
- return {
348
- ...(user2 && user2.uid ? { __userId: user2.uid } : {}),
349
- route: route2,
350
- startTime: timestamp2,
351
- time: [{
352
- type: 'active', total: 0,
353
- }],
354
- };
355
560
  }
356
- }
357
- }, undefined),
561
+ },
562
+ undefined,
563
+ ),
358
564
  map((timeAtRoute) => {
359
565
  // Add in the __sessionId, __deviceId for each timeAtRoute
360
566
  return {
@@ -4,7 +4,7 @@ import { filter, switchMap, take } from 'rxjs/operators';
4
4
  import { toObservable } from '@angular/core/rxjs-interop';
5
5
  import { User } from '../store/user/user.model';
6
6
  import { AuthStore } from '../store/auth/auth.store';
7
- import { DATABASE_SERVICE } from '../firebase/database.service';
7
+ import { AuthSession, DATABASE_SERVICE } from '../firebase/database.service';
8
8
 
9
9
  /**
10
10
  * Shared authentication service used by all functional guards.
@@ -22,6 +22,11 @@ export class AuthService {
22
22
  /** Firebase auth user stream (null when signed out). */
23
23
  readonly afUser$ = this.db.afUser();
24
24
 
25
+ /** Resolves Firebase session metadata for guards that enforce provider state. */
26
+ resolveSession(): Observable<AuthSession | null> {
27
+ return this.afUser$.pipe(take(1));
28
+ }
29
+
25
30
  /**
26
31
  * Database User record stream. Only emits once the AuthStore has loaded
27
32
  * a non-null user value. This is safe to use in guards that already know