diff --git a/functions/src/index.ts b/functions/src/index.ts index cf75802e..b3f65a4f 100644 --- a/functions/src/index.ts +++ b/functions/src/index.ts @@ -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' diff --git a/functions/src/on-group-delete.ts b/functions/src/on-group-delete.ts new file mode 100644 index 00000000..e078bbcd --- /dev/null +++ b/functions/src/on-group-delete.ts @@ -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 + ), + }) + } + }) diff --git a/web/hooks/use-group.ts b/web/hooks/use-group.ts index 8af2183e..be0c92f6 100644 --- a/web/hooks/use-group.ts +++ b/web/hooks/use-group.ts @@ -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) => { diff --git a/web/lib/firebase/groups.ts b/web/lib/firebase/groups.ts index 708096b3..ec152792 100644 --- a/web/lib/firebase/groups.ts +++ b/web/lib/firebase/groups.ts @@ -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 { const { memberIds } = group if (!memberIds.includes(userId)) {