"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLoadingTask = 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 loading_worksheet_v2_1 = require("./loading-worksheet-v2");
exports.getLoadingTask = {
    async getLoadingTask(_, {}, context) {
        const { tx, domain, user } = context.state;
        if (process.env.NODE_ENV == 'development') {
            console.time('getLoadingTask');
        }
        try {
            // 1. Find assigned worksheet
            let worksheet = await tx
                .getRepository(worksheet_base_1.Worksheet)
                .createQueryBuilder('ws')
                .innerJoinAndSelect('ws.bizplace', 'biz')
                .innerJoinAndSelect('ws.releaseGood', 'rg')
                .innerJoin('ws.worksheetDetails', 'wsd')
                .where({
                domain,
                type: worksheet_base_1.WORKSHEET_TYPE.LOADING,
                sorter: user,
                status: (0, typeorm_1.In)([worksheet_base_1.WORKSHEET_STATUS.EXECUTING, worksheet_base_1.WORKSHEET_STATUS.DEACTIVATED])
            })
                .andWhere('rg.status IN (:...status)', {
                status: [sales_base_1.ORDER_STATUS.LOADING, sales_base_1.ORDER_STATUS.PROCESSING, sales_base_1.ORDER_STATUS.PARTIAL_PROCESSING]
            })
                .andWhere('wsd.status NOT IN (:...status)', { status: [worksheet_base_1.WORKSHEET_STATUS.DONE, worksheet_base_1.WORKSHEET_STATUS.DEACTIVATED] })
                .getOne();
            // 2. If no assigned worksheet, find and assign next available one
            if (!worksheet) {
                let updatedWorksheets = await (0, typeorm_1.getConnection)().transaction(async (tx2) => {
                    let x = await tx2.query(`
            UPDATE worksheets ws SET 
              sorter_id = $2,
              updated_at = NOW(),
              updater_id = $2
            FROM (
              SELECT ws.id 
              FROM worksheets ws
              INNER JOIN release_goods rg ON rg.id = ws.release_good_id
              INNER JOIN worksheet_details wsd ON wsd.worksheet_id = ws.id
              WHERE ws.domain_id = $1 
                AND ws.type = 'LOADING'
                AND ws.status IN ('EXECUTING', 'DEACTIVATED')
                AND ws.sorter_id IS NULL
                AND rg.status IN ('LOADING', 'PROCESSING', 'PARTIAL_PROCESSING')
                AND wsd.status NOT IN ('DONE', 'DEACTIVATED')
                AND (rg.sorted_by_id = $2 OR rg.sorted_by_id IS NULL)
              ORDER BY rg.created_at 
              LIMIT 1
            ) src 
            WHERE src.id = ws.id
            RETURNING ws.id
          `, [domain.id, user.id]);
                    return x[0];
                });
                if (updatedWorksheets.length == 0)
                    throw new Error('no suitable worksheet found');
                //fetch updated ws
                worksheet = await tx
                    .getRepository(worksheet_base_1.Worksheet)
                    .createQueryBuilder('ws')
                    .innerJoinAndSelect('ws.releaseGood', 'rg')
                    .where('ws.id = :id', { id: updatedWorksheets[0].id })
                    .andWhere('ws.sorter_id = :sorter', { sorter: user.id })
                    .getOne();
            }
            //validate worksheet is assigned to user
            if (!worksheet)
                throw new Error('Please try again by clicking the "Get Task" button');
            if (worksheet.status == worksheet_base_1.WORKSHEET_STATUS.DEACTIVATED) {
                await tx.getRepository(worksheet_base_1.Worksheet).update(worksheet.id, {
                    status: worksheet_base_1.WORKSHEET_STATUS.EXECUTING,
                    startedAt: new Date()
                });
            }
            //update ro sorter if its null
            if ((worksheet === null || worksheet === void 0 ? void 0 : worksheet.releaseGood.sortedBy) == null) {
                await tx.getRepository(sales_base_1.ReleaseGood).update(worksheet.releaseGood.id, {
                    sortedBy: user
                });
            }
            return loading_worksheet_v2_1.loadingWorksheetv2.loadingWorksheetv2(_, { orderNo: worksheet.releaseGood.name, filter: 'all' }, context);
        }
        catch (error) {
            console.error(error);
            throw error;
        }
        finally {
            if (process.env.NODE_ENV == 'development') {
                console.timeEnd('getLoadingTask');
            }
        }
    }
};
//# sourceMappingURL=get-loading-task.js.map