|
| 1 | +import { continueAsNew, proxyActivities } from '@temporalio/workflow' |
| 2 | + |
| 3 | +import * as activities from '../activities' |
| 4 | +import { IBlockOrganizationAffiliationArgs } from '../types' |
| 5 | +import { chunkArray } from '../utils/common' |
| 6 | + |
| 7 | +const { getOrganizationMembers, blockMemberOrganizationAffiliation, calculateMemberAffiliations } = |
| 8 | + proxyActivities<typeof activities>({ |
| 9 | + startToCloseTimeout: '30 minutes', |
| 10 | + }) |
| 11 | + |
| 12 | +export async function blockOrganizationAffiliation( |
| 13 | + args: IBlockOrganizationAffiliationArgs, |
| 14 | +): Promise<void> { |
| 15 | + const MEMBERS_PER_RUN = 500 |
| 16 | + const BATCH_SIZE = 50 |
| 17 | + const OFFSET = args.offset ?? 0 |
| 18 | + |
| 19 | + const memberOrganizations = await getOrganizationMembers( |
| 20 | + args.organizationId, |
| 21 | + MEMBERS_PER_RUN, |
| 22 | + OFFSET, |
| 23 | + ) |
| 24 | + |
| 25 | + if (memberOrganizations.length === 0) { |
| 26 | + console.log('No more organization members to block!') |
| 27 | + return |
| 28 | + } |
| 29 | + |
| 30 | + // Step 1: Block all affiliations in batches |
| 31 | + for (const chunk of chunkArray(memberOrganizations, BATCH_SIZE)) { |
| 32 | + await Promise.all(chunk.map((mo) => blockMemberOrganizationAffiliation(mo.memberId, mo.id))) |
| 33 | + } |
| 34 | + |
| 35 | + // Step 2: Deduplicate memberIds and calculate affiliations |
| 36 | + const uniqueMemberIds = Array.from(new Set(memberOrganizations.map((mo) => mo.memberId))) |
| 37 | + for (const chunk of chunkArray(uniqueMemberIds, BATCH_SIZE)) { |
| 38 | + await Promise.all(chunk.map((memberId) => calculateMemberAffiliations(memberId))) |
| 39 | + } |
| 40 | + |
| 41 | + // Step 3: Continue pagination |
| 42 | + await continueAsNew<typeof blockOrganizationAffiliation>({ |
| 43 | + ...args, |
| 44 | + offset: OFFSET + MEMBERS_PER_RUN, |
| 45 | + }) |
| 46 | +} |
0 commit comments