"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDeliveryOrders = void 0;
const typeorm_1 = require("typeorm");
const sales_base_1 = require("@things-factory/sales-base");
const setting_base_1 = require("@things-factory/setting-base");
const SETTINGS = {
    QC_SKU: 'qc-sku'
};
exports.getDeliveryOrders = {
    async getDeliveryOrders(_, { releaseGoodNo }, context) {
        var _a, _b;
        const { domain, tx } = context.state;
        const releaseGood = await (0, typeorm_1.getRepository)(sales_base_1.ReleaseGood).findOne({
            where: { domain, name: releaseGoodNo },
            relations: ['orderInventories']
        });
        if (!releaseGood) {
            throw new Error(`ReleaseGood with name ${releaseGoodNo} not found`);
        }
        const complete_status = [sales_base_1.ORDER_INVENTORY_STATUS.LOADED, sales_base_1.ORDER_INVENTORY_STATUS.TERMINATED, sales_base_1.ORDER_INVENTORY_STATUS.RETURNING, sales_base_1.ORDER_INVENTORY_STATUS.MISSING];
        const completable = (_a = releaseGood.orderInventories) === null || _a === void 0 ? void 0 : _a.every(oi => complete_status.includes(oi.status));
        const settingRepo = (tx === null || tx === void 0 ? void 0 : tx.getRepository(setting_base_1.Setting)) || (0, typeorm_1.getRepository)(setting_base_1.Setting);
        const qcSetting = await settingRepo.findOne({
            where: { domain, name: SETTINGS.QC_SKU }
        });
        const useQcSku = ((_b = qcSetting === null || qcSetting === void 0 ? void 0 : qcSetting.value) === null || _b === void 0 ? void 0 : _b.toString().toLowerCase().trim()) === 'true';
        let deliveryOrders = await (0, typeorm_1.getRepository)(sales_base_1.DeliveryOrder).find({
            where: { releaseGood },
            relations: ['orderInventories', 'orderInventories.inventory', 'orderInventories.product']
        });
        if (useQcSku) {
            deliveryOrders = deliveryOrders
                .map((do_) => {
                const liveOIs = do_.orderInventories.filter((oi) => oi.status !== sales_base_1.ORDER_INVENTORY_STATUS.TERMINATED);
                return Object.assign(Object.assign({}, do_), { orderInventories: liveOIs });
            })
                .filter((do_) => do_.orderInventories.length > 0);
        }
        return {
            completable: completable,
            deliveryOrders: deliveryOrders
        };
    }
};
//# sourceMappingURL=get-delivery-orders.js.map