|
1 | | -import { runWith } from "firebase-functions" |
| 1 | +import { logger, runWith } from "firebase-functions" |
2 | 2 | import { DocUpdate } from "../common" |
3 | 3 | import { db } from "../firebase" |
4 | 4 | import { Member } from "../members/types" |
5 | 5 | import { Committee } from "./types" |
6 | 6 | import { currentGeneralCourt } from "../shared" |
7 | 7 |
|
| 8 | +export class MissingCommitteeDocsError extends Error { |
| 9 | + constructor( |
| 10 | + public readonly court: number | string, |
| 11 | + public readonly missingIds: string[] |
| 12 | + ) { |
| 13 | + super( |
| 14 | + `updateCommitteeRosters: ${missingIds.length} committee doc(s) missing for court ${court}: ${missingIds.join(", ")}. ` + |
| 15 | + `Run startCommitteeBatches first, or investigate stale member->committee references.` |
| 16 | + ) |
| 17 | + this.name = "MissingCommitteeDocsError" |
| 18 | + } |
| 19 | +} |
| 20 | + |
8 | 21 | export async function runUpdateCommitteeRosters(court: number | string) { |
9 | 22 | const members = await db |
10 | 23 | .collection(`/generalCourts/${court}/members`) |
11 | 24 | .get() |
12 | 25 | .then(c => c.docs.map(d => d.data()).filter(Member.guard)) |
13 | 26 | const rosters = computeRosters(members) |
14 | 27 |
|
| 28 | + const committeesRef = db.collection(`/generalCourts/${court}/committees`) |
| 29 | + const existingIds = new Set( |
| 30 | + (await committeesRef.listDocuments()).map(ref => ref.id) |
| 31 | + ) |
| 32 | + const missing = Array.from(rosters.keys()) |
| 33 | + .filter(id => !existingIds.has(id)) |
| 34 | + .sort() |
| 35 | + if (missing.length > 0) { |
| 36 | + const err = new MissingCommitteeDocsError(court, missing) |
| 37 | + logger.error(err.message) |
| 38 | + throw err |
| 39 | + } |
| 40 | + |
15 | 41 | const writer = db.bulkWriter() |
16 | 42 | rosters.forEach((roster, id) => { |
17 | 43 | const update: DocUpdate<Committee> = { |
18 | 44 | members: roster.map(m => ({ id: m.id, name: m.content.Name })) |
19 | 45 | } |
20 | | - writer.set(db.doc(`/generalCourts/${court}/committees/${id}`), update, { |
| 46 | + writer.set(committeesRef.doc(id), update, { |
21 | 47 | merge: true |
22 | 48 | }) |
23 | 49 | }) |
|
0 commit comments