@tech4good/angular-schematics 13.6.0 → 13.7.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 (106) hide show
  1. package/package.json +1 -1
  2. package/src/component/files/__name@dasherize__/__name@dasherize__.component.ts.template +8 -8
  3. package/src/container/files/__name@dasherize__/+state/__name@dasherize__.actions.ts.template +3 -2
  4. package/src/container/files/__name@dasherize__/+state/__name@dasherize__.effects.ts.template +6 -5
  5. package/src/container/files/__name@dasherize__/+state/__name@dasherize__.selectors.ts.template +2 -2
  6. package/src/container/files/__name@dasherize__/__name@dasherize__.component.ts.template +25 -14
  7. package/src/container/index.js +13 -2
  8. package/src/container/index.js.map +1 -1
  9. package/src/entity/files/__name@dasherize__/__name@dasherize__.actions.ts.template +9 -30
  10. package/src/entity/files/__name@dasherize__/__name@dasherize__.effects.ts.template +23 -24
  11. package/src/init/files/package.json.template +3 -1
  12. package/src/init/files/src/app/admin/admin-routing.module.ts.template +17 -0
  13. package/src/init/files/src/app/admin/admin.module.spec.ts.template +13 -0
  14. package/src/init/files/src/app/admin/admin.module.ts.template +28 -0
  15. package/src/init/files/src/app/admin/waitlist/+state/waitlist.actions.ts.template +23 -0
  16. package/src/init/files/src/app/admin/waitlist/+state/waitlist.effects.ts.template +50 -0
  17. package/src/init/files/src/app/admin/waitlist/+state/waitlist.selectors.ts.template +39 -0
  18. package/src/init/files/src/app/admin/waitlist/+state/waitlist.state.ts.template +13 -0
  19. package/src/init/files/src/app/admin/waitlist/waitlist.animations.ts.template +4 -0
  20. package/src/init/files/src/app/admin/waitlist/waitlist.component.html.template +30 -0
  21. package/src/init/files/src/app/admin/waitlist/waitlist.component.scss.template +14 -0
  22. package/src/init/files/src/app/admin/waitlist/waitlist.component.spec.ts.template +25 -0
  23. package/src/init/files/src/app/admin/waitlist/waitlist.component.ts.template +136 -0
  24. package/src/init/files/src/app/app-routing.module.ts.template +13 -5
  25. package/src/init/files/src/app/core/analytics/log.service.ts.template +89 -4
  26. package/src/init/files/src/app/core/analytics/time-analytics.service.ts.template +204 -69
  27. package/src/init/files/src/app/core/auth/auth.guard.ts.template +85 -0
  28. package/src/init/files/src/app/core/core.module.ts.template +4 -0
  29. package/src/init/files/src/app/core/firebase/firebase.service.ts.template +4 -4
  30. package/src/init/files/src/app/core/local-storage/local-storage.service.ts.template +47 -0
  31. package/src/init/files/src/app/core/local-storage/session-local-storage.service.ts.template +67 -0
  32. package/src/init/files/src/app/core/local-storage/session.service.ts.template +48 -0
  33. package/src/init/files/src/app/core/store/app-state/app-state.actions.ts.template +270 -0
  34. package/src/init/files/src/app/core/store/app-state/app-state.effects.ts.template +131 -0
  35. package/src/init/files/src/app/core/store/app-state/app-state.model.ts.template +8 -0
  36. package/src/init/files/src/app/core/store/app-state/app-state.reducer.spec.ts.template +13 -0
  37. package/src/init/files/src/app/core/store/app-state/app-state.reducer.ts.template +51 -0
  38. package/src/init/files/src/app/core/store/app-state/app-state.service.ts.template +50 -0
  39. package/src/init/files/src/app/core/store/app.effects.ts.template +10 -2
  40. package/src/init/files/src/app/core/store/app.reducer.ts.template +6 -0
  41. package/src/init/files/src/app/core/store/app.selectors.ts.template +12 -0
  42. package/src/init/files/src/app/core/store/auth/auth.actions.ts.template +3 -1
  43. package/src/init/files/src/app/core/store/auth/auth.effects.ts.template +27 -31
  44. package/src/init/files/src/app/core/store/auth/auth.reducer.ts.template +1 -1
  45. package/src/init/files/src/app/core/store/auth/auth.selectors.ts.template +5 -1
  46. package/src/init/files/src/app/core/store/cached-load-connections.service.ts.template +9 -8
  47. package/src/init/files/src/app/core/store/user/user.model.ts.template +14 -0
  48. package/src/init/files/src/app/core/store/user-context/user-context.actions.ts.template +270 -0
  49. package/src/init/files/src/app/core/store/user-context/user-context.effects.ts.template +131 -0
  50. package/src/init/files/src/app/core/store/user-context/user-context.model.ts.template +13 -0
  51. package/src/init/files/src/app/core/store/user-context/user-context.reducer.spec.ts.template +13 -0
  52. package/src/init/files/src/app/core/store/user-context/user-context.reducer.ts.template +51 -0
  53. package/src/init/files/src/app/core/store/user-context/user-context.service.ts.template +50 -0
  54. package/src/init/files/src/app/general/general-routing.module.ts.template +6 -2
  55. package/src/init/files/src/app/general/general.module.ts.template +8 -2
  56. package/src/init/files/src/app/general/home/+state/home.actions.ts.template +26 -0
  57. package/src/init/files/src/app/general/home/+state/home.effects.ts.template +48 -0
  58. package/src/init/files/src/app/general/home/+state/home.model.ts.template +0 -0
  59. package/src/init/files/src/app/general/home/+state/home.selectors.ts.template +20 -0
  60. package/src/init/files/src/app/general/home/+state/home.state.ts.template +13 -0
  61. package/src/init/files/src/app/general/home/home.animations.ts.template +4 -0
  62. package/src/init/files/src/app/general/home/home.component.html.template +5 -0
  63. package/src/init/files/src/app/general/home/home.component.scss.template +5 -0
  64. package/src/init/files/src/app/general/{e404/e404.component.spec.ts.template → home/home.component.spec.ts.template} +6 -6
  65. package/src/init/files/src/app/general/home/home.component.ts.template +88 -0
  66. package/src/init/files/src/app/general/landing/+state/landing.actions.ts.template +26 -0
  67. package/src/init/files/src/app/general/landing/+state/landing.effects.ts.template +48 -0
  68. package/src/init/files/src/app/general/landing/+state/landing.model.ts.template +0 -0
  69. package/src/init/files/src/app/general/landing/+state/landing.selectors.ts.template +20 -0
  70. package/src/init/files/src/app/general/landing/+state/landing.state.ts.template +13 -0
  71. package/src/init/files/src/app/general/landing/landing.animations.ts.template +4 -0
  72. package/src/init/files/src/app/general/landing/landing.component.html.template +3 -0
  73. package/src/init/files/src/app/general/landing/landing.component.scss.template +13 -0
  74. package/src/init/files/src/app/general/landing/landing.component.spec.ts.template +25 -0
  75. package/src/init/files/src/app/general/landing/landing.component.ts.template +98 -0
  76. package/src/init/files/src/app/general/login/login.component.html.template +5 -5
  77. package/src/init/files/src/app/general/login/login.component.ts.template +12 -4
  78. package/src/init/files/src/app/onboarding/consent/+state/consent.actions.ts.template +23 -0
  79. package/src/init/files/src/app/onboarding/consent/+state/consent.effects.ts.template +47 -0
  80. package/src/init/files/src/app/onboarding/consent/+state/consent.model.ts.template +0 -0
  81. package/src/init/files/src/app/onboarding/consent/+state/consent.selectors.ts.template +20 -0
  82. package/src/init/files/src/app/onboarding/consent/+state/consent.state.ts.template +13 -0
  83. package/src/init/files/src/app/onboarding/consent/consent.animations.ts.template +4 -0
  84. package/src/init/files/src/app/onboarding/consent/consent.component.html.template +61 -0
  85. package/src/init/files/src/app/onboarding/consent/consent.component.scss.template +77 -0
  86. package/src/init/files/src/app/onboarding/consent/consent.component.spec.ts.template +25 -0
  87. package/src/init/files/src/app/onboarding/consent/consent.component.ts.template +152 -0
  88. package/src/init/files/src/app/onboarding/onboarding-routing.module.ts.template +19 -0
  89. package/src/init/files/src/app/onboarding/onboarding.module.spec.ts.template +13 -0
  90. package/src/init/files/src/app/onboarding/onboarding.module.ts.template +32 -0
  91. package/src/init/files/src/app/onboarding/waiting/+state/waiting.actions.ts.template +26 -0
  92. package/src/init/files/src/app/onboarding/waiting/+state/waiting.effects.ts.template +52 -0
  93. package/src/init/files/src/app/onboarding/waiting/+state/waiting.model.ts.template +9 -0
  94. package/src/init/files/src/app/onboarding/waiting/+state/waiting.selectors.ts.template +42 -0
  95. package/src/init/files/src/app/onboarding/waiting/+state/waiting.state.ts.template +13 -0
  96. package/src/init/files/src/app/onboarding/waiting/waiting.animations.ts.template +4 -0
  97. package/src/init/files/src/app/onboarding/waiting/waiting.component.html.template +57 -0
  98. package/src/init/files/src/app/onboarding/waiting/waiting.component.scss.template +99 -0
  99. package/src/init/files/src/app/onboarding/waiting/waiting.component.spec.ts.template +25 -0
  100. package/src/init/files/src/app/onboarding/waiting/waiting.component.ts.template +279 -0
  101. package/src/init/files/src/app/shared/shared.module.ts.template +3 -0
  102. package/src/init/files/src/index.html.template +0 -3
  103. package/src/module/files/__name@dasherize__/__name@dasherize__-routing.module.ts.template +2 -0
  104. package/src/init/files/src/app/general/e404/e404.component.html.template +0 -1
  105. package/src/init/files/src/app/general/e404/e404.component.ts.template +0 -28
  106. /package/src/init/files/src/app/{general/e404/e404.component.scss.template → admin/waitlist/+state/waitlist.model.ts.template} +0 -0
@@ -1,26 +1,65 @@
1
1
  import { Injectable } from '@angular/core';
2
2
  import { Router, NavigationEnd } from '@angular/router';
3
3
  import { Subject, Observable, ConnectableObservable, fromEvent, merge, combineLatest } from 'rxjs';
4
- import { startWith, withLatestFrom, tap, takeUntil, switchMap, mergeMap, publishReplay, filter, map, pairwise, scan } from 'rxjs/operators';
4
+ import { startWith, withLatestFrom, tap, takeUntil, switchMap, debounceTime, mergeMap, publishReplay, filter, map, pairwise, scan } from 'rxjs/operators';
5
5
  import { FirebaseService } from '../firebase/firebase.service';
6
6
  import { LogService } from './log.service';
7
+ import { SessionLocalStorageService } from '../local-storage/session-local-storage.service';
8
+ import { SessionService } from '../local-storage/session.service';
7
9
 
8
10
  export interface TimeAtRoute {
11
+ __userId?: string;
12
+ __sessionId: string; // unique for a given session/tab
13
+ __deviceId: string; // unique for the device
9
14
  route: string;
10
15
  startTime: number;
11
16
  time: Array<{ type: string, total: number }>;
12
17
  }
13
18
 
14
- export interface InteractionsAtRoute {
15
- route: string;
16
- // We use this typing since Firebase doesn't accept nested arrays
17
- interactions: Array<{ 0: number, 1: string, 2: string, 3: string }>;
19
+ // We use this typing since Firebase doesn't accept nested arrays
20
+ export interface Interaction {
21
+ 0: number;
22
+ 1: string;
23
+ 2: string;
24
+ 3: string;
18
25
  }
19
26
 
27
+ /**
28
+ * When the application starts and SessionService is initialized, we:
29
+ * - get the stored sessionId or create one ourselves,
30
+ * - get the stored deviceId or create one ourselves
31
+ *
32
+ * When the application starts and TimeAnalytics is initialized, we:
33
+ * - add an eventlistener for "visibilitychange" to sendBeacon when user leaves
34
+ * - define the event stream (this.eventTimestamps$),
35
+ * - 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
38
+ * each event, and adding in __userId, __sessionId, __deviceId
39
+ *
40
+ * Then when startTimeLogging is called in the app init, we:
41
+ * - first handle any logs in localStorage that never got saved to the DB due to
42
+ * refresh/close/etc. and clear localStorage
43
+ * - subscribe to this.runningTimeAtRoute$, saving latest to localStorage, then
44
+ * filtering to only when the route or user changes and when total time is
45
+ * non-zero to log to the DB. When saving, reset the interactionsAtRoute and
46
+ * remove interactions from localStorage
47
+ *
48
+ * When registerInteractions is called anywhere in the app, we:
49
+ * - subscribe to the interaction observables passed in
50
+ * - whenever an event comes into one of those observables, we update it within a
51
+ * local variable as well as in localStorage. The local variable is used when
52
+ * saving to the DB on route/user changes and the localStorage variable is used
53
+ * when retrieving and saving prior logs on a new session.
54
+ */
20
55
  @Injectable({
21
56
  providedIn: 'root',
22
57
  })
23
58
  export class TimeAnalyticsService {
59
+ /** Local storage keys for storing unsaved log data. */
60
+ private TIME_KEY = 'timeAtRoute';
61
+ private IX_KEY = 'interactionsAtRoute';
62
+
24
63
  /** Timestamps for all the main user events. */
25
64
  private eventTimestamps$: Observable<number>;
26
65
 
@@ -30,46 +69,96 @@ export class TimeAnalyticsService {
30
69
  /** The running update of time analytics for each route. */
31
70
  private runningTimeAtRoute$: Observable<TimeAtRoute>;
32
71
 
33
- /** Only the final time analytics for each route (after navigating to next). */
34
- private timeAtRoute$: Observable<TimeAtRoute>;
35
-
36
72
  /** Events representing different registered interactions. */
37
73
  private interactions$: Subject<string> = new Subject<string>();
38
74
 
39
- /** Current interactionsAtRoute data. */
40
- private interactionsAtRoute: InteractionsAtRoute;
75
+ /** Interactions data at latest route. */
76
+ private interactionsAtRoute: Interaction[] = null;
77
+
78
+ /**
79
+ * Helper function for getting a log id to make sure we don't save two logs
80
+ * of the same session at the same time
81
+ */
82
+ private getLogId(data) {
83
+ return `${data.__sessionId}__${data.startTime}`;
84
+ }
85
+
86
+ /** Helper function for saving log to DB given timeAtRoute, interactionsAtRoute. */
87
+ private saveLogToDB(timeAtRoute: TimeAtRoute, interactionsAtRoute: Interaction[]) {
88
+ if (timeAtRoute) {
89
+ if (!interactionsAtRoute) {
90
+ this.log.rawLog(timeAtRoute, 'logs', this.getLogId(timeAtRoute));
91
+ } else {
92
+ this.log.rawLog({
93
+ ...timeAtRoute,
94
+ interactions: interactionsAtRoute,
95
+ }, 'logs', this.getLogId(timeAtRoute));
96
+ }
97
+ }
98
+ }
99
+
100
+ /** Function that checks for any prior session logs unsaved to DB, called in startTimeLogging only. */
101
+ private handlePriorSessionLogs() {
102
+ // Check if there are any unsaved logs in localStorage. If so, save to firebase
103
+ // Note that there could be multiple because there could be multiple tabs/windows
104
+ // open on the same browser. Also note that we save and remove ALL of them,
105
+ // including ones that could be currently active. This is ok because it just
106
+ // means we're saving an early version of the log to the DB which will get
107
+ // overwritten later (we can't distinguish between an active session and an
108
+ // inactive one, so we just have to process them all).
109
+
110
+ for (const timeAtRoute of this.local.getItemForAllSessions(this.TIME_KEY)) {
111
+ // console.log('GET PRIOR SESSION LOG', timeAtRoute);
112
+
113
+ // Safety check that it really is our data
114
+ if (Object.prototype.hasOwnProperty.call(timeAtRoute, '__sessionId') &&
115
+ Object.prototype.hasOwnProperty.call(timeAtRoute, 'route') &&
116
+ Object.prototype.hasOwnProperty.call(timeAtRoute, 'startTime')
117
+ ) {
118
+ const interactionsAtRoute = this.local.getItemForSession(this.IX_KEY, timeAtRoute.__sessionId);
119
+ // console.log('SAVE PRIOR SESSION LOG', timeAtRoute, interactionsAtRoute);
120
+ this.saveLogToDB(timeAtRoute, interactionsAtRoute);
121
+ }
122
+ }
123
+
124
+ // Remove old keys from localStorage.
125
+ this.local.removeItemForAllSessions(this.TIME_KEY);
126
+ this.local.removeItemForAllSessions(this.IX_KEY);
127
+ }
41
128
 
42
129
  /** Function that is called by the app to start analytics. */
43
130
  public startTimeLogging() {
44
- // Start logging time
45
- this.timeAtRoute$.pipe(
46
- withLatestFrom(this.db.afUser()),
47
- ).subscribe(([timeAtRoute, user]: [TimeAtRoute, { uid: string }]) => {
48
- if (user && user.uid) {
49
- if (!this.interactionsAtRoute || !this.interactionsAtRoute.interactions) {
50
- this.log.rawLog({
51
- __userId: user.uid,
52
- ...timeAtRoute,
53
- });
54
- } else if (timeAtRoute.route === this.interactionsAtRoute.route) {
55
- this.log.rawLog({
56
- __userId: user.uid,
57
- ...timeAtRoute,
58
- interactions: this.interactionsAtRoute.interactions,
59
- });
60
- } else {
61
- console.log('ERROR in time-analytics. Why does route not match?');
62
- }
63
- }
64
- });
131
+ // console.log('START TIME LOGGING');
132
+
133
+ // Handle any unstored logs from prior session
134
+ this.handlePriorSessionLogs();
65
135
 
66
- this.currentRoute$.pipe(
67
- startWith(null as string),
136
+ // 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
137
+ this.runningTimeAtRoute$.pipe(
68
138
  pairwise(),
69
- ).subscribe(([route1, route2]) => {
70
- if (!route1 || route1 !== route2) {
71
- this.interactionsAtRoute = { route: route2, interactions: null };
72
- }
139
+ // Save the latest timeAtRoute to localStorage in case we're interrupted
140
+ tap(([timeAtRoute1, timeAtRoute2]) => {
141
+ // console.log('SET SESSION LOG', timeAtRoute2);
142
+ this.local.setItemForSession(this.TIME_KEY, timeAtRoute2);
143
+ }),
144
+ filter(([timeAtRoute1, timeAtRoute2]) => {
145
+ return timeAtRoute2.route !== timeAtRoute1.route || timeAtRoute2.__userId !== timeAtRoute1.__userId;
146
+ }),
147
+ filter(([timeAtRoute1, timeAtRoute2]) => {
148
+ const total = timeAtRoute1.time.reduce((x, y) => {
149
+ return x + y.total;
150
+ }, 0);
151
+ return total > 0;
152
+ }),
153
+ ).subscribe(([timeAtRoute1, timeAtRoute2]) => {
154
+ // Log the completed log (currently only for logged in users)
155
+ // console.log('SAVE LOG TO DB', timeAtRoute1, this.interactionsAtRoute);
156
+ this.saveLogToDB(timeAtRoute1, this.interactionsAtRoute);
157
+
158
+ // Reset the interactions. Note we do null rather than empty array
159
+ // so that we don't add that field when there are no interactions
160
+ this.interactionsAtRoute = null;
161
+ this.local.removeItemForSession(this.IX_KEY);
73
162
  });
74
163
  }
75
164
 
@@ -80,6 +169,7 @@ export class TimeAnalyticsService {
80
169
  ) {
81
170
  for (const ix of interactions) {
82
171
  // Subscribe to each interaction until unsubscribe, and register that the event occured
172
+ // console.log('REGISTER INTERACTION', `${ix[0]}-${ix[1]}`);
83
173
  ix[2].pipe(
84
174
  takeUntil(unsubscribe$),
85
175
  ).subscribe((data) => {
@@ -89,11 +179,15 @@ export class TimeAnalyticsService {
89
179
  } else {
90
180
  ixLog = { 0: Date.now(), 1: String(ix[0]), 2: String(ix[1]), 3: null };
91
181
  }
92
- if (!this.interactionsAtRoute || !this.interactionsAtRoute.interactions) {
182
+ if (!this.interactionsAtRoute) {
93
183
  const newInteractions: Array<{ 0: number, 1: string, 2: string, 3: string }> = [ixLog];
94
- this.interactionsAtRoute.interactions = newInteractions;
184
+ this.interactionsAtRoute = newInteractions;
185
+ this.local.setItemForSession(this.IX_KEY, this.interactionsAtRoute);
186
+ // console.log('UPDATE INTERACTIONS', this.interactionsAtRoute);
95
187
  } else {
96
- this.interactionsAtRoute.interactions.push(ixLog);
188
+ this.interactionsAtRoute.push(ixLog);
189
+ this.local.setItemForSession(this.IX_KEY, this.interactionsAtRoute);
190
+ // console.log('UPDATE INTERACTIONS', this.interactionsAtRoute);
97
191
  }
98
192
  });
99
193
  }
@@ -103,18 +197,46 @@ export class TimeAnalyticsService {
103
197
  private router: Router,
104
198
  private db: FirebaseService,
105
199
  private log: LogService,
200
+ private local: SessionLocalStorageService,
201
+ private session: SessionService,
106
202
  ) {
203
+ // On visibility change to hidden, get latest stuff from session and
204
+ // save it to the backend. Note that we are not deleting from localStorage
205
+ // so that there is a backup.
206
+ document.addEventListener('visibilitychange', () => {
207
+ if (document.visibilityState === 'hidden') {
208
+ const timeAtRoute = this.local.getItemForSession(this.TIME_KEY);
209
+ // console.log('VISIBILITY CHANGE', timeAtRoute);
210
+ if (timeAtRoute &&
211
+ Object.prototype.hasOwnProperty.call(timeAtRoute, '__sessionId') &&
212
+ Object.prototype.hasOwnProperty.call(timeAtRoute, 'route') &&
213
+ Object.prototype.hasOwnProperty.call(timeAtRoute, 'startTime')
214
+ ) {
215
+ const interactionsAtRoute = this.local.getItemForSession(this.IX_KEY);
216
+ if (!interactionsAtRoute) {
217
+ this.log.rawLogOnBeaconEvent(timeAtRoute, 'logs', this.getLogId(timeAtRoute));
218
+ } else {
219
+ this.log.rawLogOnBeaconEvent({
220
+ ...timeAtRoute,
221
+ interactions: interactionsAtRoute,
222
+ }, 'logs', this.getLogId(timeAtRoute));
223
+ }
224
+ }
225
+ }
226
+ }, { capture: true });
227
+
228
+
107
229
  /** Event timestamps from the user. */
108
230
  this.eventTimestamps$ = merge(
109
- fromEvent(document, 'mousemove'),
231
+ fromEvent(document, 'mousemove').pipe(debounceTime(100)),
110
232
  fromEvent(document, 'mousedown'),
111
233
  fromEvent(document, 'keypress'),
112
234
  fromEvent(document, 'click'),
113
- fromEvent(document, 'scroll'),
114
- fromEvent(document, 'DOMMouseScroll'),
115
- fromEvent(document, 'mousewheel'),
116
- fromEvent(document, 'touchmove'),
117
- fromEvent(document, 'MSPointerMove'),
235
+ fromEvent(document, 'scroll').pipe(debounceTime(100)),
236
+ fromEvent(document, 'DOMMouseScroll').pipe(debounceTime(100)),
237
+ fromEvent(document, 'mousewheel').pipe(debounceTime(100)),
238
+ fromEvent(document, 'touchmove').pipe(debounceTime(100)),
239
+ fromEvent(document, 'MSPointerMove').pipe(debounceTime(100)),
118
240
  ).pipe(
119
241
  map(() => Date.now()),
120
242
  );
@@ -129,11 +251,10 @@ export class TimeAnalyticsService {
129
251
  // Need to manually connect to make sure it gets the first one
130
252
  this.currentRoute$.connect();
131
253
 
132
-
133
254
  /** Tracks the active time at the current route. */
134
- this.runningTimeAtRoute$ = combineLatest([this.eventTimestamps$, this.currentRoute$]).pipe(
255
+ this.runningTimeAtRoute$ = combineLatest([this.eventTimestamps$, this.currentRoute$, this.db.afUser()]).pipe(
135
256
  pairwise(),
136
- scan((timeAtRoute, [[timestamp1, route1], [timestamp2, route2]]) => {
257
+ scan((timeAtRoute, [[timestamp1, route1, user1], [timestamp2, route2, user2]]) => {
137
258
  // Amount of inactive time that indicates not working
138
259
  // We're using 1 minute for now. Could probably use longer
139
260
  // cause people are likely to search for things online, and
@@ -145,8 +266,9 @@ export class TimeAnalyticsService {
145
266
 
146
267
  if (!timeAtRoute) {
147
268
  // If this is the very first event pair
148
- if (route1 === route2) {
269
+ if (route1 === route2 && ((!user1 && !user2) || (user1 && user2 && user1.uid === user2.uid))) {
149
270
  return {
271
+ ...(user1 && user1.uid ? { __userId: user1.uid } : {}),
150
272
  route: route1,
151
273
  startTime: timestamp1,
152
274
  time: [{
@@ -156,8 +278,9 @@ export class TimeAnalyticsService {
156
278
  };
157
279
  } else {
158
280
  return {
281
+ ...(user2 && user2.uid ? { __userId: user2.uid } : {}),
159
282
  route: route2,
160
- startTime: timestamp1,
283
+ startTime: timestamp2,
161
284
  time: [{
162
285
  type: 'active',
163
286
  total: 0,
@@ -165,8 +288,8 @@ export class TimeAnalyticsService {
165
288
  };
166
289
  }
167
290
  } else {
168
- // For the remainder of events
169
- if (timeAtRoute.route === route2) {
291
+ // For the remainder of events: look at the case when route and user are the same, and when there is a difference
292
+ if (timeAtRoute.route === route2 && ((!timeAtRoute.__userId && !user2) || (user2 && timeAtRoute.__userId === user2.uid))) {
170
293
  const recentTimeEntry = timeAtRoute.time[timeAtRoute.time.length - 1];
171
294
 
172
295
  if (interval === 0) {
@@ -179,22 +302,40 @@ export class TimeAnalyticsService {
179
302
  };
180
303
  const newTimeArr = [...timeAtRoute.time.slice(0, timeAtRoute.time.length - 1), newRecentTimeEntry];
181
304
 
182
- return { route: route2, startTime: timeAtRoute.startTime, time: newTimeArr };
305
+ return {
306
+ ...(timeAtRoute.__userId ? { __userId: timeAtRoute.__userId } : {}),
307
+ route: route2,
308
+ startTime: timeAtRoute.startTime,
309
+ time: newTimeArr,
310
+ };
183
311
  } else if (recentTimeEntry.type === 'rest' && timeToRecord > 0) {
184
312
  // If this is new active time, make a new entry
185
313
  const newTimeArr = [...timeAtRoute.time, {
186
314
  type: 'active', total: timeToRecord,
187
315
  }];
188
- return { route: route2, startTime: timeAtRoute.startTime, time: newTimeArr };
316
+
317
+ return {
318
+ ...(timeAtRoute.__userId ? { __userId: timeAtRoute.__userId } : {}),
319
+ route: route2,
320
+ startTime: timeAtRoute.startTime,
321
+ time: newTimeArr,
322
+ };
189
323
  } else {
190
324
  // If this is rest time, make a new entry
191
325
  const newTimeArr = [...timeAtRoute.time, {
192
326
  type: 'rest', total: restToRecord,
193
327
  }];
194
- return { route: route2, startTime: timeAtRoute.startTime, time: newTimeArr };
328
+
329
+ return {
330
+ ...(timeAtRoute.__userId ? { __userId: timeAtRoute.__userId } : {}),
331
+ route: route2,
332
+ startTime: timeAtRoute.startTime,
333
+ time: newTimeArr,
334
+ };
195
335
  }
196
336
  } else {
197
337
  return {
338
+ ...(user2 && user2.uid ? { __userId: user2.uid } : {}),
198
339
  route: route2,
199
340
  startTime: timestamp2,
200
341
  time: [{
@@ -204,19 +345,13 @@ export class TimeAnalyticsService {
204
345
  }
205
346
  }
206
347
  }, undefined),
207
- );
208
-
209
- this.timeAtRoute$ = this.runningTimeAtRoute$.pipe(
210
- pairwise(),
211
- filter(([timeAtRoute1, timeAtRoute2]) => {
212
- return timeAtRoute2.route !== timeAtRoute1.route;
213
- }),
214
- map(([timeAtRoute1, timeAtRoute2]) => timeAtRoute1),
215
- filter((timeAtRoute: TimeAtRoute) => {
216
- const total = timeAtRoute.time.reduce((x, y) => {
217
- return x + y.total;
218
- }, 0);
219
- return total > 0;
348
+ map((timeAtRoute) => {
349
+ // Add in the __sessionId, __deviceId for each timeAtRoute
350
+ return {
351
+ __sessionId: this.session.getSessionId(),
352
+ __deviceId: this.session.getDeviceId(),
353
+ ...timeAtRoute,
354
+ };
220
355
  }),
221
356
  );
222
357
  }
@@ -0,0 +1,85 @@
1
+ import { Injectable } from '@angular/core';
2
+ import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
3
+ import { of, Observable, forkJoin } from 'rxjs';
4
+ import { combineLatest, tap, filter, switchMap, map, take, pluck, withLatestFrom } from 'rxjs/operators';
5
+ import { select, Store } from '@ngrx/store';
6
+ import { User, AccessState } from '../store/user/user.model';
7
+ import * as fromStore from '../store/app.reducer';
8
+ import * as fromAuth from '../store/auth/auth.reducer';
9
+ import { FirebaseService } from '../firebase/firebase.service';
10
+ import { AuthSelectorsService } from '../store/auth/auth.selectors';
11
+
12
+ @Injectable({
13
+ providedIn: 'root',
14
+ })
15
+ export class AuthGuard implements CanActivate {
16
+ constructor(
17
+ private db: FirebaseService,
18
+ private store: Store<fromStore.State>,
19
+ private router: Router,
20
+ private authSelector: AuthSelectorsService,
21
+ ) { }
22
+
23
+ canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
24
+ return this.db.afUser().pipe(
25
+ switchMap((afUser) => afUser ? this.authSelector.selectAuthUser() : of(null)),
26
+ switchMap((dbUser) => {
27
+ // The overall approach is that we have a sequence of things we need to check (signed in, consent, waiting, walkthrough).
28
+ // - For each, we want to make sure people not past that stage can't see past it,
29
+ // - We also want to make sure people already past that stage get auto-moved past that page,
30
+ // - We preserve queryParams in case we want to support things like referral links in the future,
31
+ // - Admin users are also handled (so that only admin users can go to admin pages, including pages they would
32
+ // typically get rerouted from)
33
+
34
+ // First handle whether users are logged in. If not, go to landing, otherwise skip past landing.
35
+ if (!dbUser && (state.url !== '/' && state.url !== '/landing')) {
36
+ this.router.navigate(['/'], { queryParams: next.queryParams });
37
+ return of(false);
38
+ } else if (!dbUser && (state.url === '/' || state.url === '/landing')) {
39
+ return of(true);
40
+ } else if (dbUser && (state.url === '/' || state.url === '/landing')) {
41
+ this.router.navigate(['/onboarding/consent'], { queryParams: next.queryParams });
42
+ return of(false);
43
+ }
44
+
45
+ // Make sure non-admin users can't visit admin pages and admin users can visit any page
46
+ // Note: this also means there isn't the same auto-redirection/authguard behavior for admins
47
+ if (!dbUser.isAdmin && state.url.startsWith('/admin')) {
48
+ this.router.navigate(['/home'], { queryParams: next.queryParams });
49
+ return of(false);
50
+ } else if (dbUser.isAdmin) {
51
+ return of(true);
52
+ }
53
+
54
+
55
+ // Then handle whether users have consented. If not, go to consent, otherwise skip past consent.
56
+ if ((!dbUser.consented || dbUser.accessState === AccessState.CONSENT) && state.url !== '/onboarding/consent') {
57
+ this.router.navigate(['/onboarding/consent'], { queryParams: next.queryParams });
58
+ return of(false);
59
+ } else if ((!dbUser.consented || dbUser.accessState === AccessState.CONSENT) && state.url === '/onboarding/consent') {
60
+ return of(true);
61
+ } else if (dbUser.consented && dbUser.accessState !== AccessState.CONSENT && state.url === '/onboarding/consent') {
62
+ this.router.navigate(['/onboarding/waiting'], { queryParams: next.queryParams });
63
+ return of(false);
64
+ }
65
+
66
+ // Then handle whether users are past waitlist. If not, go to waiting, otherwise skip past waiting.
67
+ const waitingStates = [AccessState.SUBMIT_INTEREST, AccessState.SUBMIT_DETAILED, AccessState.WAITING];
68
+ if (waitingStates.includes(dbUser.accessState) && state.url !== '/onboarding/waiting') {
69
+ this.router.navigate(['/onboarding/waiting'], { queryParams: next.queryParams });
70
+ return of(false);
71
+ } else if (waitingStates.includes(dbUser.accessState) && state.url === '/onboarding/waiting') {
72
+ return of(true);
73
+ } else if (!waitingStates.includes(dbUser.accessState) && state.url === '/onboarding/waiting') {
74
+ this.router.navigate(['/home'], { queryParams: next.queryParams });
75
+ return of(false);
76
+ }
77
+
78
+ // PLACEHOLDER: Add similar logic to waitlist states if there is an app-specific walkthrough process
79
+
80
+ // For anything else, return true
81
+ return of(true);
82
+ }),
83
+ );
84
+ }
85
+ }
@@ -24,6 +24,8 @@ import { AppEffects } from './store/app.effects';
24
24
  import { AuthEffects } from './store/auth/auth.effects';
25
25
 
26
26
  // Entity Effects
27
+ import { AppStateEffects } from './store/app-state/app-state.effects';
28
+ import { UserContextEffects } from './store/user-context/user-context.effects';
27
29
  import { UserEffects } from './store/user/user.effects';
28
30
 
29
31
  // Service Effects
@@ -54,6 +56,8 @@ import { SnackbarEffects } from './snackbar/snackbar.effects';
54
56
  // Service Effects
55
57
  SnackbarEffects,
56
58
  // Entity Effects
59
+ AppStateEffects,
60
+ UserContextEffects,
57
61
  UserEffects,
58
62
  ]),
59
63
  ],
@@ -128,7 +128,7 @@ export class FirebaseService {
128
128
  queryListStateChanges = <T>(collection, queryParams, queryOptions?) => {
129
129
  let stateChangeObs$;
130
130
 
131
- if (queryParams.length === 0) {
131
+ if (queryParams.length === 0 && (!queryOptions || Object.keys(queryOptions).length === 0)) {
132
132
  stateChangeObs$ = this.afStore.collection<T>(`/${collection}`).stateChanges();
133
133
  } else {
134
134
  stateChangeObs$ = this.afStore.collection<T>(
@@ -150,7 +150,7 @@ export class FirebaseService {
150
150
  };
151
151
 
152
152
  queryListValueChanges = <T>(collection, queryParams, queryOptions?) => {
153
- if (queryParams.length === 0) {
153
+ if (queryParams.length === 0 && (!queryOptions || Object.keys(queryOptions).length === 0)) {
154
154
  return this.afStore.collection<T>(`/${collection}`).valueChanges();
155
155
  } else {
156
156
  return this.afStore.collection<T>(
@@ -250,8 +250,8 @@ export class FirebaseService {
250
250
 
251
251
  addEntity = (collection, entity) => {
252
252
  return from(this.afStore.doc(`/${collection}/${entity.__id}`).set(Object.assign({}, entity, {
253
- _createdAt: firebase.firestore.Timestamp.now(),
254
- _updatedAt: firebase.firestore.Timestamp.now(),
253
+ _createdAt: firebase.firestore.Timestamp.now(), // TODO: update to ServerValue.TIMESTAMP since more accurate
254
+ _updatedAt: firebase.firestore.Timestamp.now(), // TODO: update to ServerValue.TIMESTAMP since more accurate
255
255
  })));
256
256
  };
257
257
 
@@ -0,0 +1,47 @@
1
+ import { Injectable } from '@angular/core';
2
+ import CryptoES from 'crypto-es';
3
+
4
+ // https://javascript.info/localstorage
5
+ @Injectable({
6
+ providedIn: 'root',
7
+ })
8
+ export class LocalStorageService {
9
+ private ENCRYPT_KEY = 'asdfjkl;';
10
+
11
+ constructor() { }
12
+
13
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
14
+ public setItem(key: string, data: any): void {
15
+ localStorage.setItem(key, this.encrypt(JSON.stringify(data)));
16
+ }
17
+
18
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
+ public getItem(key: string): any {
20
+ const data = localStorage.getItem(key) || '';
21
+ if (data) {
22
+ return JSON.parse(this.decrypt(data));
23
+ } else {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ public removeItem(key: string): void {
29
+ localStorage.removeItem(key);
30
+ }
31
+
32
+ public clear() {
33
+ localStorage.clear();
34
+ }
35
+
36
+ // Using encryption following this:
37
+ // https://blog.jscrambler.com/working-with-angular-local-storage
38
+ // https://medium.com/front-end-weekly/refactoring-cryptojs-in-modern-ecmascript-1d4e1837c272
39
+
40
+ private encrypt(txt: string): string {
41
+ return CryptoES.AES.encrypt(txt, this.ENCRYPT_KEY).toString();
42
+ }
43
+
44
+ private decrypt(txtToDecrypt: string) {
45
+ return CryptoES.AES.decrypt(txtToDecrypt, this.ENCRYPT_KEY).toString(CryptoES.enc.Utf8);
46
+ }
47
+ }
@@ -0,0 +1,67 @@
1
+ import { Injectable } from '@angular/core';
2
+ import { SessionService } from './session.service';
3
+ import { LocalStorageService } from './local-storage.service';
4
+
5
+ // The reason why we need these is to hold independent data for each tab.
6
+ // The set/get/removeItemForSession is used when working with the same tab (typically),
7
+ // whereas, the get/remove for all sessions allows one to look at what keys might have
8
+ // been stored in past tabs
9
+ @Injectable({
10
+ providedIn: 'root',
11
+ })
12
+ export class SessionLocalStorageService {
13
+ constructor(
14
+ private session: SessionService,
15
+ private local: LocalStorageService,
16
+ ) { }
17
+
18
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
+ public setItemForSession(key: string, data: any, sessionId?: string): void {
20
+ let keyWithSession;
21
+ if (sessionId) {
22
+ keyWithSession = `${key}__${sessionId}`;
23
+ } else {
24
+ keyWithSession = `${key}__${this.session.getSessionId()}`;
25
+ }
26
+
27
+ this.local.setItem(keyWithSession, data);
28
+ }
29
+
30
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
+ public getItemForSession(key: string, sessionId?: string): any {
32
+ let keyWithSession;
33
+ if (sessionId) {
34
+ keyWithSession = `${key}__${sessionId}`;
35
+ } else {
36
+ keyWithSession = `${key}__${this.session.getSessionId()}`;
37
+ }
38
+
39
+ return this.local.getItem(keyWithSession);
40
+ }
41
+
42
+ public removeItemForSession(key: string, sessionId?: string): void {
43
+ let keyWithSession;
44
+ if (sessionId) {
45
+ keyWithSession = `${key}__${sessionId}`;
46
+ } else {
47
+ keyWithSession = `${key}__${this.session.getSessionId()}`;
48
+ }
49
+
50
+ this.local.removeItem(keyWithSession);
51
+ }
52
+
53
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
54
+ public getItemForAllSessions(key: string): any[] {
55
+ return Object.keys(localStorage)
56
+ .filter((k) => k.startsWith(`${key}__`))
57
+ .map((k) => this.local.getItem(k));
58
+ }
59
+
60
+ public removeItemForAllSessions(key: string): void {
61
+ for (const k of Object.keys(localStorage)) {
62
+ if (k.startsWith(`${key}__`)) {
63
+ this.local.removeItem(k);
64
+ }
65
+ }
66
+ }
67
+ }