"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.QuickbooksService = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const dayjs_1 = __importDefault(require("dayjs"));
const decimal_js_1 = __importDefault(require("decimal.js"));
const lodash_1 = __importDefault(require("lodash"));
const loan_charge_type_enum_1 = require("../enums/loan-charge-type.enum");
const loan_types_enum_1 = require("../enums/loan-types.enum");
const LoanProducts_model_1 = require("../models/LoanProducts.model");
const Borrower_model_1 = require("../models/Borrower.model");
const TermLoan_model_1 = require("../models/TermLoan.model");
const reports_db_1 = require("../db/reports.db");
const QuickbooksAccount_model_1 = require("../models/QuickbooksAccount.model");
const date_helper_1 = require("../helpers/date.helper");
const headersIIF = [
    {
        service: '!TRNS',
        id: 'TRNSID',
        type: 'TRNSTYPE',
        date: 'DATE',
        account: 'ACCNT',
        class: 'CLASS',
        amount: 'AMOUNT',
        document: 'DOCNUM',
        memo: 'MEMO',
    },
    {
        service: '!SPL',
        id: 'SPLID',
        type: 'TRNSTYPE',
        date: 'DATE',
        account: 'ACCNT',
        class: 'CLASS',
        amount: 'AMOUNT',
        document: 'DOCNUM',
        memo: 'MEMO',
    },
    {
        service: '!ENDTRNS',
        id: '',
        type: '',
        date: '',
        account: '',
        class: '',
        amount: '',
        document: '',
        memo: '',
    },
];
const IIF = [
    {
        service: 'ENDTRNS',
        id: '',
        type: '',
        date: '',
        account: '',
        class: '',
        amount: '',
        document: '',
        memo: '',
    },
];
const headersCSV = () => {
    return {
        journalNumber: 'Journal No',
        journalDate: 'Journal Date',
        memo: 'Memo',
        account: 'Account',
        amount: 'Amount',
        description: 'Description',
        name: 'Name',
        location: 'Location',
        class: 'Class',
    };
};
const transactionsDateFormat = 'DDMMMYYYY';
const IIFDateFormat = 'M/D/YYYY';
class QuickbooksService {
    banksService;
    bankUploadedTransactionsService;
    borrowersDB;
    brokersService;
    cashAllocationService;
    companiesService;
    loanChargesService;
    loanPaymentsService;
    constructor(banksService, bankUploadedTransactionsService, borrowersDB, brokersService, cashAllocationService, companiesService, loanChargesService, loanPaymentsService) {
        this.banksService = banksService;
        this.bankUploadedTransactionsService = bankUploadedTransactionsService;
        this.borrowersDB = borrowersDB;
        this.brokersService = brokersService;
        this.cashAllocationService = cashAllocationService;
        this.companiesService = companiesService;
        this.loanChargesService = loanChargesService;
        this.loanPaymentsService = loanPaymentsService;
    }
    async uploadAccounts(accounts, deleteOld) {
        const accountsWithId = accounts.map((account) => ({ _id: 'new_', ...account }));
        await this.saveAccounts(accountsWithId, deleteOld);
    }
    async getAllAccounts() {
        return QuickbooksAccount_model_1.QuickbooksAccount
            .find({}, { createdAt: 0, updatedAt: 0, __v: 0 })
            .sort({ order: 1 }).lean();
    }
    async saveAccounts(accounts, deleteOld) {
        if (!accounts.length) {
            return;
        }
        if (deleteOld && accounts.length === 0) {
            throw new Error('Refusing to sync accounts: empty payload');
        }
        if (deleteOld) {
            const existingIds = accounts
                .filter((acc) => !acc._id.startsWith('new_'))
                .map((acc) => new mongoose_1.default.Types.ObjectId(acc._id));
            if (existingIds.length === 0) {
                await QuickbooksAccount_model_1.QuickbooksAccount.deleteMany({});
            }
            else {
                await QuickbooksAccount_model_1.QuickbooksAccount.deleteMany({
                    _id: { $nin: existingIds },
                });
            }
        }
        const accountSavePromises = accounts.map(async (account, order) => {
            if (account._id.startsWith('new_')) {
                const { _id, ...accountWithoutId } = account;
                return QuickbooksAccount_model_1.QuickbooksAccount.create({ ...accountWithoutId, order });
            }
            else {
                return QuickbooksAccount_model_1.QuickbooksAccount.findByIdAndUpdate(account._id, { ...account, order }, { new: true, upsert: true });
            }
        });
        return Promise.all(accountSavePromises);
    }
    async getAllProducts() {
        const borrowers = await this.borrowersDB.getActiveBorrowers();
        const borrowerIds = borrowers.map((borrower) => borrower._id);
        return LoanProducts_model_1.LoanProduct.aggregate([
            {
                '$match': {
                    borrowerId: { $in: borrowerIds },
                },
            }, {
                $lookup: {
                    from: 'borrowers',
                    localField: 'borrowerId',
                    foreignField: '_id',
                    as: 'borrower',
                },
            }, {
                $unwind: {
                    path: '$borrower',
                },
            }, {
                $project: {
                    '_id': 0,
                    'data': {
                        $mergeObjects: [
                            {
                                $arrayToObject: {
                                    $filter: {
                                        input: { $objectToArray: '$$ROOT' },
                                        cond: { $in: ['$$this.k', ['name', '_id', 'type']] },
                                    },
                                },
                            }, {
                                'clientName': '$borrower.name',
                                'productAccrualStatus': '$borrower.accrualStatus',
                            },
                        ],
                    },
                },
            }, {
                $replaceRoot: {
                    'newRoot': '$data',
                },
            }, {
                $project: {
                    '_id': 0,
                    'productId': '$_id',
                    'productName': '$name',
                    'productType': '$type',
                    'clientName': 1,
                    'productAccrualStatus': 1,
                },
            }, {
                $sort: {
                    'clientName': 1,
                    'order': 1,
                },
            }, {
                $addFields: {
                    'isSelected': null,
                },
            }, {
                $lookup: {
                    from: 'term_loans',
                    let: {
                        productIdVar: '$productId',
                        productTypeVar: '$productType',
                    },
                    pipeline: [
                        {
                            $match: {
                                $expr: {
                                    $and: [
                                        {
                                            $eq: [
                                                '$productId',
                                                '$$productIdVar',
                                            ],
                                        },
                                        {
                                            $ne: [
                                                '$$productTypeVar',
                                                'REVOLVER',
                                            ],
                                        },
                                        {
                                            $eq: ['$actual', true],
                                        },
                                    ],
                                },
                            },
                        },
                    ],
                    as: 'term',
                },
            }, {
                $unwind: {
                    path: '$term',
                    preserveNullAndEmptyArrays: true,
                },
            }, {
                $addFields: {
                    selectable: {
                        $cond: {
                            if: '$term',
                            then: {
                                $eq: [
                                    '$term.calculationStatus',
                                    'CALCULATED',
                                ],
                            },
                            else: true,
                        },
                    },
                },
            },
        ]);
    }
    async getChargeTransactionsForAccrual(productIds, reportDate) {
        if (productIds.length === 0) {
            return [];
        }
        const transactionsFilter = {
            productIds: productIds,
            start: (0, dayjs_1.default)(reportDate).utcOffset(0).startOf('month').toDate(),
            end: (0, dayjs_1.default)(reportDate).utcOffset(0).endOf('month').toDate(),
        };
        return await this.loanChargesService.getLoanStatementsForProduct(transactionsFilter);
    }
    async getChargeTransactionsForPayments(productIds, reportDate) {
        const start = (0, dayjs_1.default)(reportDate).utcOffset(0).startOf('day').toDate();
        const end = (0, dayjs_1.default)(reportDate).utcOffset(0).endOf('day').toDate();
        const payments = await this.loanPaymentsService.getPaymentsForPeriod(productIds, start, end);
        if (!payments.length) {
            return [];
        }
        const transactionIds = payments.reduce((acc, payment) => [...acc, ...payment.paid.map((p) => p.statementId)], []);
        const transactionsFilter = { productIds, transactionIds, start, end };
        return await this.loanChargesService.getLoanStatementsForIdsAndCharge(transactionsFilter);
    }
    async getPrincipalTransactionsForPayments(productId, reportDate) {
        const start = (0, dayjs_1.default)(reportDate).utcOffset(0).startOf('day').toDate();
        const end = (0, dayjs_1.default)(reportDate).utcOffset(0).endOf('day').toDate();
        const payments = await this.loanPaymentsService.getPaymentsForPeriod([productId], start, end);
        if (!payments.length) {
            return {};
        }
        return payments.reduce((acc, payment) => {
            const settlementCode = payment.settlementCode ? payment.settlementCode : null;
            const amount = payment.loanTransactions.reduce((acc, transaction) => new decimal_js_1.default(acc).add(transaction.amount).toNumber(), 0);
            return {
                ...acc,
                [settlementCode]: amount,
            };
        }, {});
    }
    async getQuickbooksReport(params) {
        const reportErrorsSet = new Set();
        await Promise.all(params.productIds.map(async (productId) => {
            const product = await this.loanChargesService.getLoanProductById(productId);
            if (product.type === loan_types_enum_1.ELoanTypes.TERM) {
                const termLoan = await TermLoan_model_1.TermLoanModel.findOne({ productId, actual: true }).lean();
                if (termLoan && termLoan.calculationStatus !== TermLoan_model_1.ETermLoanStatus.CALCULATED) {
                    reportErrorsSet.add(`${product.name} is not calculated`);
                }
            }
        }));
        if (reportErrorsSet.size > 0) {
            return { reportData: [], reportErrors: Array.from(reportErrorsSet) };
        }
        const companyFilter = { companyId: { $in: params.companyIds.map((id) => new mongoose_1.default.Types.ObjectId(id)) } };
        const { reportType, productIds, chargeTypes, reportDate } = params;
        const reportDateFormatted = (0, dayjs_1.default)(reportDate).utcOffset(0).format('MM/DD/YYYY').toUpperCase();
        const reportDateTrFormatted = (0, dayjs_1.default)(reportDate).utcOffset(0).format(transactionsDateFormat).toUpperCase();
        const currentDateTrFormatted = (0, dayjs_1.default)(new Date).utcOffset(0).format(transactionsDateFormat).toUpperCase();
        const isAccrual = reportType === 'accrual';
        const mainData = [];
        const trTemplate = {
            service: 'SPL',
            id: '',
            type: 'GENERAL JOURNAL',
            date: reportDateFormatted,
            account: '',
            class: '',
            amount: 0,
            document: '',
            memo: '',
        };
        await Promise.all(productIds.map(async (productId) => {
            const product = await this.loanChargesService.getLoanProductById(productId);
            const charges = await this.loanChargesService.getLoanChargeForProduct(productId);
            const filteredCharges = charges.filter((charge) => chargeTypes.includes(charge.chargeType));
            const productBrokers = await this.brokersService.getProductBrokers(productId);
            const borrower = await Borrower_model_1.BorrowerModel.findById(product.borrowerId).lean();
            const allTransactions = isAccrual
                ? await this.getChargeTransactionsForAccrual([productId], reportDate)
                : await this.getChargeTransactionsForPayments([productId], reportDate);
            await Promise.all(filteredCharges.map(async (charge) => {
                const chargeTransactions = allTransactions.filter((tr) => tr.chargeId.toString() === charge._id.toString());
                if (!chargeTransactions.length) {
                    return;
                }
                const totalAmountGroups = isAccrual
                    ? { [charge.PLCode]: chargeTransactions.reduce((acc, tr) => new decimal_js_1.default(acc).add(tr.amount).toNumber(), 0) }
                    : chargeTransactions.reduce((acc, tr) => {
                        if (tr.settlementCode) {
                            return {
                                ...acc,
                                [tr.settlementCode]: new decimal_js_1.default(acc[tr.settlementCode] || 0).add(tr.amount).toNumber(),
                            };
                        }
                        return {
                            ...acc,
                            [charge.PLCode]: new decimal_js_1.default(acc[charge.PLCode] || 0).add(tr.amount).toNumber(),
                        };
                    }, {});
                await Promise.all(Object.entries(totalAmountGroups).map(async ([PLCode, totalAmountValue]) => {
                    if (totalAmountValue === 0) {
                        return;
                    }
                    let totalAmount = product.masterLoanProductId != null ? -totalAmountValue : totalAmountValue;
                    totalAmount = isAccrual ? totalAmount : -totalAmount;
                    const quickbooksAccountBS = await QuickbooksAccount_model_1.QuickbooksAccount.findOne({ accountCode: charge.code, ...companyFilter }).lean();
                    const quickbooksAccountPL = await QuickbooksAccount_model_1.QuickbooksAccount.findOne({ accountCode: PLCode, ...companyFilter }).lean();
                    if (!quickbooksAccountBS || !quickbooksAccountPL) {
                        if (!quickbooksAccountBS) {
                            reportErrorsSet.add(charge.code);
                        }
                        if (!quickbooksAccountPL) {
                            reportErrorsSet.add(PLCode);
                        }
                        return;
                    }
                    const tr = {
                        ...trTemplate,
                        productId,
                        class: borrower.code,
                        memo: `${borrower.code} ${product.masterLoanProductId != null ? 'PARTICIPANT' : ''} ${reports_db_1.EChargeType[charge.chargeType].toUpperCase()} ${product.type.toUpperCase()} - TRANS: ${reportDateTrFormatted} - POST: ${currentDateTrFormatted}`,
                    };
                    tr.account = quickbooksAccountBS.fullName;
                    tr.amount = totalAmount;
                    mainData.push({ ...tr });
                    tr.account = quickbooksAccountPL.fullName;
                    tr.amount = -totalAmount;
                    mainData.push({ ...tr });
                    if (chargeTypes.includes('BROKERS') && isAccrual) {
                        const handleFee = async (broker, shareName) => {
                            const quickbooksAccountBrokerBS = await QuickbooksAccount_model_1.QuickbooksAccount.findOne({ accountCode: broker.BSCode, ...companyFilter }).lean();
                            const quickbooksAccountBrokerPL = await QuickbooksAccount_model_1.QuickbooksAccount.findOne({ accountCode: broker.PLCode, ...companyFilter }).lean();
                            if (!quickbooksAccountBrokerBS || !quickbooksAccountBrokerPL) {
                                if (!quickbooksAccountBrokerBS) {
                                    reportErrorsSet.add(broker.BSCode);
                                }
                                if (!quickbooksAccountBrokerPL) {
                                    reportErrorsSet.add(broker.PLCode);
                                }
                                return;
                            }
                            const tr = {
                                ...trTemplate,
                                productId,
                                class: borrower.code,
                                amount: new decimal_js_1.default(-totalAmount).mul(broker[shareName]).toDP(2).toNumber(),
                                memo: `${borrower.code} ${reports_db_1.EChargeType[charge.chargeType].toUpperCase()} BROKER ${broker.order + 1}`,
                            };
                            tr.account = quickbooksAccountBrokerBS.fullName;
                            mainData.push({ ...tr });
                            tr.account = quickbooksAccountBrokerPL.fullName;
                            tr.amount = -tr.amount;
                            mainData.push({ ...tr });
                        };
                        const handlers = {
                            [loan_charge_type_enum_1.ELoanChargeType.ADMIN_FEE]: async (broker) => await handleFee(broker, 'adminShare'),
                            [loan_charge_type_enum_1.ELoanChargeType.INTEREST_FEE]: async (broker) => await handleFee(broker, 'interestShare'),
                            [loan_charge_type_enum_1.ELoanChargeType.OTHER]: async (broker) => await handleFee(broker, 'otherShare'),
                        };
                        await Promise.all(productBrokers.map(async (broker) => {
                            if (handlers[charge.chargeType]) {
                                await handlers[charge.chargeType](broker);
                            }
                        }));
                    }
                }));
            }));
            const principalPayments = isAccrual || product.type === loan_types_enum_1.ELoanTypes.REVOLVER
                ? {}
                : await this.getPrincipalTransactionsForPayments(productId, reportDate);
            await Promise.all(Object.entries(principalPayments).map(async ([settlementCode, amount]) => {
                const tr = {
                    ...trTemplate,
                    productId,
                    class: borrower.code,
                    amount: product.masterLoanProductId != null ? +amount : -+amount,
                    memo: `${borrower.code} ${product.masterLoanProductId != null ? 'PARTICIPANT' : ''} PRINCIPAL PAID TERM - TRANS: ${reportDateTrFormatted} - POST: ${currentDateTrFormatted}`,
                };
                if (settlementCode === 'null') {
                    const products = await this.loanChargesService.getLoanProducts(borrower._id.toString());
                    const revolverProduct = products.find((product) => product.type === loan_types_enum_1.ELoanTypes.REVOLVER && (0, date_helper_1.isProductActive)(product.startDate, product.deactivationDate, reportDate));
                    if (revolverProduct) {
                        settlementCode = revolverProduct.code;
                    }
                }
                const quickbooksAccountPaymentBS = await QuickbooksAccount_model_1.QuickbooksAccount.findOne({ accountCode: product.code, ...companyFilter }).lean();
                const quickbooksAccountPaymentPL = await QuickbooksAccount_model_1.QuickbooksAccount.findOne({ accountCode: settlementCode, ...companyFilter }).lean();
                if (!quickbooksAccountPaymentBS || !quickbooksAccountPaymentPL) {
                    if (!quickbooksAccountPaymentBS) {
                        reportErrorsSet.add(product.code);
                    }
                    if (!quickbooksAccountPaymentPL) {
                        reportErrorsSet.add(settlementCode);
                    }
                    return;
                }
                tr.account = quickbooksAccountPaymentBS.fullName;
                tr.amount = -tr.amount;
                mainData.push({ ...tr });
                tr.amount = -tr.amount;
                tr.account = quickbooksAccountPaymentPL.fullName;
                mainData.push({ ...tr });
            }));
        }));
        const groupedData = lodash_1.default.groupBy(mainData, (obj) => obj.service + obj.id + obj.type + obj.date + obj.account + obj.class + obj.document + obj.memo + obj.productId);
        const mergedData = Object.keys(groupedData).reduce((acc, key) => {
            const group = groupedData[key];
            const mergedObject = {
                account: group[0].account,
                class: group[0].class,
                date: group[0].date,
                document: group[0].document,
                memo: group[0].memo,
                service: group[0].service,
                type: group[0].type,
                id: group[0].id,
                amount: group.reduce((acc, curr) => new decimal_js_1.default(acc).add(+curr.amount).toNumber(), 0),
            };
            return [...acc, mergedObject];
        }, []);
        const reportData = (lodash_1.default.orderBy(mergedData, ['class', 'memo', 'account'], ['asc', 'asc', 'asc'])).filter((record) => record.amount !== 0);
        if (reportData.length > 0) {
            reportData[0].service = 'TRNS';
        }
        return { reportData, reportErrors: Array.from(reportErrorsSet).map((code) => `No account for ${code}`) };
    }
    async getQuickbooksCashReport(params) {
        const reportErrorsSet = new Set();
        const { reportType, productIds, chargeTypes, reportDate } = params;
        const reportDateFormatted = (0, dayjs_1.default)(reportDate).utcOffset(0).format('MM/DD/YYYY').toUpperCase();
        const reportDateTrFormatted = (0, dayjs_1.default)(reportDate).utcOffset(0).format(transactionsDateFormat).toUpperCase();
        const startDate = (0, dayjs_1.default)(reportDate).utcOffset(0).startOf('day').toDate();
        const endDate = (0, dayjs_1.default)(reportDate).utcOffset(0).endOf('day').toDate();
        const transactions = await this.bankUploadedTransactionsService.getUploadedBankTransactions(startDate, endDate);
        const { references, products } = await this.cashAllocationService.getAllCashAllocations();
        const allAccounts = await this.getAllAccounts();
        const companyAccounts = allAccounts.filter((acc) => acc.companyId?.toString() === params.companyId);
        const banks = await this.banksService.getBanks();
        const banksMap = new Map();
        banks.forEach((bank) => banksMap.set(bank.bankAccountNumber, bank));
        const reportData = transactions
            .reduce((acc, transaction) => {
            // if (!transaction.isConverted) { // TODO only for converted?
            //   return acc;
            // }
            if (transaction.splitTransactions.length) {
                const restTransaction = { ...transaction, splitMemo: '' };
                const splitTransactions = transaction.splitTransactions.map((splitTransaction) => {
                    restTransaction.amount = new decimal_js_1.default(restTransaction.amount).sub(splitTransaction.amount).toNumber();
                    return {
                        ...transaction,
                        reference: splitTransaction.reference,
                        amount: splitTransaction.amount,
                        splitMemo: splitTransaction.memo ?? '',
                    };
                });
                if (restTransaction.amount !== 0) {
                    return [...acc, restTransaction, ...splitTransactions];
                }
                return [...acc, ...splitTransactions];
            }
            return [...acc, { ...transaction, splitMemo: '' }];
        }, [])
            .reduce((acc, transaction) => {
            const foundReference = references.find((ref) => transaction.reference.toLowerCase().includes(ref.reference.toLowerCase()));
            if (!foundReference || !foundReference.cashAllocationProductId) {
                return acc;
            }
            const foundProduct = products.find((product) => product._id.toString() === foundReference.cashAllocationProductId.toString());
            const accounts = foundProduct.accounts[params.companyId];
            if (!accounts) {
                return acc;
            }
            const findAccountForBank = () => {
                const foundBank = banksMap.get(transaction.accountNumber);
                if (!foundBank) {
                    return null;
                }
                const accountCodeId = foundBank.ledgerAccountCodes[params.companyId];
                if (!accountCodeId) {
                    return null;
                }
                const account = companyAccounts.find((account) => account._id.toString() === accountCodeId.toString());
                return account;
            };
            if (!accounts.accountId1 || !accounts.accountId2) {
                return acc;
            }
            const account1 = accounts.accountId1 === 'BANK'
                ? findAccountForBank()
                : companyAccounts.find((acc) => acc._id.toString() === accounts.accountId1.toString());
            if (!account1) {
                return acc;
            }
            const account2 = accounts.accountId2 === 'BANK'
                ? findAccountForBank()
                : companyAccounts.find((acc) => acc._id.toString() === accounts.accountId2.toString());
            if (!account2) {
                return acc;
            }
            const reportTransactions = {
                type: 'GENERAL JOURNAL',
                date: (0, dayjs_1.default)(transaction.date).format(IIFDateFormat),
                class: foundProduct.class,
                amount: transaction.amount,
                document: '',
                location: foundProduct.location,
                id: '',
                service: 'SPL',
            };
            const reportTransactions1 = {
                ...reportTransactions,
                account: account1?.fullName ?? 'BANK',
                amount: -reportTransactions.amount,
                memo: +reportTransactions.amount > 0 ? foundProduct.DRMemo : foundProduct.CRMemo,
            };
            const reportTransactions2 = {
                ...reportTransactions,
                account: account2?.fullName ?? 'BANK',
                amount: reportTransactions.amount,
                memo: +reportTransactions.amount > 0 ? foundProduct.DRMemo : foundProduct.CRMemo,
            };
            return [...acc, reportTransactions1, reportTransactions2];
        }, []);
        if (reportData.length > 0) {
            reportData[0].service = 'TRNS';
        }
        return { reportData, reportErrors: Array.from(reportErrorsSet).map((code) => `No account for ${code}`) };
    }
    convertQuickbooksReport(reportData, format, memo) {
        switch (format) {
            case 'IIF': {
                const fullReport = [...headersIIF, ...reportData, ...IIF];
                let iifContent = '';
                const getReportString = (transaction) => {
                    const fields = [
                        transaction.service,
                        transaction.id,
                        transaction.type,
                        transaction.date,
                        transaction.account,
                        transaction.class,
                        transaction.amount,
                        transaction.document,
                        transaction.memo,
                    ];
                    const joinedString = fields.join('\t');
                    iifContent += `${joinedString}\n`;
                };
                fullReport.forEach(getReportString);
                return iifContent;
            }
            case 'CSV': {
                const ref = `REF${Math.floor(Math.random() * (999 - 100 + 1)) + 100}`;
                const qboReport = reportData.map((transaction) => ({
                    journalNumber: `${transaction.date} ${ref}`,
                    journalDate: transaction.date,
                    memo,
                    account: transaction.account,
                    amount: transaction.amount,
                    description: transaction.memo,
                    name: '',
                    location: transaction.location,
                    class: transaction.class,
                }));
                const fullReport = [headersCSV(), ...qboReport];
                return JSON.stringify({ fullReport });
            }
        }
    }
    async reassignAccounts() {
        const companies = await this.companiesService.getCompanies();
        const accounts = await QuickbooksAccount_model_1.QuickbooksAccount.find().lean();
        for (const [index, company] of companies.entries()) {
            if (index === 0) {
                await Promise.all(accounts.map(async (account) => {
                    await QuickbooksAccount_model_1.QuickbooksAccount.findByIdAndUpdate(account._id, { companyId: company._id });
                }));
            }
            else {
                await Promise.all(accounts.map(async (account) => {
                    const { _id, ...rest } = account;
                    console.log(rest);
                    const newAccount = new QuickbooksAccount_model_1.QuickbooksAccount({ ...rest });
                    newAccount.companyId = company._id;
                    await newAccount.save();
                }));
            }
        }
    }
}
exports.QuickbooksService = QuickbooksService;
