"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadingWorksheetv2 = void 0;
const typeorm_1 = require("typeorm");
const sales_base_1 = require("@things-factory/sales-base");
const worksheet_base_1 = require("@things-factory/worksheet-base");
const setting_base_1 = require("@things-factory/setting-base");
const FILTER_TYPES = {
    QC: 'qc',
    LOADING: 'loading'
};
// Helper functions
function formatDate(date) {
    if (!date)
        return null;
    return new Date(date).toISOString().slice(0, 19).replace('T', ' ');
}
function shouldFilterBySortedQty(releaseGoodStatus, disableQC) {
    return releaseGoodStatus === sales_base_1.ORDER_STATUS.LOADING && !disableQC;
}
function getSortedQty(releaseGoodStatus, disableQC, pickedQty, sortedQty) {
    return releaseGoodStatus === sales_base_1.ORDER_STATUS.LOADING && disableQC ? pickedQty : sortedQty;
}
exports.loadingWorksheetv2 = {
    async loadingWorksheetv2(_, { orderNo, filter = null }, context) {
        const { domain, tx } = context.state;
        if (process.env.NODE_ENV === 'development') {
            console.time('loadingWorksheetv2');
        }
        // Find release good
        const releaseGood = await tx.getRepository(sales_base_1.ReleaseGood).findOne({
            where: { domain, name: orderNo }
        });
        if (!releaseGood)
            throw new Error('Release good not found');
        // Find worksheet
        const worksheet = await tx.getRepository(worksheet_base_1.Worksheet).findOne({
            where: {
                domain,
                releaseGood,
                type: worksheet_base_1.WORKSHEET_TYPE.LOADING,
                status: (0, typeorm_1.In)([worksheet_base_1.WORKSHEET_STATUS.EXECUTING, worksheet_base_1.WORKSHEET_STATUS.PARTIAL_EXECUTING])
            },
            relations: ['bizplace']
        });
        if (!worksheet)
            throw new Error('No loading worksheet found for order ' + orderNo);
        // Get QC setting
        const disableQcSetting = await tx.getRepository(setting_base_1.Setting).findOne({
            where: {
                domain,
                name: 'disable-QC-in-loading'
            }
        });
        const disableQc = (disableQcSetting === null || disableQcSetting === void 0 ? void 0 : disableQcSetting.value) === 'true';
        // Build worksheet details query
        const qb = tx
            .getRepository(worksheet_base_1.WorksheetDetail)
            .createQueryBuilder('worksheetDetail')
            .leftJoinAndSelect('worksheetDetail.targetInventory', 'targetInventory')
            .leftJoinAndSelect('targetInventory.binLocation', 'binLocation')
            .leftJoinAndSelect('targetInventory.product', 'product')
            .leftJoinAndSelect('targetInventory.productDetail', 'productDetail')
            .leftJoinAndSelect('productDetail.productBarcodes', 'productBarcodes')
            .leftJoinAndSelect('productDetail.childProductDetail', 'childProductDetail')
            .leftJoinAndSelect('productDetail.parentProductDetails', 'parentProductDetails')
            .leftJoin('targetInventory.inventory', 'inventory')
            .addSelect('inventory.expirationDate')
            .where('worksheetDetail.domain_id = :domainId', { domainId: domain.id })
            .andWhere('worksheetDetail.worksheet_id = :worksheetId', { worksheetId: worksheet.id });
        // Check if all items are deactivated
        const allWorksheetDetails = await qb.getMany();
        if (allWorksheetDetails.every(wsd => wsd.status === worksheet_base_1.WORKSHEET_STATUS.DEACTIVATED)) {
            throw new Error('Item in this RO is not ready to be loaded');
        }
        // Apply filters
        qb.andWhere('targetInventory.status NOT IN (:...excludeStatuses)', {
            excludeStatuses: [sales_base_1.ORDER_INVENTORY_STATUS.TERMINATED, sales_base_1.ORDER_INVENTORY_STATUS.RETURNING]
        });
        qb.andWhere('worksheetDetail.status IN (:...wsdStatus)', {
            wsdStatus: [worksheet_base_1.WORKSHEET_STATUS.EXECUTING]
        });
        if (filter === FILTER_TYPES.QC) {
            qb.andWhere('targetInventory.status IN (:...loadingStatus)', {
                loadingStatus: [sales_base_1.ORDER_INVENTORY_STATUS.SORTING, sales_base_1.ORDER_INVENTORY_STATUS.LOADING]
            });
            qb.andWhere('targetInventory.sortedQty <> targetInventory.pickedQty');
        }
        if (filter === FILTER_TYPES.LOADING) {
            if (shouldFilterBySortedQty(releaseGood.status, disableQc)) {
                qb.andWhere('targetInventory.sortedQty > 0');
                // Exclude LOADED items - they should only appear in LOADED tab
                qb.andWhere('targetInventory.status <> :loadedStatus', {
                    loadedStatus: sales_base_1.ORDER_INVENTORY_STATUS.LOADED
                });
            }
            else {
                qb.andWhere('targetInventory.status IN (:...loadingStatus)', {
                    loadingStatus: [sales_base_1.ORDER_INVENTORY_STATUS.SORTING, sales_base_1.ORDER_INVENTORY_STATUS.LOADING]
                });
            }
        }
        qb.orderBy('product.name', 'ASC');
        const worksheetDetails = await qb.getMany();
        if (process.env.NODE_ENV === 'development') {
            console.timeEnd('loadingWorksheetv2');
        }
        return await mapdata(worksheet, worksheetDetails, releaseGood, disableQc);
    }
};
async function mapdata(worksheet, worksheetDetails, releaseGood, disableQC) {
    var _a;
    const worksheetInfo = {
        worksheet: {
            id: worksheet.id,
            name: worksheet.name,
            type: worksheet.type,
            status: worksheet.status
        },
        bizplaceName: (_a = worksheet.bizplace) === null || _a === void 0 ? void 0 : _a.name,
        startedAt: formatDate(worksheet.startedAt),
        releaseGood: {
            id: releaseGood.id,
            name: releaseGood.name,
            status: releaseGood.status,
            attentionCompany: releaseGood === null || releaseGood === void 0 ? void 0 : releaseGood.attentionCompany,
            attentionTo: releaseGood === null || releaseGood === void 0 ? void 0 : releaseGood.attentionTo,
            deliveryAddress1: releaseGood === null || releaseGood === void 0 ? void 0 : releaseGood.deliveryAddress1,
            deliveryAddress2: releaseGood === null || releaseGood === void 0 ? void 0 : releaseGood.deliveryAddress2,
            refNo: releaseGood === null || releaseGood === void 0 ? void 0 : releaseGood.refNo,
            refNo2: releaseGood === null || releaseGood === void 0 ? void 0 : releaseGood.refNo2,
            refNo3: releaseGood === null || releaseGood === void 0 ? void 0 : releaseGood.refNo3,
            remark: releaseGood === null || releaseGood === void 0 ? void 0 : releaseGood.remark,
            rtm: releaseGood === null || releaseGood === void 0 ? void 0 : releaseGood.rtm
        }
    };
    const worksheetDetailInfos = worksheetDetails.map(wsd => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1;
        return ({
            id: wsd.id,
            name: wsd.name,
            batchId: wsd.targetInventory.batchId || '-',
            releaseQty: wsd.targetInventory.releaseQty,
            pickedQty: wsd.targetInventory.pickedQty,
            sortedQty: getSortedQty(releaseGood.status, disableQC, wsd.targetInventory.pickedQty, wsd.targetInventory.sortedQty),
            loadedQty: wsd.targetInventory.loadedQty,
            status: wsd.status,
            packingType: wsd.targetInventory.packingType,
            packingSize: wsd.targetInventory.packingSize,
            conversion: (0, worksheet_base_1.computeConversionString)(wsd.targetInventory.releaseQty, wsd.targetInventory.productDetail),
            expirationDate: (_b = (_a = wsd.targetInventory) === null || _a === void 0 ? void 0 : _a.inventory) === null || _b === void 0 ? void 0 : _b.expirationDate,
            binLocation: {
                name: (_c = wsd.targetInventory.binLocation) === null || _c === void 0 ? void 0 : _c.name
            },
            productName: (_e = (_d = wsd.targetInventory) === null || _d === void 0 ? void 0 : _d.product) === null || _e === void 0 ? void 0 : _e.name,
            productSku: (_g = (_f = wsd.targetInventory) === null || _f === void 0 ? void 0 : _f.product) === null || _g === void 0 ? void 0 : _g.sku,
            relatedOrderInv: {
                id: (_h = wsd.targetInventory) === null || _h === void 0 ? void 0 : _h.id,
                batchId: ((_j = wsd.targetInventory) === null || _j === void 0 ? void 0 : _j.batchId) || '-',
                packingType: (_k = wsd.targetInventory) === null || _k === void 0 ? void 0 : _k.packingType,
                refWorksheetId: (_l = wsd.targetInventory) === null || _l === void 0 ? void 0 : _l.refWorksheetId,
                packedQty: ((_m = wsd.targetInventory) === null || _m === void 0 ? void 0 : _m.packedQty) || 0,
                releaseQty: (_o = wsd.targetInventory) === null || _o === void 0 ? void 0 : _o.releaseQty,
                product: {
                    id: (_q = (_p = wsd.targetInventory) === null || _p === void 0 ? void 0 : _p.product) === null || _q === void 0 ? void 0 : _q.id,
                    sku: (_s = (_r = wsd.targetInventory) === null || _r === void 0 ? void 0 : _r.product) === null || _s === void 0 ? void 0 : _s.sku,
                    name: (_u = (_t = wsd.targetInventory) === null || _t === void 0 ? void 0 : _t.product) === null || _u === void 0 ? void 0 : _u.name,
                    isInventoryDecimal: (_w = (_v = wsd.targetInventory) === null || _v === void 0 ? void 0 : _v.product) === null || _w === void 0 ? void 0 : _w.isInventoryDecimal
                },
                productDetail: {
                    id: (_y = (_x = wsd.targetInventory) === null || _x === void 0 ? void 0 : _x.productDetail) === null || _y === void 0 ? void 0 : _y.id,
                    productBarcodes: (((_0 = (_z = wsd.targetInventory) === null || _z === void 0 ? void 0 : _z.productDetail) === null || _0 === void 0 ? void 0 : _0.productBarcodes) || []).map((pb) => ({ gtin: pb.gtin }))
                },
                orderProduct: {
                    id: (_1 = wsd.targetInventory) === null || _1 === void 0 ? void 0 : _1.orderProductId
                }
            }
        });
    });
    return {
        worksheetInfo,
        worksheetDetailInfos
    };
}
//# sourceMappingURL=loading-worksheet-v2.js.map