Skip to content

Update of users representatives/senators with court 194 #1755

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 171 additions & 0 deletions scripts/firebase-admin/updateGeneralCourt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { Script } from "./types"
import { currentGeneralCourt } from "../../functions/src/shared"
import { Boolean, Optional, Record } from "runtypes"
import { Profile} from "components/db/profile/types"

const Args = Record({
dryRun: Optional(Boolean)
})

export const script: Script = async ({ db, args }) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One nit: could we add a dryRun arg here, and only actually make the updates if it's set to true? This would make it easier for us to first run this script without making any changes just to see that the proposed changes look correct.

There's other examples of us using args in other scripts, like here:

const { dryRun } = Args.check(args)

// if (!dryRun) {
// await profileDoc.ref.update({ nextDigestAt })
// }

console.log(`Update General Court ${currentGeneralCourt} in progress...`)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Love the logging here - it makes this super easy to follow!

try {
const generalCourts = await db
.collection(`/generalCourts/${currentGeneralCourt}/members`)
.get()
console.log(`${generalCourts.size} members fetched`)

// check if generalCourts is valid
if (generalCourts.empty) {
console.log("ERROR: No members found in the collection.")
return
}

const courtMembersMap = new Map<string, any>()
for (const member of generalCourts.docs) {
const data = member.data()
// store the member data in a map with the district as the key
console.log(`${data.content["District"]}: ${data.content["Name"]} , ${data.content["MemberCode"]}`)
courtMembersMap.set(data.content["District"], data)
}

// prepare update
const writer = db.bulkWriter()

console.log("Fetching all profiles ...")
const users = await db.collection("profiles").get()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just for posterity - this is likely fine because there are currently only like ~500 profiles, which is roughly the default bulk writer batch size anyway..

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to know!

console.log(`${users.size} profiles fetched`)

// count updated profiles
let updatedProfiles = 0

let numUsersWithoutSenator = 0
let numUsersWithUpToDateSenator = 0

let numUsersWithoutRepres = 0
let numUsersWithUpToDateRepres = 0

for (const user of users.docs) {
console.log("User info:", user.id)
let hasBeenUpdated = false
let data = user.data() as Profile
if (data.hasOwnProperty("senator")) {
let updateData = updateProfileMember(data, "senator", courtMembersMap)
if (updateData) {
// update profile
if (!dryRun) {
writer.update(user.ref, updateData)
}
hasBeenUpdated = true
numUsersWithUpToDateSenator++
}
} else {
console.log(`No senator set on profile ${user.id}!`)
numUsersWithoutSenator++
}

if (data.hasOwnProperty("representative")) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be helpful to extract a helper function for this block, given that the senator and representative blocks here have near identical logic. e.g. something like const updateProfileMember = (profileRef, memberType, currentMemberMap, bulkWriter) => { // doStuff()} - where memberType is "senator" | "represenative"

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All comments I made on the senator block also apply here, so this might make it easier to make changes in just one place.

const updateData = updateProfileMember(data, "representative", courtMembersMap)
if (updateData) {
// update profile
if (!dryRun) {
writer.update(user.ref, updateData)
}
hasBeenUpdated = hasBeenUpdated || true
numUsersWithUpToDateRepres++
}
} else {
console.log(`No representative set on profile ${user.id}!`)
numUsersWithoutRepres++
}

if (hasBeenUpdated) {
updatedProfiles++
}
}

// summary of updated profiles
// numUsersWithoutSenator/numUsersWithUpToDateSenator/numUsersUpdated
displaySummaryChanges("senator", updatedProfiles, numUsersWithoutSenator,
numUsersWithUpToDateSenator)
displaySummaryChanges("representative", updatedProfiles, numUsersWithoutRepres,
numUsersWithUpToDateRepres)

await writer.close()
} catch (error) {
console.error("ERROR: updating General Court failed with ", error)
}
}



// return Profile update if change is needed
// return undefined if no change is needed
const updateProfileMember = (
profileRef: Profile,
memberType: string,
currentMembersMap: Map<string, any>,
): Profile | undefined => {

let shouldUpdate = false;
let lastMember = profileRef.representative;
if (memberType == "senator") {
lastMember = profileRef.senator;
}

if (!lastMember) {
console.log(`User has no ${memberType}`)
return undefined
}

if (currentMembersMap.has(lastMember.district)) {
const currentMember = currentMembersMap.get(lastMember.district)
console.log(
`User has ${memberType} ${lastMember.id} ${currentMember.id}`
)

if (currentMember.name != lastMember.name) {
shouldUpdate = true
}

if (shouldUpdate) {
if (memberType == "senator") {
profileRef.senator = {
id: currentMember.id,
name: currentMember.content["Name"],
district: currentMember.content["District"]
}
}
else {
profileRef.representative = {
id: currentMember.id,
name: currentMember.content["Name"],
district: currentMember.content["District"]
}
}
console.log(`Updating ${memberType} ${currentMember.content["Name"]} ${currentMember.id}`)
return profileRef;
}
} else {
console.log(`District ${lastMember.district} ${lastMember.id} not found in the new court`)
}
return undefined
}

const displaySummaryChanges = (
memberType: string,
updatedProfiles: number,
numUsersWithoutMember: number,
numUsersWithUpToDateMember: number
) => {
console.log(`Summary of ${memberType} changes`)
console.log(`Updated ${updatedProfiles} profiles`)
console.log(`Number of users without ${memberType}: ${numUsersWithoutMember}`)
console.log(`Number of users with up to date ${memberType}: ${numUsersWithUpToDateMember}`)
}
Loading