"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UploadsService = void 0;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const XLSX = __importStar(require("xlsx"));
const mongoose_1 = __importDefault(require("mongoose"));
const dayjs_1 = __importDefault(require("dayjs"));
const decimal_js_1 = __importDefault(require("decimal.js"));
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 validators_enums_1 = require("../enums/validators.enums");
const column_desciptions_helper_1 = require("../helpers/column-desciptions.helper");
const date_helper_1 = require("../helpers/date.helper");
const upload_types_enum_1 = require("../enums/upload-types.enum");
const BBCDate_model_1 = require("../models/BBCDate.model");
const AvailabilitySigns_model_1 = require("../models/AvailabilitySigns.model");
const ReceivableAvailability_model_1 = require("../models/ReceivableAvailability.model");
const BBCSheet_model_1 = require("../models/BBCSheet.model");
const InventoryManualEntry_model_1 = require("../models/InventoryManualEntry.model");
const UserLog_model_1 = require("../models/UserLog.model");
const microservice_tasks_db_1 = require("../db/microservice-tasks.db");
const microservice_task_enum_1 = require("../enums/microservice-task.enum");
const UploadedFile_model_1 = __importDefault(require("../models/UploadedFile.model"));
const UploadedSheet_model_1 = __importDefault(require("../models/UploadedSheet.model"));
const UploadedData_model_1 = __importDefault(require("../models/UploadedData.model"));
const inventory_item_1 = require("../classes/inventory-item");
const receivable_item_1 = require("../classes/receivable-item");
const payable_account_item_1 = require("../classes/payable-account-item");
const uploads_db_1 = require("../db/uploads.db");
const inventories_1 = require("../db/inventories");
const bank_transaction_item_1 = require("../classes/bank-transaction-item");
const Equipment_model_1 = __importDefault(require("../models/Equipment.model"));
const Reserve_model_1 = __importDefault(require("../models/Reserve.model"));
const quickbook_item_1 = require("../classes/quickbook-item");
const bank_uploaded_transaction_1 = require("../classes/bank-uploaded-transaction");
const sales_item_1 = require("../classes/sales-item");
const validators = {
    [validators_enums_1.EValidators.NOT_EMPTY]: (field, value) => {
        if (!value || value.toString().trim() === '') {
            return { error: `value ${field} must not be empty!` };
        }
    },
    [validators_enums_1.EValidators.NUMBER_GT_NULL]: (field, value) => {
        if (value === 0 || value < 0) {
            return { error: `value ${field} must be greater than 0!` };
        }
    },
    [validators_enums_1.EValidators.NUMBER_GTE_NULL]: (field, value) => {
        if (value < 0) {
            return { error: `value ${field} must be greater or equal 0!` };
        }
    },
    [validators_enums_1.EValidators.IS_NUMBER]: (field, value) => {
        if (typeof value === 'object' || isNaN(Number(value))) {
            return { error: `value ${field} must be number!` };
        }
    },
    [validators_enums_1.EValidators.IS_DATE]: (field, value) => {
        if (!value) {
            return;
        }
        if (value.toString().trim() !== '' && Object.prototype.toString.call((0, date_helper_1.convertAnyToDate)(value)) !== '[object Date]') {
            return { error: `value ${field} must be date!` };
        }
    },
};
class UploadsService {
    rootDir;
    bankUploadedTransactionsService;
    getCollateralsService;
    getLoanTransactionsService;
    getQuickbooksService;
    getLockService;
    userLogsService;
    borrowersDB;
    usersService;
    constructor(rootDir, bankUploadedTransactionsService, getCollateralsService, getLoanTransactionsService, getQuickbooksService, getLockService, userLogsService, borrowersDB, usersService) {
        this.rootDir = rootDir;
        this.bankUploadedTransactionsService = bankUploadedTransactionsService;
        this.getCollateralsService = getCollateralsService;
        this.getLoanTransactionsService = getLoanTransactionsService;
        this.getQuickbooksService = getQuickbooksService;
        this.getLockService = getLockService;
        this.userLogsService = userLogsService;
        this.borrowersDB = borrowersDB;
        this.usersService = usersService;
    }
    async createUploadFile(file, borrowerId, userId, uploadType) {
        const borrowerIdToWrite = new mongoose_1.default.Types.ObjectId(borrowerId);
        const newFile = {
            borrowerId: borrowerIdToWrite,
            filename: file.filename,
            originalName: file.originalname,
            userId,
            type: uploadType,
        };
        return await UploadedFile_model_1.default.create(newFile);
    }
    async convertFileToData(uploadedFileId) {
        const uploadedFile = await UploadedFile_model_1.default.findById(uploadedFileId).lean();
        if (!uploadedFile) {
            return;
        }
        const absolutePath = path_1.default.join(this.rootDir, 'uploads', uploadedFile.filename);
        let excelData;
        fs_1.default.readFile(absolutePath, async (err, data) => {
            if (err) {
                console.error({ err });
                return;
            }
            const xlsxOptions = { cellDates: true, dateNF: 'yyyy/mm/dd;@' };
            const workbook = XLSX.read(data, xlsxOptions);
            excelData = Object.keys(workbook.Sheets).reduce((acc, ws) => {
                const worksheet = workbook.Sheets[ws];
                const arrayList = XLSX.utils.sheet_to_json(worksheet, { header: 1, defval: null });
                const trimmedArray = this.trimExcelArray(arrayList);
                return { ...acc, [ws]: trimmedArray.map((arr) => Object.assign({}, arr)) };
            }, {});
            await Promise.all(Object.entries(excelData).map(async ([sheetName, sheetData]) => {
                const newSheet = {
                    fileId: new mongoose_1.default.Types.ObjectId(uploadedFileId),
                    sheetName: sheetName,
                    total: sheetData.length,
                };
                const createdSheet = await UploadedSheet_model_1.default.create(newSheet);
                sheetData.map(async (data, order) => {
                    const convertedData = Object.entries(data).reduce((acc, [key, value]) => {
                        return {
                            ...acc,
                            [key]: typeof value === 'number' ? new decimal_js_1.default(value).toDecimalPlaces(2).toNumber() : value,
                        };
                    }, {});
                    const newData = {
                        sheetId: new mongoose_1.default.Types.ObjectId(String(createdSheet._id)),
                        order,
                        data: convertedData,
                    };
                    await UploadedData_model_1.default.create(newData);
                });
            }));
            fs_1.default.unlink(absolutePath, async (err) => {
                if (err) {
                    console.error(err);
                }
            });
        });
    }
    async convertDataToFile(dataToConvert) {
        return (0, excel_helper_1.convertDataToFile)(dataToConvert);
    }
    async convertDataToFileWithStyleOld(dataToConvert, options) {
        return (0, excel_helper_1.convertDataToFileWithStyleOld)(dataToConvert, options);
    }
    async deleteFile(uploadedFileId) {
        await UploadedFile_model_1.default.deleteOne({ _id: uploadedFileId });
    }
    async deleteSheet(uploadedSheetId) {
        const sheet = await UploadedSheet_model_1.default.findById(uploadedSheetId).lean();
        const file = await UploadedFile_model_1.default.findById(sheet.fileId).lean();
        const borrowerId = file.borrowerId ? file.borrowerId.toString() : null;
        await UploadedSheet_model_1.default.deleteOne({ _id: uploadedSheetId });
        await UploadedData_model_1.default.deleteMany({ sheetId: uploadedSheetId });
        const sheets = await UploadedSheet_model_1.default.find({ fileId: file._id });
        if (!sheets.length) {
            await UploadedFile_model_1.default.deleteOne({ _id: file._id });
        }
        return await this.getUploadedSheets(borrowerId, file.type);
    }
    async deleteAllSheets(uploadType) {
        const files = await UploadedFile_model_1.default.find({ type: uploadType });
        const fileIds = files.map((i) => i._id);
        const sheets = await UploadedSheet_model_1.default.find({ fileId: { $in: fileIds } });
        const sheetIds = sheets.map((i) => i._id);
        await UploadedSheet_model_1.default.deleteMany({ _id: { $in: sheetIds } });
        await UploadedData_model_1.default.deleteMany({ sheetId: { $in: sheetIds } });
        await UploadedFile_model_1.default.deleteMany({ _id: { $in: fileIds } });
    }
    trimExcelArray(data) {
        let dataFiltered = data.filter((arr) => arr.some((elem) => elem !== null && elem !== 0 && elem.toString().trim() !== ''));
        if (!dataFiltered.length) {
            return [];
        }
        const dataRotated = dataFiltered[0].map((_, index) => dataFiltered.map(row => row[index]).reverse());
        let dataRotatedFiltered = dataRotated.filter((arr) => arr.some((elem) => elem !== null && elem !== 0 && elem.toString().trim() !== ''));
        return dataRotatedFiltered[0].map((_, index) => dataRotatedFiltered.map((row) => row[row.length - 1 - index]));
    }
    async getUploadedRawFiles(borrowerId, uploadType) {
        const findFilter = uploadType === upload_types_enum_1.EUploadTypes.BBC
            ? { borrowerId, type: uploadType }
            : { type: uploadType };
        const uploadedFiles = await UploadedFile_model_1.default.find(findFilter).lean();
        const files = await Promise.all(uploadedFiles.map(async (file) => {
            const sheets = await UploadedSheet_model_1.default.find({ fileId: file._id });
            if (!sheets.length) {
                return file;
            }
        }));
        return files.filter((file) => !!file);
    }
    async getUploadedSheets(borrowerId, uploadType) {
        const borrowerFilter = uploadType === upload_types_enum_1.EUploadTypes.BBC ? { borrowerId: new mongoose_1.default.Types.ObjectId(borrowerId) } : {};
        const files = await UploadedFile_model_1.default.aggregate([
            {
                $match: {
                    ...borrowerFilter,
                    'type': uploadType,
                },
            }, {
                $sort: {
                    'createdAt': 1,
                },
            },
        ]);
        const fileIds = files.map((file) => file._id);
        const sheets = await UploadedSheet_model_1.default.aggregate([
            {
                $match: {
                    'fileId': {
                        $in: fileIds,
                    },
                },
            }, {
                $lookup: {
                    from: 'uploadedfiles',
                    localField: 'fileId',
                    foreignField: '_id',
                    as: 'file',
                },
            }, {
                $unwind: {
                    path: '$file',
                },
            }, {
                $sort: {
                    'createdAt': 1,
                },
            },
        ]);
        return sheets.map((sheet) => {
            return {
                _id: sheet._id,
                sheetName: sheet.sheetName,
                fileId: sheet.file._id,
                fileName: sheet.file.originalName,
                total: sheet.total,
            };
        });
    }
    async getUploadedData(sheetId, paginatorOptions) {
        const uploadedData = await UploadedData_model_1.default.aggregate([
            {
                $match: {
                    'sheetId': new mongoose_1.default.Types.ObjectId(sheetId),
                },
            }, {
                $sort: {
                    'order': 1,
                },
            },
            ...(0, collaterals_db_1.ITEMS_PAGINATION)(paginatorOptions),
        ]);
        const totalItems = (await UploadedSheet_model_1.default.findById(sheetId)).total;
        return {
            paginatorOptions,
            totalItems,
            items: uploadedData.map((row) => row.data),
        };
    }
    transformNumberIntoDate(mappedRow, collateralType) {
        const dateFields = column_desciptions_helper_1.COLLATERALS[collateralType].filter((field) => field.isDate).map((field) => field.db_title);
        Object.entries(mappedRow).forEach(([key, value]) => {
            if (dateFields.includes(key) && typeof value === 'number') {
                mappedRow[key] = (0, date_helper_1.excelDateToJSDate)(value);
            }
        });
        return mappedRow;
    }
    validateRow(mappedRow, collateralType) {
        try {
            const rowValidationErrors = [];
            Object.entries(mappedRow).forEach(([field, value]) => {
                const foundDesc = column_desciptions_helper_1.COLLATERALS[collateralType].find((columnDesc) => field === columnDesc.db_title);
                const fieldValidationErrors = [];
                if (!foundDesc) {
                    return;
                }
                if (foundDesc.validators) {
                    foundDesc.validators.forEach((validator) => {
                        const validationError = validators[validator](field, value);
                        if (!!validationError) {
                            fieldValidationErrors.push(validationError);
                        }
                    });
                }
                if (fieldValidationErrors.length) {
                    rowValidationErrors.push({ [field]: fieldValidationErrors });
                }
            });
            return rowValidationErrors;
        }
        catch (e) {
            console.error(e);
            return [{ row: e }];
        }
    }
    async mapData(mapData, paginators) {
        const mappedData = await this.prepareData(mapData);
        const hasDateMismatch = mappedData.approved.items.some((item) => {
            if ((0, dayjs_1.default)(item.date).format('YYYY-MM-DD') !== mapData.effectiveDate) {
            }
            return (0, dayjs_1.default)(item.date).format('YYYY-MM-DD') !== mapData.effectiveDate;
        });
        const paginateItems = (items, paginator) => {
            const startItem = paginator.pageIndex * paginator.pageSize;
            return items.slice(startItem, startItem + paginator.pageSize);
        };
        return Object.keys(mappedData).reduce((acc, key) => {
            return {
                ...acc,
                hasDateMismatch,
                [key]: {
                    totalItems: mappedData[key].totalItems,
                    items: paginateItems(mappedData[key].items, paginators[key]),
                    paginatorOptions: paginators[key],
                },
            };
        }, {});
    }
    async convertData(mapData, userId) {
        const { approved } = await this.prepareData(mapData);
        const fileData = await (0, uploads_db_1.getSheetWithFile)(mapData.sheetId);
        const borrowerId = fileData[0].file.borrowerId?.toString() ?? null;
        const bbcDate = dayjs_1.default.utc(mapData.bbcDate).startOf('day').toDate();
        if (borrowerId) {
            const lockService = this.getLockService();
            const isDateLocked = await lockService.isDateLocked(bbcDate, borrowerId);
            if (isDateLocked) {
                return { success: false, message: 'This period is signed and locked', data: null };
            }
        }
        const newCollateralData = {
            borrowerId,
            bbcDate,
            fileName: fileData[0].file.originalName,
            sheetName: fileData[0].sheetName,
            items: approved.items,
        };
        const uploadOption = {
            fileName: fileData[0].file.originalName,
            sheetName: fileData[0].sheetName,
            effectiveDate: mapData.effectiveDate,
        };
        try {
            let taskId;
            switch (mapData.sheetType) {
                case collaterals_enum_1.ECollaterals.LOAN_TRANSACTIONS: {
                    const loanTransactionsService = this.getLoanTransactionsService();
                    await loanTransactionsService.uploadLoanTransactions(newCollateralData.items, uploadOption, userId);
                    await this.userLogsService.createUserLog({
                        userId,
                        logType: UserLog_model_1.ELogType.TRANSACTIONS_UPLOAD,
                        action: UserLog_model_1.ELogActionType.UPLOAD,
                        details: { mapData, uploadOption },
                    });
                    break;
                }
                case collaterals_enum_1.ECollaterals.QUICKBOOKS: {
                    const quickbooksService = this.getQuickbooksService();
                    await quickbooksService.uploadAccounts(newCollateralData.items, true);
                    break;
                }
                case collaterals_enum_1.ECollaterals.UPLOADED_BANK_TRANSACTIONS: {
                    taskId = await this.bankUploadedTransactionsService.uploadTransactions(newCollateralData.items);
                    break;
                }
                default: {
                    const collateralsService = this.getCollateralsService();
                    const bbcDateId = await collateralsService.saveCollateralItems(newCollateralData, collaterals_enum_1.ECollaterals[mapData.sheetType]);
                    const user = await this.usersService.getUserById(userId);
                    if (user) {
                        const params = {
                            borrowerId: new mongoose_1.default.Types.ObjectId(borrowerId),
                            bbcDateId,
                            userId,
                        };
                        await (0, microservice_tasks_db_1.createMicroserviceTasks)(microservice_task_enum_1.EMicroserviceTask.POST_UPLOAD, params);
                    }
                    await this.userLogsService.createUserLog({
                        userId,
                        logType: UserLog_model_1.ELogType.COLLATERAL_UPLOAD,
                        action: UserLog_model_1.ELogActionType.UPLOAD,
                        details: { mapData, uploadOption, borrowerId, bbcDate },
                    });
                    break;
                }
            }
            await this.removeConvertedData(mapData.sheetId);
            return { success: true, message: 'Successfully uploaded', data: { taskId } };
        }
        catch (e) {
            console.error({ e });
            return { success: false, message: 'Error while uploading', data: null };
        }
    }
    async prepareData(mapData) {
        const { startRow, endRow, bbcDate, sheetType, mappedColumns, sheetId } = mapData;
        const excelData = await this.getUploadedData(sheetId);
        const SLICED_DATA = excelData.items.slice(startRow - 1, endRow);
        const MAPPED_DATA = (SLICED_DATA.reduce((acc, row) => {
            const RES = Object.entries(mappedColumns).reduce((result, [key, value]) => {
                if (value !== null) {
                    return { ...result, [key]: row[value] ?? null };
                }
                return result;
            }, {});
            return [...acc, RES];
        }, []));
        let skuDates = [];
        if (mapData.sheetType === collaterals_enum_1.ECollaterals.INVENTORY) {
            const uploadedSheet = await UploadedSheet_model_1.default.findById(mapData.sheetId).lean();
            const uploadedFile = await UploadedFile_model_1.default.findById(uploadedSheet.fileId).lean();
            skuDates = await (0, inventories_1.getAllTimeOldestSKUDateNew)(uploadedFile.borrowerId.toString(), mapData.bbcDate);
        }
        const approvedItems = [];
        const removedItems = [];
        try {
            await Promise.all(MAPPED_DATA.map(async (row, index) => {
                const extraErrors = [];
                const mappedCollateralTypes = {
                    [collaterals_enum_1.ECollaterals.INVENTORY]: () => new inventory_item_1.InventoryItem(row, bbcDate, skuDates),
                    [collaterals_enum_1.ECollaterals.RECEIVABLE]: () => new receivable_item_1.ReceivableItem(row, bbcDate),
                    [collaterals_enum_1.ECollaterals.ACCOUNT_PAYABLE]: () => new payable_account_item_1.PayableAccountItem(row, bbcDate),
                    [collaterals_enum_1.ECollaterals.SALES]: () => new sales_item_1.SalesItem(row, bbcDate, mapData.extraOptions),
                    [collaterals_enum_1.ECollaterals.LOAN_TRANSACTIONS]: async () => {
                        const newItem = new bank_transaction_item_1.LoanTransactionItem(row, this.borrowersDB);
                        const classErrors = await newItem.initialize();
                        if (classErrors.length) {
                            classErrors.forEach((error) => extraErrors.push(error));
                        }
                        const cleanItem = { ...newItem, transactionType: '' };
                        cleanItem.transactionType = newItem.isStatement ? 'STATEMENT' : newItem.transactionType;
                        delete cleanItem.isStatement;
                        return cleanItem;
                    },
                    [collaterals_enum_1.ECollaterals.UPLOADED_BANK_TRANSACTIONS]: async () => new bank_uploaded_transaction_1.BankUploadedTransactionItem({
                        ...row,
                        order: index,
                    }, mapData.extraOptions),
                    [collaterals_enum_1.ECollaterals.QUICKBOOKS]: async () => {
                        const newItem = new quickbook_item_1.IQuickbooksUploadItem(row, mapData.extraOptions);
                        const classErrors = await newItem.initialize();
                        if (classErrors.length) {
                            classErrors.forEach((error) => extraErrors.push(error));
                        }
                        return newItem;
                    },
                };
                const item = await mappedCollateralTypes[collaterals_enum_1.ECollaterals[sheetType]]();
                const mappedRow = this.transformNumberIntoDate(item, collaterals_enum_1.ECollaterals[sheetType]);
                const validationErrors = this.validateRow(mappedRow, collaterals_enum_1.ECollaterals[sheetType]);
                const allErrors = [...extraErrors, ...validationErrors];
                if (allErrors.length) {
                    const errors = allErrors.map((errorValues) => {
                        return Object.values(errorValues).reduce((acc, obj) => {
                            const errorsV = obj.map((v) => v.error);
                            return [...acc, errorsV];
                        }, []);
                    });
                    removedItems[index] = {
                        ...row,
                        checked: true,
                        validationErrors: errors.join(', '),
                    };
                }
                else {
                    approvedItems[index] = mappedRow;
                }
            }));
            const approvedItemsOnly = approvedItems.filter(Boolean);
            const removedItemsOnly = removedItems.filter(Boolean);
            return {
                approved: {
                    items: approvedItemsOnly,
                    totalItems: approvedItemsOnly.length,
                },
                removed: {
                    items: removedItemsOnly,
                    totalItems: removedItemsOnly.length,
                },
            };
        }
        catch (e) {
            console.error(e);
            throw new Error('error while loading');
        }
    }
    async removeConvertedData(sheetId) {
        try {
            const uploadedFile = await UploadedSheet_model_1.default.findById(sheetId);
            const fileId = uploadedFile.fileId;
            await UploadedSheet_model_1.default.deleteOne({ _id: sheetId });
            await UploadedData_model_1.default.deleteMany({ sheetId: sheetId });
            const siblingsSheets = await UploadedSheet_model_1.default.find({ fileId });
            if (!siblingsSheets.length) {
                await UploadedFile_model_1.default.deleteOne({ _id: fileId });
            }
        }
        catch (e) {
            console.error({ e });
        }
    }
    async removeEntriesWithoutFiles() {
        try {
            const uploadedFiles = await UploadedFile_model_1.default.find({});
            await Promise.all(uploadedFiles.map(async (file) => {
                const sheets = await UploadedSheet_model_1.default.find({ fileId: file._id });
                if (!sheets.length) {
                    await UploadedFile_model_1.default.findByIdAndDelete(file._id);
                }
            }));
        }
        catch (e) {
            console.error({ e });
        }
    }
    async cleanUploads() {
        try {
            fs_1.default.readdir(path_1.default.join(this.rootDir, 'uploads'), async (err, files) => {
                await Promise.all(files.map((file) => {
                    fs_1.default.unlink(path_1.default.join(this.rootDir, 'uploads', file), (err) => {
                        if (err) {
                            console.error({ err });
                        }
                    });
                }));
            });
            await UploadedFile_model_1.default.deleteMany();
            await UploadedSheet_model_1.default.deleteMany();
            await UploadedData_model_1.default.deleteMany();
        }
        catch (e) {
            console.error({ e });
        }
    }
    async removeEmptyBBC(remove = false) {
        const bbcDates = await BBCDate_model_1.BBCDateModel.find().lean();
        for (const bbcDate of bbcDates) {
            const sheets = await BBCSheet_model_1.BBCSheetModel.find({ bbcDateId: bbcDate._id });
            if (sheets.length === 0) {
                console.log(bbcDate._id.toString(), 'can be deleted');
                if (remove) {
                    await BBCDate_model_1.BBCDateModel.findByIdAndDelete(bbcDate._id);
                    await AvailabilitySigns_model_1.AvailabilitySignsModel.deleteMany({ bbcDateId: bbcDate._id });
                    await Equipment_model_1.default.deleteMany({ bbcDateId: bbcDate._id });
                    await InventoryManualEntry_model_1.InventoryManualEntryModel.deleteMany({ bbcDateId: bbcDate._id.toString() });
                    await ReceivableAvailability_model_1.ReceivableAvailabilityModel.deleteMany({ bbcDateId: bbcDate._id });
                    await Reserve_model_1.default.deleteMany({ bbcDateId: bbcDate._id });
                }
            }
        }
    }
}
exports.UploadsService = UploadsService;
