File size: 1,845 Bytes
6147b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
708bb91
6147b1b
 
 
 
 
 
708bb91
6147b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
708bb91
6147b1b
 
 
 
 
 
 
 
fbb83a2
6147b1b
 
 
 
 
d747060
 
6147b1b
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

import { logger } from '../../utils/logger';

import { fetchGLAccountsForSync } from './propertyware.service';
import PWGlaccounts from '../../models/pwGlaccounts';

const ExpenseAccountTypes = ['Expense', 'Income', 'Current Liability', 'Current Asset', 'Equity'];

const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

export const syncGlAccountsFromJsonService = async (): Promise<string> => {
    const allGlAccounts = [];
    let offset = 0;
    const limit = 500;
    const includeDeactivated = false;

    try {
        let totalRecords = 0;
        let response;

        do {
            response = await fetchGLAccountsForSync({ limit, offset, includeDeactivated });

            allGlAccounts.push(...response.data);

            if (response.headers && response.headers['x-total-count']) {
                totalRecords = parseInt(response.headers['x-total-count'], 10);
            }

            offset += limit;

            await sleep(1000);

        } while (allGlAccounts.length < totalRecords);

        const glAccountsResponseData = allGlAccounts
            // .filter((account) => ExpenseAccountTypes.includes(account.accountType))
            .map((account) => ({
                pw_id: account.id,
                name: account.name,
                account_number: account.accountNumber
            }));


        await PWGlaccounts.bulkCreate(glAccountsResponseData, {
            updateOnDuplicate: ['account_number'],
        });

        logger.info("Total " + glAccountsResponseData.length + " GL Accounts synced successfully");
        return "Total " + glAccountsResponseData.length + " GL Accounts synced successfully";
    } catch (error) {
        logger.error("Error syncing Gl Accounts");
        logger.error(error);
        throw new Error("Error syncing Gl Accounts");
    }
};