"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assignSorter = void 0;
const typeorm_1 = require("typeorm");
const auth_base_1 = require("@things-factory/auth-base");
const sales_base_1 = require("@things-factory/sales-base");
exports.assignSorter = {
    async assignSorter(_parentObj, { releaseGoodId, userId }, context) {
        const { tx, domain } = context.state;
        const sorter = await tx.getRepository(auth_base_1.User).findOne(userId, { relations: ['domains'] });
        if (((sorter === null || sorter === void 0 ? void 0 : sorter.domains) || []).every((userDomain) => userDomain.id !== domain.id)) {
            throw new Error('Target user does not belong to current domain');
        }
        if (!sorter)
            throw new Error('failed to find target user');
        await Promise.all(releaseGoodId.map(async (releaseGoodId) => {
            const releaseGood = await tx.getRepository(sales_base_1.ReleaseGood).findOne({
                id: releaseGoodId
            }, {
                where: [
                    {
                        status: (0, typeorm_1.Not)((0, typeorm_1.In)([sales_base_1.ORDER_STATUS.PROCESSING, sales_base_1.ORDER_STATUS.DONE]))
                    }
                ]
            });
            if (!releaseGood)
                throw new Error('failed to find target order');
            await tx.getRepository(sales_base_1.ReleaseGood).update({
                id: releaseGoodId
            }, {
                sortedBy: sorter
            });
        }));
    }
};
//# sourceMappingURL=assign-sorter.js.map