"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getGroupedReceivables = exports.getGroupedReceivablesFull = void 0;
const dayjs_1 = __importDefault(require("dayjs"));
const excel_helper_1 = require("../../helpers/excel.helper");
const collaterals_db_1 = require("../../db/collaterals.db");
const collaterals_enum_1 = require("../../enums/collaterals.enum");
const mongoose_1 = __importDefault(require("mongoose"));
const column_desciptions_helper_1 = require("../../helpers/column-desciptions.helper");
const BBCDate_model_1 = require("../../models/BBCDate.model");
const partially_paid_restated_1 = require("./partially-paid-restated");
const getGroupedReceivablesFull = async (params) => {
    const data = await (0, exports.getGroupedReceivables)(params);
    const header = getGroupedReceivablesHeader();
    return (0, excel_helper_1.addHeaderToData)(header, data);
};
exports.getGroupedReceivablesFull = getGroupedReceivablesFull;
const getGroupedReceivables = async (params) => {
    const { borrowerId, bbcDateId, extraParams } = params;
    const { calculateDueDate } = extraParams;
    const sheets = await (0, collaterals_db_1.findCollateralSheets)(bbcDateId.toString(), collaterals_enum_1.ECollaterals.RECEIVABLE);
    return await Promise.all(sheets.map(async (sheet) => {
        const data = await (0, collaterals_db_1.findCollaterals)(sheet._id.toString(), false);
        const customerTitleIndex = column_desciptions_helper_1.COLLATERALS[collaterals_enum_1.ECollaterals.RECEIVABLE].findIndex((column) => column.db_title === 'customerTitle');
        const columnsShort = column_desciptions_helper_1.COLLATERALS[collaterals_enum_1.ECollaterals.RECEIVABLE]
            .map((c) => ({ db_title: c.db_title, title: c.title }))
            .filter((c) => c.db_title !== 'bbcDate');
        columnsShort.splice(customerTitleIndex, 0, { db_title: 'customerGroup', title: 'Customer group' });
        columnsShort.push({ db_title: 'partiallyPaid', title: 'Partially paid' });
        const columnDB = columnsShort.map((c) => c.db_title);
        const bbcDate = await BBCDate_model_1.BBCDateModel.findById(bbcDateId).lean();
        const startDate = (0, dayjs_1.default)(new Date(bbcDate.bbcDate)).subtract(180, 'day').toDate();
        const endDate = new Date(bbcDate.bbcDate);
        const { partiallyPaidInvoices } = await (0, partially_paid_restated_1.getPartialPaid)({ borrowerId: new mongoose_1.default.Types.ObjectId(borrowerId), startDate, endDate });
        const dataWithPartiallyPaid = data.map((invoice) => {
            let partiallyPaid = false;
            const foundInvoice = partiallyPaidInvoices.find((pInvoice) => {
                return (pInvoice.invoiceNumber === invoice.invoiceNumber) && (pInvoice.customer === invoice.customerTitle);
            });
            if (foundInvoice) {
                partiallyPaid = foundInvoice.difference > 0;
            }
            if ((invoice.originalAmount !== 0) && (invoice.originalAmount !== invoice.invoiceAmount)) {
                partiallyPaid = true;
            }
            return {
                ...invoice,
                partiallyPaid,
                dueDate: calculateDueDate ? (0, dayjs_1.default)(invoice.invoiceDate).utcOffset(0).add(90, 'days').toDate() : invoice.dueDate,
            };
        });
        const shortData = (0, collaterals_db_1.excludeNoDataColumns)(dataWithPartiallyPaid, columnDB);
        const dataWithGroups = await (0, collaterals_db_1.addCustomerGroups)(shortData, borrowerId.toString());
        return { [sheet.sheetName]: dataWithGroups };
    }));
};
exports.getGroupedReceivables = getGroupedReceivables;
const getGroupedReceivablesHeader = () => {
    return {
        sheetName: 'Sheet name',
        invoiceNumber: 'Invoice number',
        invoiceDate: 'Invoice date',
        customerTitle: 'Customer title',
        customerGroup: 'Customer group',
        invoiceAmount: 'Invoice amount',
        dueDate: 'Due date',
        invoiceDetail1: 'Invoice detail 1',
        invoiceDetail2: 'Invoice detail 2',
        invoiceDetail3: 'Invoice detail 3',
        partiallyPaid: 'Partially paid',
    };
};
