Update groupContracts in db trigger

This commit is contained in:
Ian Philips 2022-10-06 09:26:35 -04:00
parent 68075db3da
commit 25ef17498a
4 changed files with 65 additions and 31 deletions

View File

@ -39,3 +39,4 @@ export type GroupLink = {
createdTime: number createdTime: number
userId?: string userId?: string
} }
export type GroupContractDoc = { contractId: string; createdTime: number }

View File

@ -2,6 +2,8 @@ import * as functions from 'firebase-functions'
import { getUser } from './utils' import { getUser } from './utils'
import { createCommentOrAnswerOrUpdatedContractNotification } from './create-notification' import { createCommentOrAnswerOrUpdatedContractNotification } from './create-notification'
import { Contract } from '../../common/contract' import { Contract } from '../../common/contract'
import { GroupContractDoc } from '../../common/group'
import * as admin from 'firebase-admin'
export const onUpdateContract = functions.firestore export const onUpdateContract = functions.firestore
.document('contracts/{contractId}') .document('contracts/{contractId}')
@ -9,17 +11,14 @@ export const onUpdateContract = functions.firestore
const contract = change.after.data() as Contract const contract = change.after.data() as Contract
const previousContract = change.before.data() as Contract const previousContract = change.before.data() as Contract
const { eventId } = context const { eventId } = context
const { openCommentBounties, closeTime, question } = contract const { closeTime, question } = contract
if ( if (!previousContract.isResolved && contract.isResolved) {
!previousContract.isResolved &&
contract.isResolved &&
(openCommentBounties ?? 0) > 0
) {
// No need to notify users of resolution, that's handled in resolve-market // No need to notify users of resolution, that's handled in resolve-market
return return
} } else if (previousContract.groupSlugs !== contract.groupSlugs) {
if ( await handleContractGroupUpdated(previousContract, contract)
} else if (
previousContract.closeTime !== closeTime || previousContract.closeTime !== closeTime ||
previousContract.question !== question previousContract.question !== question
) { ) {
@ -51,3 +50,43 @@ async function handleUpdatedCloseTime(
contract contract
) )
} }
async function handleContractGroupUpdated(
previousContract: Contract,
contract: Contract
) {
const prevLength = previousContract.groupSlugs?.length ?? 0
const newLength = contract.groupSlugs?.length ?? 0
if (prevLength < newLength) {
// Contract was added to a new group
const groupId = contract.groupLinks?.find(
(link) =>
!previousContract.groupLinks
?.map((l) => l.groupId)
.includes(link.groupId)
)?.groupId
if (!groupId) throw new Error('Could not find new group id')
await firestore
.collection(`groups/${groupId}/groupContracts`)
.doc(contract.id)
.set({
contractId: contract.id,
createdTime: Date.now(),
} as GroupContractDoc)
}
if (prevLength > newLength) {
// Contract was removed from a group
const groupId = previousContract.groupLinks?.find(
(link) =>
!contract.groupLinks?.map((l) => l.groupId).includes(link.groupId)
)?.groupId
if (!groupId) throw new Error('Could not find old group id')
await firestore
.collection(`groups/${groupId}/groupContracts`)
.doc(contract.id)
.delete()
}
}
const firestore = admin.firestore()

View File

@ -89,17 +89,20 @@ const getGroups = async () => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
async function updateTotalContractsAndMembers() { async function updateTotalContractsAndMembers() {
const groups = await getGroups() const groups = await getGroups()
for (const group of groups) { await Promise.all(
groups.map(async (group) => {
log('updating group total contracts and members', group.slug) log('updating group total contracts and members', group.slug)
const groupRef = admin.firestore().collection('groups').doc(group.id) const groupRef = admin.firestore().collection('groups').doc(group.id)
const totalMembers = (await groupRef.collection('groupMembers').get()).size const totalMembers = (await groupRef.collection('groupMembers').get())
.size
const totalContracts = (await groupRef.collection('groupContracts').get()) const totalContracts = (await groupRef.collection('groupContracts').get())
.size .size
await groupRef.update({ await groupRef.update({
totalMembers, totalMembers,
totalContracts, totalContracts,
}) })
} })
)
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
async function removeUnusedMemberAndContractFields() { async function removeUnusedMemberAndContractFields() {
@ -117,6 +120,6 @@ async function removeUnusedMemberAndContractFields() {
if (require.main === module) { if (require.main === module) {
initAdmin() initAdmin()
// convertGroupFieldsToGroupDocuments() // convertGroupFieldsToGroupDocuments()
// updateTotalContractsAndMembers() updateTotalContractsAndMembers()
removeUnusedMemberAndContractFields() // removeUnusedMemberAndContractFields()
} }

View File

@ -191,6 +191,7 @@ export async function leaveGroup(group: Group, userId: string): Promise<void> {
return await deleteDoc(memberDoc) return await deleteDoc(memberDoc)
} }
// TODO: This doesn't check if the user has permission to do this
export async function addContractToGroup( export async function addContractToGroup(
group: Group, group: Group,
contract: Contract, contract: Contract,
@ -211,15 +212,9 @@ export async function addContractToGroup(
groupSlugs: uniq([...(contract.groupSlugs ?? []), group.slug]), groupSlugs: uniq([...(contract.groupSlugs ?? []), group.slug]),
groupLinks: newGroupLinks, groupLinks: newGroupLinks,
}) })
// create new contract document in groupContracts collection
const contractDoc = doc(groupContracts(group.id), contract.id)
await setDoc(contractDoc, {
contractId: contract.id,
createdTime: Date.now(),
})
} }
// TODO: This doesn't check if the user has permission to do this
export async function removeContractFromGroup( export async function removeContractFromGroup(
group: Group, group: Group,
contract: Contract contract: Contract
@ -234,10 +229,6 @@ export async function removeContractFromGroup(
groupLinks: newGroupLinks ?? [], groupLinks: newGroupLinks ?? [],
}) })
} }
// delete the contract document in groupContracts collection
const contractDoc = doc(groupContracts(group.id), contract.id)
await deleteDoc(contractDoc)
} }
export function getGroupLinkToDisplay(contract: Contract) { export function getGroupLinkToDisplay(contract: Contract) {