Skip to content
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ export async function deleteMemberWorkExperience(req: Request, res: Response): P

await qx.tx(async (tx) => {
await deleteMemberOrganizations(tx, memberId, [workExperienceId])

const commonMemberService = new CommonMemberService(tx, req.temporal, req.log)
await commonMemberService.startAffiliationRecalculation(memberId, [
memberOrg.organizationId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export async function updateMemberAttributes(
export async function removeMemberOrganizations(memberId: string): Promise<void> {
try {
const qx = pgpQx(svc.postgres.writer.connection())
await deleteMemberOrganizations(qx, memberId, undefined, false)
await deleteMemberOrganizations(qx, memberId, undefined, true)
} catch (error) {
svc.log.error({ error, memberId }, `Failed to remove member organizations!`)
throw error
Expand Down
28 changes: 26 additions & 2 deletions services/libs/data-access-layer/src/members/organizations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,18 +335,42 @@ export async function deleteMemberOrganizations(
const query = `${baseQuery} WHERE ${whereClause};`

await qx.tx(async (tx) => {
// Capture affected org IDs before the delete — needed for the cleanup step below,
// since a hard delete removes rows before we can look them up.
const affectedOrgs: { organizationId: string }[] = await tx.select(
`SELECT DISTINCT "organizationId" FROM "memberOrganizations" WHERE ${whereClause}`,
params,
)
const affectedOrgIds = affectedOrgs.map((r) => r.organizationId)

// First delete from memberOrganizationAffiliationOverrides using the same conditions
await tx.result(
`DELETE FROM "memberOrganizationAffiliationOverrides"
`DELETE FROM "memberOrganizationAffiliationOverrides"
WHERE "memberOrganizationId" IN (
SELECT "id" FROM "memberOrganizations"
SELECT "id" FROM "memberOrganizations"
WHERE ${whereClause}
)`,
params,
)

// Then perform the soft/hard delete on memberOrganizations
await tx.result(query, params)

// Clean up segment affiliations for orgs that no longer have any active work experiences
if (affectedOrgIds.length > 0) {
await tx.result(
`DELETE FROM "memberSegmentAffiliations" msa
WHERE msa."memberId" = $(memberId)
AND msa."organizationId" IN ($(orgIds:csv))
AND NOT EXISTS (
SELECT 1 FROM "memberOrganizations" mo
WHERE mo."memberId" = $(memberId)
AND mo."organizationId" = msa."organizationId"
AND mo."deletedAt" IS NULL
)`,
{ memberId, orgIds: affectedOrgIds },
)
}
})
}

Expand Down
Loading