"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.warehouseReturn = void 0;
const uuid_1 = require("uuid");
const typeorm_1 = require("typeorm");
const sales_base_1 = require("@things-factory/sales-base");
const worksheet_base_1 = require("@things-factory/worksheet-base");
exports.warehouseReturn = {
    //this function is used for zone picking warehouse return
    //in this case, ro status will remain PROCESSING/PARTIAL_PROCESSING
    async warehouseReturn(_, { releaseGoodNo, worksheetDetails }, context) {
        const { domain, tx, user } = context.state;
        //find release order
        const releaseOrder = await tx.getRepository(sales_base_1.ReleaseGood).findOne({
            where: { domain, name: releaseGoodNo }
        });
        if (!releaseOrder) {
            throw new Error(`Release good not found`);
        }
        const existingWorksheet = await tx.getRepository(worksheet_base_1.Worksheet).findOne({
            where: { releaseGood: releaseOrder, type: worksheet_base_1.WORKSHEET_TYPE.WAREHOUSE_RETURN }
        });
        if (existingWorksheet) {
            throw new Error('Existing return worksheet exist for this order');
        }
        let orderInventories = worksheetDetails.map(wsd => wsd.relatedOrderInv);
        //find order inventories
        let foundOrderInventories = await tx.getRepository(sales_base_1.OrderInventory).find({
            where: { domain, id: (0, typeorm_1.In)(orderInventories.map(oi => oi.id)) },
            relations: [
                'inventory',
                'domain',
                'bizplace',
                'releaseGood',
                'product',
                'productDetail',
                'binLocation',
                'orderProduct'
            ]
        });
        let completedLoadingWsdIds = [];
        let returnOrderInventories = foundOrderInventories.flatMap(oi => {
            const matchingWorksheetDetail = worksheetDetails.find(wsd => wsd.relatedOrderInv.id === oi.id);
            if (!matchingWorksheetDetail)
                return [oi];
            if (matchingWorksheetDetail.returnQty < oi.releaseQty) {
                const remainingOI = Object.assign(Object.assign({}, oi), { id: undefined, name: sales_base_1.OrderNoGenerator.orderInventory(), status: sales_base_1.ORDER_INVENTORY_STATUS.RETURNING, releaseQty: matchingWorksheetDetail.returnQty, releaseUomValue: (oi.releaseUomValue / oi.releaseQty) * matchingWorksheetDetail.returnQty, pickedQty: oi.pickedQty - matchingWorksheetDetail.returnQty, sortedQty: oi.sortedQty - matchingWorksheetDetail.returnQty, updatedAt: new Date(), updater: user });
                oi.releaseQty = oi.releaseQty - matchingWorksheetDetail.returnQty;
                oi.releaseUomValue = oi.releaseUomValue - remainingOI.releaseUomValue;
                oi.pickedQty = oi.pickedQty - matchingWorksheetDetail.returnQty;
                oi.sortedQty = oi.sortedQty - matchingWorksheetDetail.returnQty;
                oi.updatedAt = new Date();
                oi.updater = user;
                return [oi, remainingOI];
            }
            else if (matchingWorksheetDetail.returnQty === oi.releaseQty) {
                oi.status = sales_base_1.ORDER_INVENTORY_STATUS.RETURNING;
                oi.updatedAt = new Date();
                oi.updater = user;
                completedLoadingWsdIds.push(oi.id);
                return [oi];
            }
        });
        //update current loading wsd status to done
        //for returnQty = releaseQty items
        await tx.getRepository(worksheet_base_1.WorksheetDetail).update({ targetInventory: (0, typeorm_1.In)(completedLoadingWsdIds) }, {
            status: worksheet_base_1.WORKSHEET_STATUS.DONE,
            updater: user,
            updatedAt: new Date()
        });
        await tx.getRepository(sales_base_1.OrderInventory).save(returnOrderInventories);
        //generate worksheet
        let returnWorksheet = {
            name: `RETURN-${(0, uuid_1.v4)()}`,
            type: worksheet_base_1.WORKSHEET_TYPE.WAREHOUSE_RETURN,
            status: worksheet_base_1.WORKSHEET_STATUS.DEACTIVATED,
            createdAt: new Date(),
            domain: releaseOrder.domainId,
            bizplace: releaseOrder.bizplaceId,
            releaseGood: releaseOrder,
            creator: user
        };
        await tx.getRepository(worksheet_base_1.Worksheet).save(returnWorksheet);
        //generate worksheet detail only for return order inventories
        const returnWorksheetDetails = returnOrderInventories
            .filter(oi => oi.status === sales_base_1.ORDER_INVENTORY_STATUS.RETURNING)
            .map(roi => ({
            name: `RETURN-DETAIL-` + (0, uuid_1.v4)(),
            type: worksheet_base_1.WORKSHEET_TYPE.WAREHOUSE_RETURN,
            status: worksheet_base_1.WORKSHEET_STATUS.DEACTIVATED,
            createdAt: new Date(),
            domain: domain,
            bizplaceId: releaseOrder.bizplaceId,
            worksheet: returnWorksheet,
            targetInventory: roi,
            creator: user
        }));
        await tx.getRepository(worksheet_base_1.WorksheetDetail).save(returnWorksheetDetails);
    }
};
//# sourceMappingURL=warehouse-return.js.map