"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fixStuckPersonnelReview = void 0;
var tslib_1 = require("tslib");
var consts_1 = require("../methods/consts");
var approval_engine_1 = require("../methods/approval_engine");
exports.fixStuckPersonnelReview = {
    rest: {
        method: 'GET',
        fullPath: '/api/pepsico-content/fix-stuck-personnel-review/:approvalId'
    },
    handler: function (ctx) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var user, logger, approvalId, approval, isPositive, isPass, effectiveStatus, currentStepApprovalStatus, lastProcess, lastSubmittedDate, overrideDoc, updatedApproval, nextStep, newProcessRecords, newProcessRecords_1, newProcessRecords_1_1, proc, e_1_1;
            var e_1, _a;
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        user = ctx.meta.user;
                        if (!user || !user.is_space_admin) {
                            return [2, { status: 403, msg: "只有管理员可以执行此操作" }];
                        }
                        ctx.getObject = this.getObject;
                        return [4, this.getLogger()];
                    case 1:
                        logger = _b.sent();
                        ctx.logger = logger;
                        approvalId = ctx.params.approvalId;
                        if (!approvalId) {
                            return [2, { status: 400, msg: "请传入参数 approvalId" }];
                        }
                        return [4, ctx.getObject('pepsico_material_approval').findOne(approvalId)];
                    case 2:
                        approval = _b.sent();
                        if (!approval) {
                            return [2, { status: 404, msg: "审批单不存在" }];
                        }
                        if (approval.current_step !== consts_1.Step.personnel_review) {
                            return [2, { status: 200, msg: "\u5BA1\u6279\u5355\u5F53\u524D\u6B65\u9AA4\u4E3A ".concat(approval.current_step, "\uFF0C\u4E0D\u662F\u56FA\u5B9A\u4EBA\u5458\u5BA1\u6838\u6B65\u9AA4\uFF0C\u65E0\u9700\u4FEE\u590D") }];
                        }
                        if (!(0, approval_engine_1.isDeptReviewComplete)(approval, 'approval')) {
                            return [2, { status: 200, msg: "固定人员审核周期确实未完成，无需修复" }];
                        }
                        if (approval.child_files === 'yes' && !(0, approval_engine_1.hasReviewed)(approval.kids_approval_status)) {
                            return [2, { status: 200, msg: "kids审核人未审批，暂不能推进" }];
                        }
                        isPositive = function (status) { return status === true || status === consts_1.ApprovalStatus.approved || status === consts_1.ApprovalStatus.pass; };
                        isPass = function (status) { return status === consts_1.ApprovalStatus.pass; };
                        effectiveStatus = (0, approval_engine_1.getDeptEffectiveStatus)(approval, 'approval');
                        if (isPositive(effectiveStatus)) {
                            currentStepApprovalStatus = isPass(effectiveStatus) ? consts_1.ApprovalStatus.pass : consts_1.ApprovalStatus.approved;
                        }
                        else {
                            currentStepApprovalStatus = consts_1.ApprovalStatus.rejected;
                        }
                        if (approval.child_files === 'yes' && approval.kids_approval_status === false) {
                            currentStepApprovalStatus = consts_1.ApprovalStatus.rejected;
                        }
                        return [4, ctx.getObject('pepsico_approval_process').find({
                                filters: [
                                    ['pepsico_material_approval', '=', approvalId],
                                    ['current_step', '=', consts_1.Step.personnel_review],
                                    ['space', '=', approval.space],
                                    ['submitted', '!=', null]
                                ],
                                sort: 'submitted desc',
                                top: 1
                            })];
                    case 3:
                        lastProcess = _b.sent();
                        lastSubmittedDate = lastProcess.length > 0 && lastProcess[0].submitted
                            ? new Date(lastProcess[0].submitted)
                            : null;
                        console.log("[fixStuckPersonnelReview] \u5BA1\u6279\u5355: ".concat(approvalId, ", \u4FEE\u590D\u63A8\u8FDB, \u5BA1\u6279\u7ED3\u679C: ").concat(currentStepApprovalStatus, ", \u4F7F\u7528\u63D0\u4EA4\u65F6\u95F4: ").concat(lastSubmittedDate));
                        return [4, this.advanceApproval(ctx, approvalId, currentStepApprovalStatus)];
                    case 4:
                        _b.sent();
                        if (!lastSubmittedDate) return [3, 18];
                        overrideDoc = {
                            re_reviewed_date: lastSubmittedDate
                        };
                        return [4, ctx.getObject('pepsico_material_approval').findOne(approvalId)];
                    case 5:
                        updatedApproval = _b.sent();
                        if (!(updatedApproval.current_step === consts_1.Step.awaiting_deployment && updatedApproval.review_completed_date)) return [3, 7];
                        overrideDoc.review_completed_date = lastSubmittedDate;
                        return [4, ctx.getObject('pepsico_material').directUpdateMany(['pepsico_material_approval', '=', approvalId], { review_completed_date: lastSubmittedDate })];
                    case 6:
                        _b.sent();
                        _b.label = 7;
                    case 7: return [4, ctx.getObject('pepsico_material_approval').directUpdate(approvalId, overrideDoc)];
                    case 8:
                        _b.sent();
                        nextStep = updatedApproval.current_step;
                        return [4, ctx.getObject('pepsico_approval_process').directFind({
                                filters: [
                                    ['pepsico_material_approval', '=', approvalId],
                                    ['current_step', '=', nextStep],
                                    ['space', '=', approval.space]
                                ]
                            })];
                    case 9:
                        newProcessRecords = _b.sent();
                        _b.label = 10;
                    case 10:
                        _b.trys.push([10, 15, 16, 17]);
                        newProcessRecords_1 = tslib_1.__values(newProcessRecords), newProcessRecords_1_1 = newProcessRecords_1.next();
                        _b.label = 11;
                    case 11:
                        if (!!newProcessRecords_1_1.done) return [3, 14];
                        proc = newProcessRecords_1_1.value;
                        return [4, ctx.getObject('pepsico_approval_process').directUpdate(proc._id, {
                                created: lastSubmittedDate
                            })];
                    case 12:
                        _b.sent();
                        _b.label = 13;
                    case 13:
                        newProcessRecords_1_1 = newProcessRecords_1.next();
                        return [3, 11];
                    case 14: return [3, 17];
                    case 15:
                        e_1_1 = _b.sent();
                        e_1 = { error: e_1_1 };
                        return [3, 17];
                    case 16:
                        try {
                            if (newProcessRecords_1_1 && !newProcessRecords_1_1.done && (_a = newProcessRecords_1.return)) _a.call(newProcessRecords_1);
                        }
                        finally { if (e_1) throw e_1.error; }
                        return [7];
                    case 17:
                        console.log("[fixStuckPersonnelReview] \u5DF2\u8986\u76D6\u65F6\u95F4\u5B57\u6BB5:", JSON.stringify(overrideDoc), ", \u4FEE\u6B63\u4E86 ".concat(newProcessRecords.length, " \u6761 approval_process \u8BB0\u5F55\u7684\u63A5\u6536\u65F6\u95F4"));
                        _b.label = 18;
                    case 18: return [2, {
                            status: 200,
                            msg: "\u5BA1\u6279\u5355 ".concat(approvalId, " \u5DF2\u4FEE\u590D\u5E76\u63A8\u8FDB\u5230\u4E0B\u4E00\u6B65"),
                            data: { approvalId: approvalId, result: currentStepApprovalStatus, submittedDate: lastSubmittedDate }
                        }];
                }
            });
        });
    }
};
//# sourceMappingURL=fixStuckPersonnelReview.js.map