async function activate()

in api/v1/src/accounts/dataManager.js [586:693]


async function activate(projectId, host, token, reason, email) {
    try {
        console.log(`Activate called for token: ${token} for email: ${email}`);
        const procurementUtil = new CommerceProcurementUtil(projectId);
        const registration = await register(host, token);
        console.log(`registration: ${JSON.stringify(registration)}`);
        if (registration.success === true) {
            console.log('Registration success');
            const accountId = registration.data.payload.sub;
            const accountName = procurementUtil.getAccountName(projectId, accountId);
            const accountRecord = { accountName: accountName };
            console.log(`accountName: ${accountName}`);

            // Must approve the account first, before approving the entitlement.
            const approval = await procurementUtil.approveAccount(accountName, approvalName, reason);
            let newPolicies = [];

            try {
                // Create filter for the list entitlements request, filtering on the current user procurement account id
                // where the entitlement is in pending state = 'ENTITLEMENT_ACTIVATION_REQUESTED'
                let accountFilter = `account=${accountId}`;
                const filterString = `state=ENTITLEMENT_ACTIVATION_REQUESTED AND (${accountFilter})`;
                const result = await procurementUtil.listEntitlements(filterString);
                if (result) {
                    let entitlements = result.entitlements || [];
                    if (entitlements && entitlements.length > 0) {
                        const policyManager = require('../policies/dataManager');
                        for (const entitlement of entitlements) {
                            const entitlementName = entitlement.name;
                            const product = entitlement.product;
                            const plan = entitlement.plan;
                            console.log(`${entitlementName} is pending activation for product: ${product} and plan: ${plan}`);

                            // Check the policy table to see if there is a policy object matching the marketplace product and plan
                            const policy = await policyManager.findMarketplacePolicy(projectId, product, plan);
                            console.log(`Found policy ${JSON.stringify(policy, null, 3)}`);
                            if (policy && policy.marketplace) {
                                const enableAutoApprove = policy.marketplace.enableAutoApprove;

                                // If enableAutoApprove is set to true, approve the entitlement via the procurement api
                                if (enableAutoApprove === true) {
                                    await procurementUtil.approveEntitlement(entitlementName);

                                    // Append the policyId to the new list of policies to add to the Datashare user account
                                    console.log(`Appending policyId to new list: ${policy.policyId}`);
                                    newPolicies.push(policy.policyId);
                                }
                            }
                        }
                    }
                }
            } catch (err) {
                console.error(`Failed to auto approve entitlement(s) for user: ${err}`);
            }

            // Insert the account records
            let account = await getAccount(projectId, null, email, 'user');
            if (account) {
                if (account.policies) {
                    account.policies = account.policies.map(e => e.policyId);
                }
                if (account.marketplace) {
                    const found = underscore.findWhere(account.marketplace, accountRecord);
                    if (!found) {
                        account.marketplace.push(accountRecord);
                    }
                } else {
                    account.marketplace = [accountRecord];
                }
                account.createdBy = email;
            } else {
                // Create the account
                account = {
                    email: email,
                    emailType: 'user',
                    createdBy: email,
                    marketplace: [accountRecord]
                };
            }

            if (newPolicies.length > 0) {
                // Initialize policies array if necessary
                if (!account.policies) {
                    console.log(`Initializing policies array`);
                    account.policies = [];
                }

                newPolicies.forEach(p => {
                    const found = account.policies.includes(p);
                    if (!found) {
                        account.policies.push(p);
                        console.log(`Added policy: ${p}`);
                    } else {
                        console.log(`Policy already in array: ${p}`);
                    }
                });
            }

            // This will create or update the account. At this point no new policies will be associated.
            await createOrUpdateAccount(projectId, null, account);

            return { success: true, code: 200, data: approval };
        }
    } catch (err) {
        console.error(err);
        return { success: false, code: 500, errors: ['Failed to approve account'] };
    }
}