Remove group slugs from contracts on delete group

This commit is contained in:
Ian Philips 2022-07-14 07:53:41 -06:00
parent 5ebd4498a0
commit ee01328553
4 changed files with 33 additions and 2 deletions

View File

@ -21,6 +21,7 @@ export * from './on-create-group'
export * from './on-update-user'
export * from './on-create-comment-on-group'
export * from './on-create-txn'
export * from './on-group-delete'
// v2
export * from './health'

View File

@ -0,0 +1,31 @@
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import { Group } from 'common/group'
import { Contract } from 'common/contract'
const firestore = admin.firestore()
exports.onGroupDelete = functions.firestore
.document('groups/{groupId}')
.onDelete(async (change) => {
const group = change.data() as Group
// get all contracts with this group's slug
const contracts = await firestore
.collection('contracts')
.where('groupSlugs', 'array-contains', group.slug)
.get()
for (const doc of contracts.docs) {
const contract = doc.data() as Contract
// remove the group from the contract
await firestore
.collection('contracts')
.doc(contract.id)
.update({
groupSlugs: (contract.groupSlugs ?? []).filter(
(groupSlug) => groupSlug !== group.slug
),
})
}
})

View File

@ -2,14 +2,12 @@ import { useEffect, useState } from 'react'
import { Group } from 'common/group'
import { User } from 'common/user'
import {
getGroupBySlug,
getGroupsWithContractId,
listenForGroup,
listenForGroups,
listenForMemberGroups,
} from 'web/lib/firebase/groups'
import { getUser } from 'web/lib/firebase/users'
import { CATEGORIES, CATEGORIES_GROUP_SLUG_POSTFIX } from 'common/categories'
import { filterDefined } from 'common/util/array'
export const useGroup = (groupId: string | undefined) => {

View File

@ -119,6 +119,7 @@ export async function addUserToGroup(
await updateGroup(newGroup, { memberIds: uniq(newMemberIds) })
return newGroup
}
export async function leaveGroup(group: Group, userId: string): Promise<Group> {
const { memberIds } = group
if (!memberIds.includes(userId)) {