@tech4good/angular-schematics 20.1.0 → 20.3.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 (90) hide show
  1. package/.agents/skills/publish-npm/SKILL.md +37 -0
  2. package/.agents/skills/publish-npm/eval.yaml +17 -0
  3. package/.t4g/agent-memory.db +0 -0
  4. package/CHANGELOG.md +66 -0
  5. package/README.md +16 -7
  6. package/changelog.config.json +19 -0
  7. package/contributing-docs/branches-and-releases.md +57 -0
  8. package/contributing-docs/commit-message.md +117 -0
  9. package/package.json +10 -2
  10. package/src/component/files/__name@dasherize__/__name@dasherize__.component.scss.template +1 -0
  11. package/src/component/schema.json +1 -0
  12. package/src/entity/files/__name@dasherize__/__name@dasherize__.mock.ts.template +1 -1
  13. package/src/entity/schema.json +1 -0
  14. package/src/ng-add/files/.gitignore.template +3 -0
  15. package/src/ng-add/files/package.json.template +3 -2
  16. package/src/ng-add/files/public/images/abstract.png +0 -0
  17. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.html.template +27 -22
  18. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.scss.template +35 -4
  19. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.ts.template +31 -75
  20. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.html.template +25 -0
  21. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.scss.template +67 -0
  22. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.ts.template +74 -0
  23. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-count-pill/admin-count-pill.animations.ts.template +4 -0
  24. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-count-pill/admin-count-pill.component.html.template +4 -0
  25. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-count-pill/admin-count-pill.component.scss.template +22 -0
  26. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-count-pill/admin-count-pill.component.spec.ts.template +37 -0
  27. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-count-pill/admin-count-pill.component.ts.template +36 -0
  28. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.animations.ts.template +4 -0
  29. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.component.html.template +11 -0
  30. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.component.scss.template +22 -0
  31. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.component.spec.ts.template +37 -0
  32. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.component.ts.template +47 -0
  33. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.html.template +52 -0
  34. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.scss.template +66 -0
  35. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.ts.template +220 -0
  36. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.animations.ts.template +4 -0
  37. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.html.template +81 -0
  38. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.scss.template +136 -0
  39. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.spec.ts.template +37 -0
  40. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.ts.template +118 -0
  41. package/src/ng-add/files/src/app/app.component.html.template +2 -0
  42. package/src/ng-add/files/src/app/app.component.ts.template +2 -0
  43. package/src/ng-add/files/src/app/app.routes.ts.template +14 -18
  44. package/src/ng-add/files/src/app/core/auth/auth.service.ts.template +58 -0
  45. package/src/ng-add/files/src/app/core/auth/guards/admin-override.ts.template +9 -0
  46. package/src/ng-add/files/src/app/core/auth/guards/index.ts.template +11 -0
  47. package/src/ng-add/files/src/app/core/auth/guards/redirect-if-authenticated.guard.ts.template +42 -0
  48. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.ts.template +39 -0
  49. package/src/ng-add/files/src/app/core/auth/guards/require-auth-and-consent.guard.ts.template +69 -0
  50. package/src/ng-add/files/src/app/core/auth/guards/require-auth.guard.ts.template +35 -0
  51. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +2 -17
  52. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +1 -1
  53. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +7 -1
  54. package/src/ng-add/files/src/app/core/store/app.model.ts.template +1 -1
  55. package/src/ng-add/files/src/app/core/store/app.store.ts.template +71 -6
  56. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +94 -53
  57. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +5 -5
  58. package/src/ng-add/files/src/app/core/store/user/user.model.ts.template +5 -7
  59. package/src/ng-add/files/src/app/core/store/user-context/user-context.mock.ts.template +3 -5
  60. package/src/ng-add/files/src/app/core/store/user-context/user-context.model.ts.template +2 -5
  61. package/src/ng-add/files/src/app/first-time/consent/consent.component.ts.template +4 -3
  62. package/src/ng-add/files/src/app/first-time/consent/consent.guard.ts.template +54 -0
  63. package/src/ng-add/files/src/app/first-time/early-access/early-access.animations.ts.template +6 -0
  64. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.html.template +70 -52
  65. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.scss.template +73 -6
  66. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +59 -111
  67. package/src/ng-add/files/src/app/first-time/early-access/early-access.guard.ts.template +44 -0
  68. package/src/ng-add/files/src/app/first-time/landing/hero/hero.animations.ts.template +15 -0
  69. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.html.template +12 -0
  70. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.scss.template +79 -0
  71. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +20 -0
  72. package/src/ng-add/files/src/app/first-time/landing/landing.component.html.template +1 -1
  73. package/src/ng-add/files/src/app/first-time/landing/landing.component.scss.template +11 -8
  74. package/src/ng-add/files/src/app/first-time/landing/landing.component.ts.template +2 -0
  75. package/src/ng-add/files/src/app/first-time/landing/rotating-quotes/rotating-quotes.component.html.template +3 -0
  76. package/src/ng-add/files/src/app/first-time/landing/rotating-quotes/rotating-quotes.component.scss.template +26 -0
  77. package/src/ng-add/files/src/app/first-time/landing/rotating-quotes/rotating-quotes.component.ts.template +52 -0
  78. package/src/ng-add/files/src/app/shared/dev-status-bar/dev-status-bar.component.html.template +21 -0
  79. package/src/ng-add/files/src/app/shared/dev-status-bar/dev-status-bar.component.scss.template +71 -0
  80. package/src/ng-add/files/src/app/shared/dev-status-bar/dev-status-bar.component.ts.template +70 -0
  81. package/src/ng-add/files/src/app/shared/hint-visibility/hint-visibility.directive.ts.template +131 -0
  82. package/src/ng-add/files/src/app/shared/navbar/navbar.component.html.template +1 -1
  83. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.ts.template +1 -1
  84. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.ts.template +2 -2
  85. package/src/ng-add/files/src/environments/environment.ts.template +1 -1
  86. package/src/ng-add/files/src/index.html.template +3 -2
  87. package/src/ng-add/files/src/styles/_variables.scss.template +1 -0
  88. package/src/ng-add/files/src/styles.scss.template +4 -2
  89. package/src/ng-add/schema.json +1 -0
  90. package/src/ng-add/files/src/app/core/auth/auth.guard.ts.template +0 -96
@@ -0,0 +1,58 @@
1
+ import { inject, Injectable } from '@angular/core';
2
+ import { Observable, of } from 'rxjs';
3
+ import { filter, switchMap, take } from 'rxjs/operators';
4
+ import { toObservable } from '@angular/core/rxjs-interop';
5
+ import { User } from '../store/user/user.model';
6
+ import { AuthStore } from '../store/auth/auth.store';
7
+ import { DATABASE_SERVICE } from '../firebase/database.service';
8
+
9
+ /**
10
+ * Shared authentication service used by all functional guards.
11
+ *
12
+ * Centralises the two key observables (Firebase auth user and database User)
13
+ * so that individual guards don't need to duplicate this setup. Every guard
14
+ * calls `resolveUser()` to get a single-emission observable of the current
15
+ * database user (or null if not authenticated).
16
+ */
17
+ @Injectable({ providedIn: 'root' })
18
+ export class AuthService {
19
+ private readonly authStore = inject(AuthStore);
20
+ private readonly db = inject(DATABASE_SERVICE);
21
+
22
+ /** Firebase auth user stream (null when signed out). */
23
+ readonly afUser$ = this.db.afUser();
24
+
25
+ /**
26
+ * Database User record stream. Only emits once the AuthStore has loaded
27
+ * a non-null user value. This is safe to use in guards that already know
28
+ * the user is authenticated — it will wait until the store is populated
29
+ * rather than emitting a stale `null`.
30
+ */
31
+ readonly user$: Observable<User> = toObservable(this.authStore.user).pipe(
32
+ filter((user): user is User => !!user),
33
+ );
34
+
35
+ /**
36
+ * Resolves the full database user in a single emission.
37
+ *
38
+ * - If the Firebase auth user exists, it first checks the synchronous
39
+ * signal value to bypass the async microtask delay of `toObservable`.
40
+ * This ensures routing guards executing immediately after a state patch
41
+ * do not read a stale state.
42
+ * - If the signal is not yet populated, it waits for the AuthStore to load
43
+ * the database user and takes the first emission.
44
+ * - If not authenticated, emits `null` immediately.
45
+ *
46
+ * This is the primary entry point for all guards.
47
+ */
48
+ resolveUser(): Observable<User | null> {
49
+ return this.afUser$.pipe(
50
+ switchMap((afUser) => {
51
+ if (!afUser) return of(null);
52
+ const currentUser = this.authStore.user();
53
+ if (currentUser) return of(currentUser);
54
+ return this.user$.pipe(take(1));
55
+ }),
56
+ );
57
+ }
58
+ }
@@ -0,0 +1,9 @@
1
+ import { User } from '../../store/user/user.model';
2
+
3
+ /**
4
+ * Helper to check if a user is an admin and has an active route override
5
+ * for the current URL. Used inside guards to short-circuit redirects.
6
+ */
7
+ export function hasAdminOverride(user: User | null | undefined, url: string): boolean {
8
+ return !!(user?.isAdmin && user.adminOverridePaths?.includes(url));
9
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Barrel export for all common auth guards.
3
+ *
4
+ * Common guards live in `core/auth/guards/` and are reusable across many
5
+ * routes. Page-specific guards are co-located with their components.
6
+ */
7
+ export { requireAuth } from './require-auth.guard';
8
+ export { redirectIfAuthenticated } from './redirect-if-authenticated.guard';
9
+ export { requireAdmin } from './require-admin.guard';
10
+ export { requireAuthAndConsent } from './require-auth-and-consent.guard';
11
+ export { hasAdminOverride } from './admin-override';
@@ -0,0 +1,42 @@
1
+ import { inject } from '@angular/core';
2
+ import { CanActivateFn, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
3
+ import { map } from 'rxjs/operators';
4
+ import { AuthService } from '../auth.service';
5
+ import { hasAdminOverride } from './admin-override';
6
+ import { User } from '../../store/user/user.model';
7
+
8
+ /**
9
+ * Redirects already-authenticated users away from public pages (landing,
10
+ * login) to `/home`. Returns `true` only for unauthenticated users,
11
+ * allowing them to view the public page.
12
+ */
13
+ export function handleAccess(
14
+ user: User | null | undefined,
15
+ router: Router,
16
+ route: ActivatedRouteSnapshot,
17
+ state: RouterStateSnapshot
18
+ ): boolean {
19
+ if (user) {
20
+ // Admin override short-circuit
21
+ if (hasAdminOverride(user, state.url)) return true;
22
+
23
+ // Already logged in → send to home
24
+ router.navigate(['/home'], { queryParams: route.queryParams });
25
+ return false;
26
+ }
27
+ return true;
28
+ }
29
+
30
+ /**
31
+ * Route guard that delegates to `handleAccess`.
32
+ */
33
+ export const redirectIfAuthenticated: CanActivateFn = (route, state) => {
34
+ const auth = inject(AuthService);
35
+ const router = inject(Router);
36
+
37
+ return auth.resolveUser().pipe(
38
+ map((user) => {
39
+ return handleAccess(user, router, route, state);
40
+ }),
41
+ );
42
+ };
@@ -0,0 +1,39 @@
1
+ import { inject } from '@angular/core';
2
+ import { CanActivateFn, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
3
+ import { User } from '../../store/user/user.model';
4
+ import { map } from 'rxjs/operators';
5
+ import { AuthService } from '../auth.service';
6
+
7
+ /**
8
+ * Restricts access to admin users only. Non-admin users are redirected
9
+ * to `/home`.
10
+ *
11
+ * This guard should always be placed *after* `requireAuth` in the
12
+ * `canActivate` array, since it assumes the user is already authenticated.
13
+ */
14
+ export function handleAccess(
15
+ user: User | null | undefined,
16
+ router: Router,
17
+ route: ActivatedRouteSnapshot,
18
+ state: RouterStateSnapshot
19
+ ): boolean {
20
+ if (!user?.isAdmin) {
21
+ router.navigate(['/home'], { queryParams: route.queryParams });
22
+ return false;
23
+ }
24
+ return true;
25
+ }
26
+
27
+ /**
28
+ * Route guard that delegates to `handleAccess`.
29
+ */
30
+ export const requireAdmin: CanActivateFn = (route, state) => {
31
+ const auth = inject(AuthService);
32
+ const router = inject(Router);
33
+
34
+ return auth.resolveUser().pipe(
35
+ map((user) => {
36
+ return handleAccess(user, router, route, state);
37
+ }),
38
+ );
39
+ };
@@ -0,0 +1,69 @@
1
+ import { inject } from '@angular/core';
2
+ import { CanActivateFn, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
3
+ import { map } from 'rxjs/operators';
4
+ import { AuthService } from '../auth.service';
5
+ import { AccessState, User } from '../../store/user/user.model';
6
+ import { hasAdminOverride } from './admin-override';
7
+
8
+ /**
9
+ * Combined guard that checks authentication, admin overrides, and full
10
+ * consent completion in a single pass. This avoids resolving the user
11
+ * multiple times when stacking separate guards.
12
+ *
13
+ * Use this on any route that requires the user to be fully through the
14
+ * onboarding pipeline (logged in + waitlist cleared + consented).
15
+ *
16
+ * Checks performed in order:
17
+ * 1. Not logged in → redirect to `/landing`
18
+ * 2. Admin with route in `adminOverridePaths` → allow immediately
19
+ * 3. `accessState` is `SUBMIT_INTEREST` or `WAITING` → redirect to `/early-access`
20
+ * 4. `accessState` is not `DONE` or `consented` is false → redirect to `/consent`
21
+ * 5. Otherwise → allow
22
+ */
23
+ export function handleAccess(
24
+ user: User | null | undefined,
25
+ router: Router,
26
+ route: ActivatedRouteSnapshot,
27
+ state: RouterStateSnapshot
28
+ ): boolean {
29
+ // Step 1: Not logged in → landing
30
+ if (!user) {
31
+ router.navigate(['/landing'], { queryParams: route.queryParams });
32
+ return false;
33
+ }
34
+
35
+ // Step 2: Admin override → bypass all downstream checks
36
+ if (hasAdminOverride(user, state.url)) {
37
+ return true;
38
+ }
39
+
40
+ // Step 3: Still on the waitlist → early-access
41
+ const waitingStates = [AccessState.SUBMIT_INTEREST, AccessState.WAITING];
42
+ if (waitingStates.includes(user.accessState)) {
43
+ router.navigate(['/early-access'], { queryParams: route.queryParams });
44
+ return false;
45
+ }
46
+
47
+ // Step 4: Not fully consented → consent
48
+ if (user.accessState !== AccessState.DONE || !user.consented) {
49
+ router.navigate(['/consent'], { queryParams: route.queryParams });
50
+ return false;
51
+ }
52
+
53
+ // Step 5: Fully through the pipeline → allow
54
+ return true;
55
+ }
56
+
57
+ /**
58
+ * Route guard that delegates to `handleAccess`.
59
+ */
60
+ export const requireAuthAndConsent: CanActivateFn = (route, state) => {
61
+ const auth = inject(AuthService);
62
+ const router = inject(Router);
63
+
64
+ return auth.resolveUser().pipe(
65
+ map((user) => {
66
+ return handleAccess(user, router, route, state);
67
+ }),
68
+ );
69
+ };
@@ -0,0 +1,35 @@
1
+ import { inject } from '@angular/core';
2
+ import { CanActivateFn, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
3
+ import { User } from '../../store/user/user.model';
4
+ import { map } from 'rxjs/operators';
5
+ import { AuthService } from '../auth.service';
6
+
7
+ /**
8
+ * Ensures the user is logged in. If not, redirects to `/landing`.
9
+ */
10
+ export function handleAccess(
11
+ user: User | null | undefined,
12
+ router: Router,
13
+ route: ActivatedRouteSnapshot,
14
+ state: RouterStateSnapshot
15
+ ): boolean {
16
+ if (!user) {
17
+ router.navigate(['/landing'], { queryParams: route.queryParams });
18
+ return false;
19
+ }
20
+ return true;
21
+ }
22
+
23
+ /**
24
+ * Route guard that delegates to `handleAccess`.
25
+ */
26
+ export const requireAuth: CanActivateFn = (route, state) => {
27
+ const auth = inject(AuthService);
28
+ const router = inject(Router);
29
+
30
+ return auth.resolveUser().pipe(
31
+ map((user) => {
32
+ return handleAccess(user, router, route, state);
33
+ }),
34
+ );
35
+ };
@@ -257,26 +257,11 @@ export class CachedListenersService {
257
257
  .filter((dc) => dc.type === 'modified' && dc.docData['_deleted'])
258
258
  .map((dc) => dc.docData['__id']);
259
259
 
260
- // Handle changes of the 'removed' type. In general, firebase 'removed'
261
- // could be due to no longer matching the stream query rather than being
262
- // deleted from the DB. this is why we use soft deletes (set _deleted to true)
263
- // so technically we shouldn't be getting any 'removed' entries. however,
264
- // if there were manual deletions in the database, there could still be changes
265
- // of this type which the below code seeks to handle
266
- const entitiesToModify2 = fbPayload
267
- .filter((dc) => dc.type === 'removed' && !entityInQueryResults(dc.docData, queryParams, queryOptions))
268
- .map((dc) => dc.docData);
269
-
270
-
271
- const entitiesToRemove2 = fbPayload
272
- .filter((dc) => dc.type === 'removed' && entityInQueryResults(dc.docData, queryParams, queryOptions))
273
- .map((dc) => dc.docData['__id']);
274
-
275
260
  // Patch all the changes to the store
276
261
  store.handleStreamChanges(
277
262
  entitiesToAdd,
278
- [...entitiesToModify, ...entitiesToModify2],
279
- [...entitiesToRemove, ...entitiesToRemove2],
263
+ entitiesToModify,
264
+ entitiesToRemove,
280
265
  );
281
266
  });
282
267
 
@@ -52,7 +52,7 @@ export class FirebaseMockService implements DatabaseService {
52
52
  return autoId;
53
53
  }
54
54
 
55
- afUser(): Observable<{ uid: string, accessToken: string, email: string, displayName: string, photoURL: string }> {
55
+ afUser(): Observable<{ uid: string, email: string, displayName: string, photoURL: string }> {
56
56
  return this.user$;
57
57
  }
58
58
 
@@ -151,7 +151,13 @@ export class FirebaseService implements DatabaseService {
151
151
  switch (queryKey) {
152
152
  case 'orderBy': {
153
153
  if (Array.isArray(queryOptions.orderBy)) {
154
- queryArray.push(orderBy(queryOptions.orderBy[0], queryOptions.orderBy[1] as OrderByDirection));
154
+ if (Array.isArray(queryOptions.orderBy[0])) {
155
+ for (const order of queryOptions.orderBy) {
156
+ queryArray.push(orderBy(order[0], order[1] as OrderByDirection));
157
+ }
158
+ } else {
159
+ queryArray.push(orderBy(queryOptions.orderBy[0] as string, queryOptions.orderBy[1] as OrderByDirection));
160
+ }
155
161
  } else {
156
162
  queryArray.push(orderBy(queryOptions.orderBy));
157
163
  }
@@ -10,7 +10,7 @@ export type AnyEntity =
10
10
  export type QueryParams = [string, string, any][];
11
11
 
12
12
  export type QueryOptions = {
13
- orderBy?: string | [string, string],
13
+ orderBy?: string | [string, string] | [string, string][],
14
14
  limit?: number,
15
15
  startAt?: string,
16
16
  startAfter?: string,
@@ -92,15 +92,52 @@ export function withEntitiesAndSelectMethods<S extends AnyEntity>() {
92
92
  );
93
93
  }
94
94
 
95
- export function withEntitiesForMockDB<S extends AnyEntity>() {
95
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
96
+ function serializeMockDBData(data: any): string {
97
+ return JSON.stringify(data, (key, value) => {
98
+ if (value && typeof value === 'object' && 'seconds' in value && 'nanoseconds' in value) {
99
+ return { __type: 'Timestamp', seconds: value.seconds, nanoseconds: value.nanoseconds };
100
+ }
101
+ return value;
102
+ });
103
+ }
104
+
105
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
106
+ function deserializeMockDBData(jsonString: string): any {
107
+ return JSON.parse(jsonString, (key, value) => {
108
+ if (value && typeof value === 'object' && value.__type === 'Timestamp') {
109
+ return new Timestamp(value.seconds, value.nanoseconds);
110
+ }
111
+ return value;
112
+ });
113
+ }
114
+
115
+ export function withEntitiesForMockDB<S extends AnyEntity>(collectionName: string) {
96
116
  return signalStoreFeature(
97
117
  withEntitiesAndSelectMethods<S>(),
98
118
  withMethods((store) => ({
119
+ init(entities: S[]) {
120
+ const saved = localStorage.getItem(`mockDB_${collectionName}`);
121
+ if (saved) {
122
+ patchState(store, setAllEntities<S>(deserializeMockDBData(saved), { selectId }));
123
+ } else {
124
+ patchState(store, setAllEntities<S>(entities, { selectId }));
125
+ }
126
+
127
+ // Listen for changes from other tabs to keep mockDB in sync
128
+ window.addEventListener('storage', (event) => {
129
+ if (event.key === `mockDB_${collectionName}` && event.newValue) {
130
+ patchState(store, setAllEntities<S>(deserializeMockDBData(event.newValue), { selectId }));
131
+ }
132
+ });
133
+ },
99
134
  add(entity: S) {
100
135
  patchState(store, setEntity<S>(entity, { selectId }));
136
+ localStorage.setItem(`mockDB_${collectionName}`, serializeMockDBData(Object.values(store.entityMap())));
101
137
  },
102
138
  update(id: string, changes: Partial<S>) {
103
139
  patchState(store, updateEntity({ id, changes }, { selectId }));
140
+ localStorage.setItem(`mockDB_${collectionName}`, serializeMockDBData(Object.values(store.entityMap())));
104
141
  },
105
142
  })),
106
143
  );
@@ -793,21 +830,49 @@ export function selectEntities<T>(entityMap: Record<string, T>, queryParams: Que
793
830
  // If orderBy is provided, will only return entities with that property
794
831
  // just like the Firestore API
795
832
 
796
- const [field, order] = Array.isArray(queryOptions.orderBy) ? queryOptions.orderBy : [queryOptions.orderBy, 'asc'];
833
+ let orderings: [string, string][] = [];
834
+ if (Array.isArray(queryOptions.orderBy)) {
835
+ if (Array.isArray(queryOptions.orderBy[0])) {
836
+ orderings = queryOptions.orderBy as [string, string][];
837
+ } else {
838
+ orderings = [queryOptions.orderBy as [string, string]];
839
+ }
840
+ } else {
841
+ orderings = [[queryOptions.orderBy as string, 'asc']];
842
+ }
843
+
844
+ // Filter out entities missing any of the orderBy fields
845
+ for (const [field] of orderings) {
846
+ filteredEntities = filteredEntities.filter((e) => e[field] !== undefined && e[field] !== null);
847
+ }
797
848
 
798
- filteredEntities = filteredEntities.filter((e) => e[field] !== undefined && e[field] !== null);
799
849
  filteredEntities.sort((a, b) => {
800
- if (a[field] < b[field]) return order === 'desc' ? 1 : -1;
801
- if (a[field] > b[field]) return order === 'desc' ? -1 : 1;
850
+ for (const [field, order] of orderings) {
851
+ if (a[field] < b[field]) return order === 'desc' ? 1 : -1;
852
+ if (a[field] > b[field]) return order === 'desc' ? -1 : 1;
853
+ }
802
854
  return 0;
803
855
  });
804
856
  }
805
857
 
806
858
  // Filter based on startAt/startAfter/endAt/endAfter
859
+ // Note: Only supports single field orderBy for cursor pagination in local store mock for now
807
860
  if (queryOptions?.orderBy && (queryOptions?.startAt !== undefined || queryOptions?.startAfter !== undefined ||
808
861
  queryOptions?.endAt !== undefined || queryOptions?.endBefore !== undefined)) {
862
+
863
+ let primaryField = '';
864
+ if (Array.isArray(queryOptions.orderBy)) {
865
+ if (Array.isArray(queryOptions.orderBy[0])) {
866
+ primaryField = queryOptions.orderBy[0][0];
867
+ } else {
868
+ primaryField = queryOptions.orderBy[0] as string;
869
+ }
870
+ } else {
871
+ primaryField = queryOptions.orderBy as string;
872
+ }
873
+
809
874
  filteredEntities = filteredEntities.filter((e) => {
810
- const value = e[queryOptions.orderBy as string];
875
+ const value = e[primaryField];
811
876
  if (queryOptions.startAt !== undefined && value < queryOptions.startAt) {
812
877
  return false;
813
878
  }
@@ -1,83 +1,127 @@
1
- import { Inject, inject, effect } from '@angular/core';
2
- import { signalStore, patchState, withState, withMethods } from '@ngrx/signals';
1
+ import { Inject, inject, effect, Injector, computed } from '@angular/core';
2
+ import { signalStore, patchState, withState, withMethods, withComputed } from '@ngrx/signals';
3
3
  import { rxMethod } from '@ngrx/signals/rxjs-interop';
4
4
  import { User, AccessState } from '../user/user.model';
5
5
  import { DATABASE_SERVICE, DatabaseService } from '../../firebase/database.service';
6
- import { firstValueFrom, EMPTY, of, pipe } from 'rxjs';
6
+ import { firstValueFrom, EMPTY, of, pipe, from } from 'rxjs';
7
7
  import { tap, catchError, switchMap, map } from 'rxjs/operators';
8
8
  import { Router } from '@angular/router';
9
+ import { UserStore } from '../user/user.store';
10
+ import { toObservable } from '@angular/core/rxjs-interop';
11
+ import { setEntity } from '@ngrx/signals/entities';
9
12
 
10
13
  type State = {
11
- user: User;
14
+ afUser: { uid: string, email: string, displayName: string, photoURL: string } | null;
12
15
  isLoadingLogin: boolean;
13
16
  }
14
17
 
15
18
  const initialState: State = {
16
- user: null,
19
+ afUser: null,
17
20
  isLoadingLogin: false,
18
21
  };
19
22
 
20
23
  export const AuthStore = signalStore(
21
24
  { providedIn: 'root' },
22
25
  withState(initialState),
23
- withMethods((store, db = inject(DATABASE_SERVICE), router = inject(Router)) => ({
24
- loadAuth: rxMethod<void>(
25
- pipe(
26
- // Every time firebase or db user changes, we want to update auth store
27
- switchMap(() => db.afUser().pipe(
28
- catchError((e) => {
29
- console.error(e);
30
- return EMPTY;
26
+ withComputed((store, userStore = inject(UserStore)) => ({
27
+ user: computed(() => {
28
+ const afUser = store.afUser();
29
+ if (!afUser) return null;
30
+ return userStore.selectEntity(afUser.uid) || null;
31
+ }),
32
+ })),
33
+ withMethods((store, db = inject(DATABASE_SERVICE), router = inject(Router), userStore = inject(UserStore), injector = inject(Injector)) => {
34
+ return {
35
+ loadAuth: rxMethod<void>(
36
+ pipe(
37
+ // 1. Listen for changes in the authenticated Firebase user.
38
+ // This emits immediately if a user is already signed in (from local cache/cookie),
39
+ // or emits whenever they log in or out.
40
+ switchMap(() => db.afUser().pipe(
41
+ catchError((e) => {
42
+ console.error(e);
43
+ return EMPTY;
44
+ }),
45
+ )),
46
+
47
+ // 2. Load the corresponding database User record.
48
+ switchMap((afUser) => {
49
+ if (afUser) {
50
+ // We perform a blocking 'load()' first to ensure the UserStore is populated
51
+ // with the database user data before we continue. This ensures the 'user'
52
+ // computed signal is populated instantly for any route guards.
53
+ return from(userStore.load([['__id', '==', afUser.uid]], {})).pipe(
54
+ switchMap(() => {
55
+ // After the initial load completes, we set up a background 'stream()'.
56
+ // This ensures the UserStore stays continuously in sync with any
57
+ // real-time backend database updates (e.g. from cloud functions).
58
+ userStore.stream([['__id', '==', afUser.uid]], {}, injector);
59
+
60
+ // Pass the afUser down the pipe to the tap() handler.
61
+ return of(afUser);
62
+ }),
63
+ catchError((e) => {
64
+ console.error('[AuthStore loadAuth] streamEntity error:', e);
65
+ return EMPTY;
66
+ }),
67
+ );
68
+ } else {
69
+ // If signed out, just pass null down.
70
+ return of(null);
71
+ }
72
+ }),
73
+
74
+ // 3. Update the local AuthStore state and handle brand new signups.
75
+ tap(async (afUser: any) => {
76
+ if (!afUser) {
77
+ patchState(store, { afUser: null });
78
+ } else {
79
+ patchState(store, { afUser });
80
+ const dbUser = userStore.selectEntity(afUser.uid);
81
+
82
+ if (!dbUser) {
83
+ // afUser exists but dbUser doesn't exist yet, we should create it
84
+ const newUser = {
85
+ __id: afUser.uid,
86
+ email: afUser.email,
87
+ name: afUser.displayName || afUser.email,
88
+ photoURL: afUser.photoURL || null,
89
+ isAdmin: false,
90
+ consented: false,
91
+ accessState: AccessState.SUBMIT_INTEREST,
92
+ };
93
+ try {
94
+ await db.addEntity('users', newUser);
95
+ } catch (e) {
96
+ console.error(`[AuthStore loadAuth] Error creating new user:`, e);
97
+ }
98
+ }
99
+ }
31
100
  }),
32
101
  )),
33
- switchMap((afUser) => {
34
- if (afUser) {
35
- return db.streamEntity('users', afUser.uid).pipe(
36
- map((dbUser) => ({ afUser, dbUser })),
37
- catchError((e) => {
38
- console.error(e);
39
- return EMPTY;
40
- }),
41
- );
42
- } else {
43
- return of({ afUser, dbUser: null });
44
- }
45
- }),
46
- tap(async ({ afUser, dbUser }) => {
47
- if (!afUser) {
48
- patchState(store, { user: undefined });
49
- } else if (afUser && dbUser) {
50
- patchState(store, { user: dbUser });
51
- }
52
- }),
53
- ),
54
- ),
55
102
  async login(provider: string, params: {
56
103
  scope?: string,
57
104
  doNotRoute: boolean
58
105
  } = { doNotRoute: false }): Promise<void> {
59
106
  patchState(store, { isLoadingLogin: true });
60
-
107
+
61
108
  try {
62
109
  const loginResult = await db.login(provider, params.scope);
63
110
  const afUser = loginResult.user;
64
- // could this be problematic if it hits a cached value?
111
+ patchState(store, { afUser });
112
+
65
113
  const dbUser: User = await db.getEntity('users', afUser.uid);
66
114
 
67
115
  const navLocation = ['/home'];
68
- // update the token if there is already a dbUser
116
+ // update the user if there is already a dbUser
69
117
  if (dbUser) {
70
- const tokenHash = {};
71
- tokenHash[provider] = afUser.accessToken;
72
118
  const changes = {
73
119
  email: afUser.email,
74
120
  name: afUser.displayName || afUser.email,
75
- photoURL: afUser.photoURL,
76
- tokens: Object.assign({}, dbUser.tokens || {}, tokenHash),
121
+ photoURL: afUser.photoURL || null,
77
122
  };
78
123
  try {
79
- patchState(store, { user: dbUser });
80
- await db.updateEntity('users', dbUser.__id, changes);
124
+ await userStore.update(dbUser.__id, changes);
81
125
 
82
126
  if (!params || !params.doNotRoute) {
83
127
  router.navigate(navLocation, { queryParamsHandling: 'preserve' });
@@ -87,27 +131,23 @@ export const AuthStore = signalStore(
87
131
  throw e;
88
132
  }
89
133
  } else {
90
- const tokenHash = {};
91
- tokenHash[provider] = afUser.accessToken;
92
134
  const newUser = {
93
135
  __id: afUser.uid,
94
136
  email: afUser.email,
95
137
  name: afUser.displayName || afUser.email,
96
- photoURL: afUser.photoURL,
97
- tokens: tokenHash,
138
+ photoURL: afUser.photoURL || null,
98
139
  isAdmin: false,
99
140
  consented: false,
100
- accessState: AccessState.CONSENT,
141
+ accessState: AccessState.SUBMIT_INTEREST,
101
142
  };
102
143
  try {
103
- await db.addEntity('users', newUser);
104
- patchState(store, { user: newUser });
144
+ await userStore.add(newUser);
105
145
 
106
146
  if (!params || !params.doNotRoute) {
107
147
  router.navigate(navLocation, { queryParamsHandling: 'preserve' });
108
148
  }
109
149
  } catch (e) {
110
- console.error(e);
150
+ console.error(`[AuthStore login] Error creating new user:`, e);
111
151
  throw e;
112
152
  }
113
153
  }
@@ -132,5 +172,6 @@ export const AuthStore = signalStore(
132
172
  throw e;
133
173
  }
134
174
  },
135
- })),
175
+ };
176
+ }),
136
177
  );