"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateWorksheetZonePicking = void 0;
const sales_base_1 = require("@things-factory/sales-base");
const worksheet_base_1 = require("@things-factory/worksheet-base");
const warehouse_base_1 = require("@things-factory/warehouse-base");
const typeorm_1 = require("typeorm");
exports.generateWorksheetZonePicking = {
    async generateWorksheetZonePicking(_, { releaseGoods }, context) {
        const { user, domain, tx } = context.state;
        let worksheets = [];
        //fetch all orders
        let relatedReleaseGoods = await tx.getRepository(sales_base_1.ReleaseGood).find({
            where: {
                name: (0, typeorm_1.In)(releaseGoods),
                status: sales_base_1.ORDER_STATUS.PENDING_WORKSHEET,
                domain: domain
            }
        });
        //split by bizplace
        const bizplaces = new Set();
        relatedReleaseGoods.forEach(item => {
            bizplaces.add(item.bizplaceId);
        });
        for (const bizplace of bizplaces) {
            let bizplaceFilteredReleaseGoods = relatedReleaseGoods.filter(rg => rg.bizplaceId === bizplace);
            let releaseGoodIds = bizplaceFilteredReleaseGoods.map(rg => rg.id);
            //fetch all oi
            let orderInventories = await tx.getRepository(sales_base_1.OrderInventory).find({
                where: {
                    releaseGood: (0, typeorm_1.In)(releaseGoodIds)
                },
                relations: ['inventory', 'inventory.location']
            });
            let oiIds = orderInventories.map(item => item.id);
            let zones = await tx
                .getRepository(warehouse_base_1.Location)
                .createQueryBuilder('l')
                .select('DISTINCT l.zone', 'zone')
                .innerJoin('inventories', 'iv', 'iv.location_id = l.id')
                .innerJoin('order_inventories', 'oi', 'oi.inventory_id = iv.id')
                .where('oi.id in (:...ids)', { ids: oiIds })
                .getRawMany()
                .then(rows => rows.map(row => row.zone));
            //split by zone
            for (const zone of zones) {
                //generate worksheets by zone
                let zoneFilteredOi = orderInventories.filter(item => item.inventory.location.zone == zone);
                let worksheet = {
                    name: worksheet_base_1.WorksheetNoGenerator.generate(worksheet_base_1.WORKSHEET_TYPE.ZONE_PICKING),
                    type: worksheet_base_1.WORKSHEET_TYPE.ZONE_PICKING,
                    status: worksheet_base_1.WORKSHEET_STATUS.DEACTIVATED,
                    bizplace: bizplace,
                    domain: domain,
                    creator: user,
                    updater: user,
                    createdAt: new Date(),
                    updatedAt: new Date(),
                    zone: zone
                };
                worksheet = await tx.getRepository(worksheet_base_1.Worksheet).save(worksheet);
                if ((zoneFilteredOi === null || zoneFilteredOi === void 0 ? void 0 : zoneFilteredOi.length) > 0) {
                    worksheet.worksheetDetails = [];
                    for (const oi of zoneFilteredOi) {
                        //generate worksheet detail for all OIs in the group
                        const worksheetDetail = {
                            name: worksheet_base_1.WorksheetNoGenerator.generateDetail(worksheet_base_1.WORKSHEET_TYPE.ZONE_PICKING),
                            domain: domain,
                            bizplace: bizplace,
                            worksheet: worksheet,
                            type: worksheet_base_1.WORKSHEET_TYPE.ZONE_PICKING,
                            status: worksheet_base_1.WORKSHEET_STATUS.DEACTIVATED,
                            targetInventory: oi,
                            creator: user,
                            updater: user,
                            createdAt: new Date(),
                            updatedAt: new Date()
                        };
                        await tx.getRepository(worksheet_base_1.WorksheetDetail).save(worksheetDetail);
                        worksheet.worksheetDetails.push(Object.assign({}, worksheetDetail));
                    }
                    //update for all OIs
                    await tx.getRepository(sales_base_1.OrderInventory).update({ id: (0, typeorm_1.In)(zoneFilteredOi.map(oi => oi.id)) }, {
                        refWorksheetId: worksheet.id,
                        status: sales_base_1.ORDER_INVENTORY_STATUS.READY_TO_PICK,
                        updater: user,
                        updatedAt: new Date()
                    });
                }
                worksheets.push(worksheet);
            }
            await tx.getRepository(sales_base_1.ReleaseGood).update({ id: (0, typeorm_1.In)(bizplaceFilteredReleaseGoods.map(rg => rg.id)) }, {
                status: sales_base_1.ORDER_STATUS.READY_TO_PICK,
                updater: user,
                updatedAt: new Date()
            });
            await tx.getRepository(sales_base_1.ReleaseGood).update({ id: (0, typeorm_1.In)(bizplaceFilteredReleaseGoods.map(rg => rg.id)) }, {
                status: sales_base_1.ORDER_STATUS.READY_TO_PICK,
                updater: user,
                updatedAt: new Date()
            });
        }
        return worksheets;
    }
};
//# sourceMappingURL=generate-zone-worksheet.js.map