@tech4good/angular-schematics 20.3.1 → 21.1.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 (146) hide show
  1. package/.agents/skills/publish-npm/SKILL.md +1 -1
  2. package/.agents/skills/publish-npm/eval.yaml +15 -0
  3. package/.agents/skills/publish-npm/fixtures/package-v21.json.template +8 -0
  4. package/.t4g/agent-memory.db +0 -0
  5. package/CHANGELOG.md +71 -0
  6. package/contributing-docs/commit-message.md +3 -6
  7. package/package.json +5 -5
  8. package/src/collection.json +8 -0
  9. package/src/component/files/__name@dasherize__/__name@dasherize__.component.ts.template +1 -3
  10. package/src/component/index_spec.js +57 -4
  11. package/src/component/index_spec.js.map +1 -1
  12. package/src/entity/files/__name@dasherize__/__name@dasherize__.mock.ts.template +15 -1
  13. package/src/entity/index.js +7 -1
  14. package/src/entity/index.js.map +1 -1
  15. package/src/entity/index_spec.js +108 -4
  16. package/src/entity/index_spec.js.map +1 -1
  17. package/src/guard/files/__name@dasherize__.guard.spec.ts.template +45 -0
  18. package/src/guard/files/__name@dasherize__.guard.ts.template +32 -0
  19. package/src/guard/index.d.ts +2 -0
  20. package/src/guard/index.js +38 -0
  21. package/src/guard/index.js.map +1 -0
  22. package/src/guard/index_spec.d.ts +1 -0
  23. package/src/guard/index_spec.js +64 -0
  24. package/src/guard/index_spec.js.map +1 -0
  25. package/src/guard/schema.json +46 -0
  26. package/src/ng-add/files/.firebaserc.template +3 -2
  27. package/src/ng-add/files/.github/workflows/angular-github-ci.yml.template +105 -39
  28. package/src/ng-add/files/.gitignore.template +1 -2
  29. package/src/ng-add/files/angular.json.template +1 -5
  30. package/src/ng-add/files/docs-infra/infrastructure-guide.md.template +390 -0
  31. package/src/ng-add/files/docs-infra/load-system-architecture.md.template +166 -0
  32. package/src/ng-add/files/docs-infra/querying-strategy.md.template +157 -0
  33. package/src/ng-add/files/docs-infra/stream-system-architecture.md.template +283 -0
  34. package/src/ng-add/files/eslint.config.js.template +4 -1
  35. package/src/ng-add/files/firebase.json.template +37 -0
  36. package/src/ng-add/files/firestore.rules.spec.ts.template +221 -0
  37. package/src/ng-add/files/firestore.rules.template +67 -0
  38. package/src/ng-add/files/jest.config.ts.template +6 -1
  39. package/src/ng-add/files/package.json.template +41 -31
  40. package/src/ng-add/files/setup-jest.ts.template +13 -5
  41. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.spec.ts.template +76 -12
  42. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.component.ts.template +1 -3
  43. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.spec.ts.template +90 -0
  44. package/src/ng-add/files/src/app/admin/admin-panel/admin-settings/admin-settings.component.ts.template +1 -1
  45. 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 +12 -17
  46. 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 +2 -4
  47. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.component.spec.ts.template +40 -19
  48. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.component.ts.template +3 -5
  49. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.html.template +2 -2
  50. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.spec.ts.template +108 -0
  51. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-list.component.ts.template +11 -11
  52. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.html.template +6 -2
  53. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.spec.ts.template +136 -19
  54. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.component.ts.template +8 -5
  55. package/src/ng-add/files/src/app/app.component.html.template +1 -1
  56. package/src/ng-add/files/src/app/app.component.scss.template +10 -0
  57. package/src/ng-add/files/src/app/app.component.ts.template +1 -1
  58. package/src/ng-add/files/src/app/app.config.ts.template +11 -11
  59. package/src/ng-add/files/src/app/auth-routing.spec.ts.template +101 -0
  60. package/src/ng-add/files/src/app/core/analytics/log.service.ts.template +5 -8
  61. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.spec.ts.template +140 -0
  62. package/src/ng-add/files/src/app/core/analytics/time-analytics.service.ts.template +25 -7
  63. package/src/ng-add/files/src/app/core/auth/guards/redirect-if-authenticated.guard.ts.template +1 -1
  64. package/src/ng-add/files/src/app/core/auth/guards/require-admin.guard.ts.template +1 -1
  65. package/src/ng-add/files/src/app/core/auth/guards/require-auth-and-consent.guard.ts.template +1 -1
  66. package/src/ng-add/files/src/app/core/auth/guards/require-auth.guard.ts.template +1 -1
  67. package/src/ng-add/files/src/app/core/firebase/cached-listeners.service.ts.template +229 -14
  68. package/src/ng-add/files/src/app/core/firebase/database.service.ts.template +1 -1
  69. package/src/ng-add/files/src/app/core/firebase/firebase.mock.service.ts.template +34 -9
  70. package/src/ng-add/files/src/app/core/firebase/firebase.service.ts.template +4 -4
  71. package/src/ng-add/files/src/app/core/firebase/query-logger.ts.template +11 -0
  72. package/src/ng-add/files/src/app/core/firebase/simulate-load.spec.ts.template +104 -0
  73. package/src/ng-add/files/src/app/core/firebase/simulate-stream.spec.ts.template +127 -0
  74. package/src/ng-add/files/src/app/core/firebase/simulation.mock.ts.template +38 -0
  75. package/src/ng-add/files/src/app/core/firebase/stream-multiplexer.ts.template +443 -0
  76. package/src/ng-add/files/src/app/core/store/app.store.spec.ts.template +920 -0
  77. package/src/ng-add/files/src/app/core/store/app.store.ts.template +303 -137
  78. package/src/ng-add/files/src/app/core/store/auth/auth.mock.ts.template +65 -23
  79. package/src/ng-add/files/src/app/core/store/auth/auth.store.ts.template +68 -67
  80. package/src/ng-add/files/src/app/core/store/user/user.mock.ts.template +46 -0
  81. package/src/ng-add/files/src/app/core/store/user-context/user-context.mock.ts.template +17 -0
  82. package/src/ng-add/files/src/app/core/testing/test-utils.ts.template +26 -0
  83. package/src/ng-add/files/src/app/first-time/consent/consent.component.html.template +3 -3
  84. package/src/ng-add/files/src/app/first-time/consent/consent.component.spec.ts.template +89 -13
  85. package/src/ng-add/files/src/app/first-time/consent/consent.component.ts.template +46 -17
  86. package/src/ng-add/files/src/app/first-time/consent/consent.guard.ts.template +1 -1
  87. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.html.template +5 -63
  88. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.scss.template +1 -94
  89. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.spec.ts.template +150 -14
  90. package/src/ng-add/files/src/app/first-time/early-access/early-access.component.ts.template +15 -42
  91. package/src/ng-add/files/src/app/first-time/early-access/early-access.guard.ts.template +2 -2
  92. package/src/ng-add/files/src/app/first-time/early-access/early-access.model.ts.template +5 -0
  93. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.html.template +42 -0
  94. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.scss.template +96 -0
  95. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.spec.ts.template +37 -0
  96. package/src/ng-add/files/src/app/first-time/early-access/survey-form/survey-form.component.ts.template +63 -0
  97. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.html.template +16 -0
  98. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.scss.template +7 -0
  99. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.spec.ts.template +41 -0
  100. package/src/ng-add/files/src/app/first-time/early-access/waitlist-view/waitlist-view.component.ts.template +26 -0
  101. package/src/ng-add/files/src/app/first-time/first-time-routing.spec.ts.template +123 -0
  102. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.html.template +11 -4
  103. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.scss.template +17 -4
  104. package/src/ng-add/files/src/app/first-time/landing/hero/hero.component.ts.template +5 -5
  105. package/src/ng-add/files/src/app/first-time/landing/landing.component.html.template +1 -1
  106. package/src/ng-add/files/src/app/first-time/landing/landing.component.scss.template +0 -1
  107. package/src/ng-add/files/src/app/first-time/landing/landing.component.spec.ts.template +25 -17
  108. package/src/ng-add/files/src/app/first-time/landing/landing.component.ts.template +4 -12
  109. package/src/ng-add/files/src/app/first-time/landing/rotating-quotes/rotating-quotes.component.ts.template +1 -1
  110. package/src/ng-add/files/src/app/first-time/login/login.component.spec.ts.template +36 -16
  111. package/src/ng-add/files/src/app/first-time/login/login.component.ts.template +1 -1
  112. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.spec.ts.template +11 -15
  113. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.component.ts.template +1 -3
  114. package/src/ng-add/files/src/app/main/home/home.component.ts.template +1 -3
  115. package/src/ng-add/files/src/app/shared/dev-status-bar/dev-status-bar.component.spec.ts.template +98 -0
  116. package/src/ng-add/files/src/app/shared/dev-status-bar/dev-status-bar.component.ts.template +9 -3
  117. package/src/ng-add/files/src/app/shared/hint-visibility/hint-visibility.directive.spec.ts.template +164 -0
  118. package/src/ng-add/files/src/app/shared/hint-visibility/hint-visibility.directive.ts.template +20 -18
  119. package/src/ng-add/files/src/app/shared/navbar/navbar.component.spec.ts.template +38 -17
  120. package/src/ng-add/files/src/app/shared/navbar/navbar.component.ts.template +1 -1
  121. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.html.template +1 -1
  122. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.spec.ts.template +49 -10
  123. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.component.ts.template +5 -5
  124. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.spec.ts.template +86 -0
  125. package/src/ng-add/files/src/app/shared/redeployment-warning/redeployment-warning.service.ts.template +11 -9
  126. package/src/ng-add/files/src/environments/environment.prod.ts.template +1 -0
  127. package/src/ng-add/files/src/environments/environment.test.ts.template +1 -0
  128. package/src/ng-add/files/src/environments/environment.ts.template +2 -8
  129. package/src/ng-add/files/src/styles.scss.template +29 -1
  130. package/src/ng-add/files/tsconfig.app.json.template +6 -6
  131. package/src/ng-add/files/tsconfig.json.template +13 -8
  132. package/src/ng-add/files/tsconfig.spec.json.template +6 -5
  133. package/src/ng-add/index.js +19 -1
  134. package/src/ng-add/index.js.map +1 -1
  135. package/tech4good-angular-schematics-21.0.0.tgz +0 -0
  136. package/src/component/files/__name@dasherize__/__name@dasherize__.animations.ts.template +0 -4
  137. package/src/ng-add/files/src/app/admin/admin-panel/admin-panel.animations.ts.template +0 -4
  138. 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 +0 -4
  139. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-counts/admin-user-counts.animations.ts.template +0 -4
  140. package/src/ng-add/files/src/app/admin/admin-panel/admin-user-list/admin-user-table/admin-user-table.animations.ts.template +0 -4
  141. package/src/ng-add/files/src/app/first-time/consent/consent.animations.ts.template +0 -4
  142. package/src/ng-add/files/src/app/first-time/early-access/early-access.animations.ts.template +0 -10
  143. package/src/ng-add/files/src/app/first-time/landing/hero/hero.animations.ts.template +0 -15
  144. package/src/ng-add/files/src/app/first-time/landing/landing.animations.ts.template +0 -4
  145. package/src/ng-add/files/src/app/first-time/onboarding/onboarding.animations.ts.template +0 -4
  146. package/src/ng-add/files/src/app/main/home/home.animations.ts.template +0 -4
@@ -0,0 +1,390 @@
1
+ # Infrastructure Guide
2
+
3
+ This document describes the custom infrastructure patterns in repositories generated using `@techgood/angular-schematics` that differ from standard Angular conventions. Understanding these is essential for contributing code correctly.
4
+
5
+ ---
6
+
7
+ ## 1. Entity System
8
+
9
+ Every Firestore collection in this project is modeled as an **entity** following a strict convention. An entity is a TypeScript interface + ngrx signal store + mock store + mock data.
10
+
11
+ ### 1.1 Entity Model Convention
12
+
13
+ All entities share reserved system fields:
14
+
15
+ | Field | Type | Purpose |
16
+ |-------|------|---------|
17
+ | `__id` | `string` | Primary key (matches Firestore document ID) |
18
+ | `_createdAt` | `Timestamp` | Set automatically on creation |
19
+ | `_updatedAt` | `Timestamp` | Set automatically on every write |
20
+ | `_deleted` | `boolean` | Soft-delete flag — **entities are never hard-deleted** |
21
+
22
+ Foreign keys use the `__` prefix (e.g. `__ownerId`, `__communityId`). This is a project convention, not an Angular or Firebase one.
23
+
24
+ **Example** (community.model.ts):
25
+ ```typescript
26
+ export interface Community {
27
+ __id: string;
28
+ _createdAt?: Timestamp;
29
+ _updatedAt?: Timestamp;
30
+ _deleted?: boolean;
31
+ name: string;
32
+ __ownerId: string;
33
+ }
34
+ ```
35
+
36
+ ### 1.2 Entity File Set
37
+
38
+ Each entity lives in `src/app/core/store/<entity-name>/` and consists of exactly 3 files:
39
+
40
+ | File | Purpose |
41
+ |------|---------|
42
+ | `<entity>.model.ts` | TypeScript interface |
43
+ | `<entity>.store.ts` | ngrx signal store with `withEntitiesAndDBMethods` |
44
+ | `<entity>.mock.ts` | Mock signal store with `withEntitiesForMockDB` + seed data array |
45
+
46
+ > [!IMPORTANT]
47
+ > **Do NOT create entity files manually.** Use the schematic: `ng generate entity <name>`. This registers the entity in several other files (e.g. `app.model.ts` `AnyEntity` union, `firebase.mock.service.ts` DB map). Missing these registrations will cause runtime errors.
48
+
49
+ ### 1.3 Collection Naming
50
+
51
+ The Firestore collection name is always the **pluralized entity name** and is hardcoded in the store and mock files. Note the convention is simply appending `s` (e.g. `'communitys'`, not `'communities'`). This matches the Firestore collection naming.
52
+
53
+ ### 1.4 Adding a New Entity to `AnyEntity`
54
+
55
+ When a new entity is generated, it must be added to the union type in `src/app/core/store/app.model.ts`:
56
+ ```typescript
57
+ export type AnyEntity = Session | Community | User | UserContext;
58
+ ```
59
+
60
+ And its MockDB store must be registered in `src/app/core/firebase/firebase.mock.service.ts`:
61
+ ```typescript
62
+ readonly DB = {
63
+ 'sessions': inject(SessionMockDB),
64
+ 'communitys': inject(CommunityMockDB),
65
+ // ... add new entity here
66
+ };
67
+ ```
68
+
69
+ ---
70
+
71
+ ## 2. Soft Deletes
72
+
73
+ Entities are **never hard-deleted** from Firestore. Instead, `removeEntity` sets `_deleted: true` and `_updatedAt: Timestamp.now()`.
74
+
75
+ This has several implications:
76
+
77
+ 1. **All queries must filter out deleted entities.** The infrastructure does this automatically:
78
+ - `store.load()` appends `['_deleted', '==', false]` to query params
79
+ - `store.selectEntities()` / `store.selectEntity()` filter out `_deleted === true`
80
+ - `store.count()` appends `['_deleted', '==', false]`
81
+
82
+ 2. **Do NOT add `_deleted == false` to your own queries** — it's already handled. Adding it would create a duplicate composite index requirement in Firestore.
83
+
84
+ 3. **Firestore stream 'removed' events are ambiguous.** A `'removed'` change from `onSnapshot` can mean either:
85
+ - The document was soft-deleted (→ remove from local store)
86
+ - The document no longer matches the query but still exists (→ keep in store)
87
+
88
+ The `src/app/core/firebase/cached-listeners.service.ts` handles this by using `entityInQueryResults()` to distinguish the two cases.
89
+
90
+ ---
91
+
92
+ ## 3. Store Data Loading Patterns
93
+
94
+ There are two ways to fetch data from Firestore into the ngrx signal store:
95
+
96
+ ### 3.1 `store.load()` — One-time Fetch
97
+
98
+ Fetches entities once using `getEntities()`. Includes delta-loading optimization: after the first load, subsequent loads only fetch documents where `_updatedAt > lastLoadTime`.
99
+
100
+ ```typescript
101
+ // In ngOnInit or a container's load method:
102
+ await this.communityStore.load(
103
+ [['__ownerId', '==', user.__id]], // queryParams
104
+ {}, // queryOptions
105
+ undefined, // loadQueries (nested)
106
+ { loading: this.loadingSignal }, // options
107
+ );
108
+ ```
109
+
110
+ ### 3.2 `store.stream()` — Real-time Listener
111
+
112
+ Opens a Firestore `onSnapshot` listener that pushes changes to the store in real-time. Managed by `CachedListenersService` which:
113
+ - **Caches listeners**: Reuses existing streams for the same query across multiple components
114
+ - **Delays disconnect**: Waits 5 seconds after a component is destroyed before closing the stream, allowing navigating between views without re-establishing connections
115
+ - **Supports nested `streamQueries`**: Automatically opens child streams when parent entities change (e.g. stream sessions when a community loads)
116
+
117
+ ```typescript
118
+ // In a container component:
119
+ await this.communityStore.stream(
120
+ [['__ownerId', '==', user.__id]], // queryParams
121
+ {}, // queryOptions
122
+ this.injector, // injector (for DestroyRef)
123
+ (community) => [ // streamQueries (nested)
124
+ new StreamSession(
125
+ this.sessionStore,
126
+ [['__communityId', '==', community.__id]],
127
+ {},
128
+ ),
129
+ ],
130
+ { loading: this.loadingSignal },
131
+ );
132
+ ```
133
+
134
+ > [!WARNING]
135
+ > `store.stream()` requires an `Injector` argument. It uses `DestroyRef` from the calling component to manage the subscription lifecycle. Pass `this.injector` from the component — do NOT use a service-level injector.
136
+
137
+ ### 3.3 Selecting Data from the Store
138
+
139
+ After loading, data is read from the store using **computed signals**, not by subscribing to the stream output:
140
+
141
+ ```typescript
142
+ // Computed signal that reactively filters the store
143
+ communities = computed(() => {
144
+ return this.communityStore.selectEntities(
145
+ [['__ownerId', '==', this.currentUser().__id]],
146
+ {},
147
+ );
148
+ });
149
+ ```
150
+
151
+ The `selectEntities()` method mirrors Firestore query operators (`==`, `!=`, `>`, `<`, `>=`, `<=`, `in`, `not-in`, `array-contains`, `array-contains-any`) and runs them against the local entity map. It always filters out `_deleted === true`.
152
+
153
+ ---
154
+
155
+ ## 4. Batch Writes
156
+
157
+ Multi-entity operations (e.g. creating a Community + its first Session atomically) use the `BatchWriteService`:
158
+
159
+ ```typescript
160
+ await this.batch.batchWrite(async (batchConfig) => {
161
+ await this.communityStore.add(newCommunity, { batchConfig });
162
+ await this.sessionStore.add(newSession, { batchConfig });
163
+ }, {
164
+ loading: this.loadingSignal,
165
+ snackBarConfig: {
166
+ successMessage: 'Created community!',
167
+ failureMessage: 'Failed to create community',
168
+ undoOnAction: true,
169
+ config: { duration: 5000 },
170
+ },
171
+ });
172
+ ```
173
+
174
+ Key behavior:
175
+ - All store writes (`add`, `update`, `remove`) accept an optional `batchConfig` parameter
176
+ - When `batchConfig` is provided, writes are **deferred** — they queue into the Firestore `WriteBatch` rather than executing immediately
177
+ - `batch.commit()` is called automatically by `processBatchWrite`
178
+ - Local state is only patched **after** the batch commit succeeds (unless `optimistic: true`)
179
+ - The snackbar "Undo" button uses `revertBatch` to reverse the operation
180
+
181
+ > [!IMPORTANT]
182
+ > Inject `BatchWriteService` via the `BATCH_WRITE_SERVICE` injection token, NOT directly. The token is swapped between `BatchWriteDBService` (production) and `BatchWriteMockService` (mock mode) in `app.config.ts`.
183
+
184
+ ---
185
+
186
+ ## 5. MockDB System
187
+
188
+ The project has a full mock database that runs entirely in-browser using ngrx signal stores + localStorage, with no Firestore dependency.
189
+
190
+ ### 5.1 Enabling MockDB
191
+
192
+ Set `mockDB: true` in `src/environments/environment.ts`:
193
+ ```typescript
194
+ export const environment = {
195
+ production: false,
196
+ mockDB: true, // ← enables mock mode
197
+ firebase: { ... },
198
+ };
199
+ ```
200
+
201
+ When `mockDB` is true, `app.config.ts` swaps out:
202
+ - `FirebaseService` → `FirebaseMockService` (via `DATABASE_SERVICE` token)
203
+ - `BatchWriteDBService` → `BatchWriteMockService` (via `BATCH_WRITE_SERVICE` token)
204
+ - Firebase providers are not loaded at all
205
+
206
+ ### 5.2 How MockDB Works
207
+
208
+ - Each entity has a `MockDB` signal store (e.g. `CommunityMockDB`) using `withEntitiesForMockDB`
209
+ - On init, the store loads from localStorage if data exists, otherwise from the seed array (e.g. `COMMUNITY_DB`)
210
+ - All writes are persisted to `localStorage` under key `mockDB_<collectionName>`
211
+ - Cross-tab sync uses the `storage` event listener so changes in one tab appear in another
212
+ - Simulated latency (`GET_LATENCY_SIMULATION_DELAY = 100ms`, `PUT_LATENCY_SIMULATION_DELAY = 300ms`) mimics real network conditions
213
+
214
+ ### 5.3 MockDB Seed Data
215
+
216
+ Each `<entity>.mock.ts` exports a seed data array (e.g. `COMMUNITY_DB = [...]`). To add test data, populate this array with entity objects. The mock system uses localStorage as the source of truth once data has been written at least once, so **clear localStorage** if you change seed data and want it to take effect.
217
+
218
+ ---
219
+
220
+ ## 6. Authentication & Access Flow
221
+
222
+ ### 6.1 Auth State
223
+
224
+ Auth state lives in `src/app/core/store/auth/auth.store.ts`:
225
+ - `authStore.afUser` — the Firebase Auth user (uid, email, displayName, photoURL)
226
+ - `authStore.user` — a computed signal that looks up the database `User` entity by `afUser.uid`
227
+
228
+ On app start, `AppComponent.ngOnInit()` calls `authStore.loadAuth()`, which:
229
+ 1. Subscribes to the Firebase auth state (`db.afUser()`)
230
+ 2. Performs a blocking `userStore.load()` to ensure the user is in the store before guards run
231
+ 3. Then sets up a background `userStore.stream()` for real-time updates
232
+ 4. Creates a new database User if one doesn't exist yet
233
+
234
+ ### 6.2 Access Pipeline (Guards)
235
+
236
+ Users progress through access states defined in `AccessState`:
237
+ ```
238
+ SUBMIT_INTEREST → WAITING → DONE (+ consented)
239
+ ```
240
+
241
+ The guard hierarchy is:
242
+
243
+ | Guard | Purpose |
244
+ |-------|---------|
245
+ | `redirectIfAuthenticated` | Public pages (landing, login) — redirects logged-in users away |
246
+ | `requireAuth` | Requires login only |
247
+ | `requireAdmin` | Requires `user.isAdmin === true` |
248
+ | `earlyAccessGuard` | Redirects users past early-access stage to consent |
249
+ | `consentGuard` | Redirects already-consented users to home |
250
+ | `requireAuthAndConsent` | Main routes — requires full pipeline completion |
251
+
252
+ > [!NOTE]
253
+ > `requireAuthAndConsent` also checks for **admin overrides** — admins can bypass access restrictions on certain paths. This is useful for testing features before granting access to users.
254
+
255
+ ### 6.3 Route Input Binding
256
+
257
+ The app uses `withComponentInputBinding()` in `app.config.ts`. This means route params and query params are automatically bound to component `input()` signals. **Do NOT manually subscribe to `ActivatedRoute.queryParams`** — use `input()` signals instead.
258
+
259
+ ```typescript
260
+ // ✅ Correct: use input() for route params
261
+ tab = input<string>('users');
262
+
263
+ // ❌ Incorrect: subscribing to queryParams
264
+ this.route.queryParams.subscribe(params => { ... });
265
+ ```
266
+
267
+ ---
268
+
269
+ ## 7. Component Structure Conventions
270
+
271
+ ### 7.1 Always Use `ng generate component`
272
+
273
+ **Do NOT create component files manually.** Always use:
274
+ ```bash
275
+ ng generate component <name>
276
+ ```
277
+ This applies the project's schematics and generates the component with the correct defaults, including the standard comment section headers.
278
+
279
+ ### 7.2 Hierarchical Folder Placement
280
+
281
+ Component folders must reflect the **component hierarchy** — child components live inside their parent's folder. Do NOT create flat organizational folders like `ui/`, `components/`, `presentational/`, etc.
282
+
283
+ ```
284
+ ✅ Correct:
285
+ src/app/main/home/
286
+ home.component.ts
287
+ community-grid/
288
+ community-grid.component.ts
289
+ community-card/
290
+ community-card.component.ts
291
+
292
+ ❌ Incorrect:
293
+ src/app/main/home/
294
+ home.component.ts
295
+ ui/
296
+ community-grid.component.ts
297
+ community-card.component.ts
298
+ ```
299
+
300
+ ### 7.3 Section Organization
301
+
302
+ Components follow a standard section order using comment dividers:
303
+
304
+ ```typescript
305
+ export class ExampleComponent implements OnInit {
306
+ // --------------- INPUTS AND OUTPUTS ------------------
307
+ // --------------- LOCAL UI STATE ----------------------
308
+ // --------------- COMPUTED DATA -----------------------
309
+ // --------------- EVENT HANDLING ----------------------
310
+ // --------------- OTHER -------------------------------
311
+ // --------------- LOAD AND CLEANUP --------------------
312
+ }
313
+ ```
314
+
315
+ ### 7.4 Imports — No `CommonModule`
316
+
317
+ **Do NOT import `CommonModule`.** Import only the specific Angular pipes/directives you need (e.g. `AsyncPipe`, `DatePipe`). In Angular 20 with standalone components, structural directives like `@if`/`@for` are built-in and don't require imports.
318
+
319
+ ### 7.5 Signals-First Approach
320
+
321
+ The codebase uses Angular signals as the primary reactivity model:
322
+ - Component state → `signal()` / `WritableSignal`
323
+ - Derived state → `computed()`
324
+ - Store queries → `computed(() => store.selectEntities(...))`
325
+ - Cross-signal dependencies → `linkedSignal()`
326
+ - Side effects → `effect()` (in constructor)
327
+ - Data loading → async methods in `ngOnInit` (for now; may move to constructor + `effect()`)
328
+
329
+ **Avoid:**
330
+ - `Observable` + `| async` pipe for data that originates from signals (round-tripping through `toObservable` → `| async` is unnecessary)
331
+ - `Subject` for local component state (use `signal()` instead)
332
+ - `BehaviorSubject` for state management (use the ngrx signal stores)
333
+
334
+ ### 7.6 Dependency Injection
335
+
336
+ Use `inject()` for all dependency injection. The codebase is transitioning from constructor DI to field-level `inject()`:
337
+
338
+ ```typescript
339
+ // ✅ Preferred
340
+ private readonly router = inject(Router);
341
+ private readonly batch = inject(BATCH_WRITE_SERVICE);
342
+
343
+ // ❌ Legacy (still present in some files)
344
+ constructor(
345
+ private router: Router,
346
+ @Inject(BATCH_WRITE_SERVICE) private batch: BatchWriteService,
347
+ ) {}
348
+ ```
349
+
350
+ ### 7.7 SCSS Budget — When to Extract Components
351
+
352
+ The project enforces a **4KB budget per component stylesheet** (configured in `angular.json`). If you hit this limit, it is a signal that the component is too large and should be refactored into smaller child components. Do NOT try to work around the budget by inlining styles or compressing CSS — instead, extract logical sub-sections into their own components with their own stylesheets. This also improves readability and maintainability.
353
+
354
+ ---
355
+
356
+ ## 8. Custom Schematics
357
+
358
+ The project uses `@tech4good/angular-schematics` for code generation. Key schematics:
359
+
360
+ | Command | What it generates |
361
+ |---------|-------------------|
362
+ | `ng generate entity <name>` | Model + Store + MockDB + seed data array, registers in `AnyEntity` union and `FirebaseMockService.DB` |
363
+ | `ng generate component <name>` | Standard Angular component with the project's section layout and comment headers |
364
+
365
+ > [!CAUTION]
366
+ > **Always use `ng generate` for both entities AND components.** Creating files manually will miss schematics defaults (section headers, registrations) and cause inconsistencies.
367
+
368
+ ---
369
+
370
+ ## 9. Pre-generating Entity IDs with `db.createId()`
371
+
372
+ When creating related entities in a single batch write (e.g. a Community and its first Session), you need to know the ID of the parent entity before it's saved to the database. Use `db.createId()` to generate a Firestore-compatible ID upfront:
373
+
374
+ ```typescript
375
+ await this.batch.batchWrite(async (batchConfig) => {
376
+ // Pre-generate the community ID so the session can reference it
377
+ const communityId = this.db.createId();
378
+
379
+ await this.communityStore.add(
380
+ { __id: communityId, name: 'My Community', __ownerId: user.__id },
381
+ { batchConfig },
382
+ );
383
+ await this.sessionStore.add(
384
+ { __communityId: communityId, __ownerId: user.__id, name: 'Session 1' },
385
+ { batchConfig },
386
+ );
387
+ }, { ... });
388
+ ```
389
+
390
+ If an `__id` is not provided to `store.add()`, one is generated automatically. But when you need to reference the ID in a related entity within the same batch, you must pre-generate it.
@@ -0,0 +1,166 @@
1
+ # Load System Architecture
2
+
3
+ This document details the code-level architecture of the `load()` method in the query system. For a high-level overview of our querying strategy, refer to [querying-strategy.md](./querying-strategy.md).
4
+
5
+ ## 1. Data Structures & State Management
6
+
7
+ The load system relies on `CachedListenersService` to track when entities were last fetched. This ensures we only fetch data modified since the previous load (Delta Fetching).
8
+
9
+ We maintain two separate state dictionaries depending on the complexity of the query:
10
+
11
+ ```typescript
12
+ // 1. Complex/General Queries: Cached by strict queryKey string
13
+ // Key: "collection.queryParams.queryOptions"
14
+ private lastLoadTime: Record<string, number> = {};
15
+
16
+ // 2. Simple Equality/In Queries: Cached per-entity
17
+ // Key: "collection.field:value"
18
+ private entityLoadTime: Record<string, number> = {};
19
+ ```
20
+
21
+ ## 2. The `load()` Flow Walkthrough
22
+
23
+ When a component calls `load(queryParams, queryOptions, loadQueries)`, it triggers a structured sequence:
24
+
25
+ ```mermaid
26
+ sequenceDiagram
27
+ participant Component
28
+ participant Store
29
+ participant CachedListeners as CachedListenersService
30
+ participant DB as DatabaseService
31
+
32
+ Component->>Store: load(queryParams, queryOptions, loadQueries)
33
+ Store->>CachedListeners: isStreamForQuery(queryParams, queryOptions)
34
+ alt Stream already exists
35
+ CachedListeners-->>Store: true (Skip DB query, data is already streaming)
36
+ else No active stream
37
+ CachedListeners-->>Store: false
38
+ Store->>CachedListeners: getLastLoadTime(queryParams, queryOptions)
39
+ CachedListeners-->>Store: timestamp (or -1 if first time)
40
+ alt has queryOptions or first time (lastLoadTime = -1)
41
+ Store->>DB: getEntities(collection, queryParams + [_deleted == false])
42
+ DB-->>Store: entitiesDelta
43
+ else Incremental load (lastLoadTime exists)
44
+ Store->>DB: getEntities(collection, queryParams + [_updatedAt > lastLoadTime, _deleted == false])
45
+ DB-->>Store: entitiesDelta
46
+ end
47
+ Store->>Store: patchState(setEntities(entitiesDelta))
48
+
49
+ Note over Store,DB: Soft Deletes Sync
50
+ Store->>DB: getEntities(collection, queryParams + [_updatedAt > lastLoadTime, _deleted == true])
51
+ DB-->>Store: deletedDelta
52
+ Store->>Store: patchState(removeEntities(deletedDelta))
53
+
54
+ Store->>CachedListeners: setLastLoadTime(queryParams, queryOptions, now)
55
+ end
56
+
57
+ rect rgb(240, 248, 255)
58
+ Note over Store: Nested Queries Processing
59
+ Store->>Store: selectEntities(queryParams, queryOptions)
60
+ Store->>Store: processLoadQueries(entities, loadQueries)
61
+ loop for each query type
62
+ Store->>Store: EntityLoadQuery.optimize(queriesForOneType)
63
+ Store->>Store: Concurrently run store.load() for each optimized query
64
+ end
65
+ end
66
+
67
+ Store-->>Component: Complete
68
+ ```
69
+
70
+ ### Step 1: Initial Load & Execution Path Split
71
+
72
+ The `load()` method dynamically checks if the query is a simple, batchable equality query (`==` or `in` with no `queryOptions`) or a complex/legacy query (inequalities, limits, multi-field).
73
+
74
+ #### Path A: The Legacy/Complex Path
75
+ For complex queries, we cache and deduplicate based on the exact query string.
76
+ 1. **Deduplication (`isStreamForQuery`)**: Exits early if the exact query string is actively streaming.
77
+ 2. **Delta Fetching**: Uses `lastLoadTime` to append `_updatedAt > lastLoadTime` to the query, fetches the delta, and patches the store.
78
+
79
+ #### Path B: The Optimized Equality Path (`==`, `in`)
80
+ For simple equality queries, we track active streams on a **per-entity** basis.
81
+ 1. **Granular Deduplication (`isIdStreamed`)**: The system iterates through each requested ID and checks if it is actively streamed by the Global Multiplexer (a centralized `StreamMultiplexer` that tracks and batches active simple equality streams across the entire app to prevent duplicate DB listeners).
82
+ 2. **Delta Fetching**: Any ID not actively streamed proceeds to fetch its delta. (If this is a large batch of IDs, it undergoes Time Bucketing—detailed in Step 3).
83
+
84
+ ### Step 2: Nested Queries & Matrix Transposition
85
+
86
+ Once the parent entities are fully loaded and patched into the store (from either Path A or Path B), the store executes any provided `loadQueries` for nested children.
87
+
88
+ When a parent list is loaded (e.g., 30 `User` docs), the store automatically calls nested queries for each element (e.g., loading `UserContext` for each user). Without optimization, this creates an N+1 cascade resulting in 31 separate database reads.
89
+
90
+ The system solves this through structural batching. As the store iterates over the fetched parent entities, it collects an array of nested queries for *each* parent. This forms a 2D array: `[Parent Index][Query Index]`. To optimize these queries, we group them by their *query type* across all parents by transposing the matrix:
91
+
92
+ ```mermaid
93
+ graph TD
94
+ subgraph "Original Layout (By Parent Entity)"
95
+ E1["Entity 1<br/>[QueryA, QueryB]"]
96
+ E2["Entity 2<br/>[QueryA, QueryB]"]
97
+ E3["Entity 3<br/>[QueryA, QueryB]"]
98
+ end
99
+
100
+ subgraph "Transposed Layout (By Query Type)"
101
+ QA["Query A List<br/>[Entity 1's Query A, Entity 2's Query A, Entity 3's Query A]"]
102
+ QB["Query B List<br/>[Entity 1's Query B, Entity 2's Query B, Entity 3's Query B]"]
103
+ end
104
+
105
+ E1 -.-> QA
106
+ E1 -.-> QB
107
+ E2 -.-> QA
108
+ E2 -.-> QB
109
+ E3 -.-> QA
110
+ E3 -.-> QB
111
+ ```
112
+
113
+ ```typescript
114
+ // 1. Create a matrix: [Entity][Queries]
115
+ const queriesByEntity = entities.map((entity) => loadQueries(entity));
116
+
117
+ // 2. Transpose the matrix: [QueryType][Entities]
118
+ const queriesByQueryType = queriesByEntity[0].map((_, colIndex) =>
119
+ queriesByEntity.map((row) => row[colIndex])
120
+ );
121
+
122
+ // 3. Optimize each query type
123
+ await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {
124
+ const optimizedQueries = EntityLoadQuery.optimize(queriesForOneType);
125
+ // Concurrently run store.load() recursively for the child queries
126
+ // ...
127
+ }));
128
+ ```
129
+
130
+ `EntityLoadQuery.optimize()` detects multiple `==` queries for the same field and collapses them into a single massive `in` query containing all requested IDs. This massive `in` query is then passed recursively back into `load()`.
131
+
132
+ ### Step 3: Time Bucketing & Convergence
133
+
134
+ When that massive recursive `in` query hits `load()` again, it falls into **Path B**.
135
+
136
+ However, we face a temporal problem: we want to only fetch data that has changed (`_updatedAt > lastLoadTime`), but a batch of 30 different IDs might have 30 different `entityLoadTime`s! Some may have been loaded 2 minutes ago, some 10 minutes ago, and some never at all. If we split the DB queries exactly by `entityLoadTime`, we'd fracture the massive batch into dozens of separate DB reads, defeating the purpose of our matrix transposition.
137
+
138
+ Instead, we group the IDs into **5-minute Time Buckets**:
139
+
140
+ ```typescript
141
+ // From app.store.ts
142
+ const BUCKET_MS = 5 * 60 * 1000;
143
+ const groupsByBucket = new Map<number, { minTime: number, values: string[] }>();
144
+
145
+ valuesToLoad.forEach(val => {
146
+ const time = cachedLoads.getEntityLoadTime(collectionName, field, val);
147
+ const bucketIndex = time === -1 ? -1 : Math.floor(time / BUCKET_MS);
148
+
149
+ if (!groupsByBucket.has(bucketIndex)) {
150
+ groupsByBucket.set(bucketIndex, { minTime: time, values: [] });
151
+ }
152
+
153
+ // Track the absolute earliest time in this bucket
154
+ const group = groupsByBucket.get(bucketIndex)!;
155
+ if (time !== -1 && time < group.minTime) {
156
+ group.minTime = time;
157
+ }
158
+ group.values.push(val);
159
+ });
160
+ ```
161
+
162
+ The system iterates over these buckets, chunks them into batches of up to 30 (Firebase's `in` limit), and executes the queries using the bucket's `minTime` for the `_updatedAt` filter.
163
+
164
+ By rounding to the nearest 5-minute bucket, we sacrifice a tiny amount of over-fetching (fetching up to 5 minutes of redundant data) in exchange for keeping the DB reads massively batched.
165
+
166
+ After the fetch completes, **all IDs in the batch are assigned the exact same `newLoadTime`**. This convergence ensures that these entities group together perfectly in future requests, eliminating fragmentation over time.