"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.submitContent = exports.submitKidsContent = exports.rejectContent = exports.approvalContent = exports.postponeDeployment = exports.confirmDeployment = exports.terminate = exports.getApproverStepRule = exports.getDefApproverStepRule = void 0;
var tslib_1 = require("tslib");
var consts_1 = require("./consts");
var amis_formula_1 = require("amis-formula");
var lodash_1 = require("lodash");
var material_1 = require("./material");
var content_hub_1 = require("./content_hub");
var AI_1 = require("./AI");
var notification_1 = require("./notification");
var agent_1 = require("./agent");
var const_1 = require("../const");
var _ = require("lodash");
var getDefApproverStepRule = function (ctx) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var rules, rule;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, ctx.getObject('pepsico_flow_rule').find({
                    filters: ['fu5nvp', '=', true], fields: ['_id', 'name', 'skip_approve']
                })];
            case 1:
                rules = _a.sent();
                rule = rules.length > 0 ? rules[0] : null;
                if (!rule) {
                    throw new Error('未找到审批流规则');
                }
                return [2, rule];
        }
    });
}); };
exports.getDefApproverStepRule = getDefApproverStepRule;
var getApproverStepRule = function (ctx, ruleId) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var rule_1, rules, rule;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                if (!ruleId) return [3, 2];
                return [4, ctx.getObject('pepsico_flow_rule').findOne(ruleId)];
            case 1:
                rule_1 = _a.sent();
                if (!rule_1) {
                    throw new Error('未找到审批流规则');
                }
                return [2, rule_1];
            case 2: return [4, ctx.getObject('pepsico_flow_rule').find({
                    fields: ['_id', 'name', 'skip_approve'],
                    sort: 'created asc',
                    top: 1
                })];
            case 3:
                rules = _a.sent();
                rule = rules.length > 0 ? rules[0] : null;
                if (!rule) {
                    throw new Error('未找到审批流规则');
                }
                return [2, rule];
        }
    });
}); };
exports.getApproverStepRule = getApproverStepRule;
var isSkipApprover = function (ctx, materialApproval) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var rule;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, (0, exports.getApproverStepRule)(ctx, materialApproval.pepsico_flow_rule)];
            case 1:
                rule = _a.sent();
                if (rule.skip_approve) {
                    return [2, (0, amis_formula_1.evaluate)(rule.skip_approve, materialApproval)];
                }
                return [2, false];
        }
    });
}); };
var getApproverStep = function (ctx, materialApproval) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var rule, skipApprover, reView;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, (0, exports.getApproverStepRule)(ctx, materialApproval.pepsico_flow_rule)];
            case 1:
                rule = _a.sent();
                return [4, isSkipApprover(ctx, materialApproval)];
            case 2:
                skipApprover = _a.sent();
                if (skipApprover) {
                    return [2, consts_1.Step.conclusion];
                }
                reView = (0, amis_formula_1.evaluate)(rule.name, materialApproval);
                console.log("getApproverStep-".concat(materialApproval._id), reView, typeof reView, rule.name, JSON.stringify(materialApproval));
                if (reView) {
                    return [2, consts_1.Step.personnel_review];
                }
                return [2, consts_1.Step.departmental_review];
        }
    });
}); };
var getApproveType = function (ctx, materialApproval) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var rule, reView;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, (0, exports.getApproverStepRule)(ctx, materialApproval.pepsico_flow_rule)];
            case 1:
                rule = _a.sent();
                reView = (0, amis_formula_1.evaluate)(rule.name, materialApproval);
                if (reView) {
                    return [2, consts_1.Step.personnel_review];
                }
                return [2, consts_1.Step.departmental_review];
        }
    });
}); };
var getNextStep = function (ctx, materialApproval, action) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var nextStep, _a, _b;
    return tslib_1.__generator(this, function (_c) {
        switch (_c.label) {
            case 0:
                nextStep = consts_1.Step.draft;
                _a = materialApproval.current_step;
                switch (_a) {
                    case consts_1.Step.draft: return [3, 1];
                    case consts_1.Step.ai_review: return [3, 2];
                    case consts_1.Step.departmental_review: return [3, 6];
                    case consts_1.Step.personnel_review: return [3, 6];
                    case consts_1.Step.submitter_revisions: return [3, 7];
                    case consts_1.Step.awaiting_deployment: return [3, 9];
                }
                return [3, 10];
            case 1:
                if (_.includes(const_1.DCO_TYPES, materialApproval.classification)) {
                    nextStep = consts_1.Step.conclusion;
                }
                else {
                    nextStep = consts_1.Step.ai_review;
                }
                return [3, 11];
            case 2:
                if (!(action == consts_1.ApprovalStatus.approved)) return [3, 4];
                return [4, getApproverStep(ctx, materialApproval)];
            case 3:
                _b = _c.sent();
                return [3, 5];
            case 4:
                _b = consts_1.Step.draft;
                _c.label = 5;
            case 5:
                nextStep = _b;
                return [3, 11];
            case 6:
                if (materialApproval.ch_upload === 'no') {
                    nextStep = action == consts_1.ApprovalStatus.approved ? consts_1.Step.conclusion : consts_1.Step.submitter_revisions;
                }
                else {
                    nextStep = action == consts_1.ApprovalStatus.approved ? consts_1.Step.awaiting_deployment : consts_1.Step.submitter_revisions;
                }
                return [3, 11];
            case 7: return [4, getApproverStep(ctx, materialApproval)];
            case 8:
                nextStep = _c.sent();
                return [3, 11];
            case 9:
                nextStep = consts_1.Step.conclusion;
                return [3, 11];
            case 10: return [3, 11];
            case 11:
                console.log('[getNextStep]', JSON.stringify({
                    action: action,
                    nextStep: nextStep
                }));
                return [2, nextStep];
        }
    });
}); };
var getNextApprovers = function (ctx, materialApproval, nextStep) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var approves, _a, nsAgents, legalAgents, sraAgents, caAgents, kidsAgents, perAgents, kidsAgents;
    return tslib_1.__generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                approves = [];
                _a = nextStep;
                switch (_a) {
                    case consts_1.Step.draft: return [3, 1];
                    case consts_1.Step.ai_review: return [3, 2];
                    case consts_1.Step.departmental_review: return [3, 3];
                    case consts_1.Step.personnel_review: return [3, 14];
                    case consts_1.Step.submitter_revisions: return [3, 18];
                    case consts_1.Step.awaiting_deployment: return [3, 19];
                }
                return [3, 20];
            case 1:
                approves = (0, lodash_1.concat)(approves, {
                    userIds: [materialApproval.owner],
                    type: consts_1.ProcessApprovalType.Others
                });
                return [3, 21];
            case 2:
                approves = (0, lodash_1.concat)(approves, {
                    userIds: [process.env.PEPSICO_CONTENT_APPROVAL_AI_USERID],
                    type: consts_1.ProcessApprovalType.AI
                });
                return [3, 21];
            case 3:
                if (!(materialApproval.ns_approval_status != true && materialApproval.ns_reviewer)) return [3, 5];
                return [4, (0, agent_1.getReviewerAgentsInfo)(ctx, materialApproval.space, materialApproval.ns_reviewer)];
            case 4:
                nsAgents = _b.sent();
                approves = (0, lodash_1.concat)(approves, tslib_1.__assign(tslib_1.__assign({}, nsAgents), { type: consts_1.ProcessApprovalType.NS }));
                _b.label = 5;
            case 5:
                if (!(materialApproval.legal_approval_status != true && materialApproval.legal_reviewer)) return [3, 7];
                return [4, (0, agent_1.getReviewerAgentsInfo)(ctx, materialApproval.space, materialApproval.legal_reviewer)];
            case 6:
                legalAgents = _b.sent();
                approves = (0, lodash_1.concat)(approves, tslib_1.__assign(tslib_1.__assign({}, legalAgents), { type: consts_1.ProcessApprovalType.Legal }));
                _b.label = 7;
            case 7:
                if (!(materialApproval.sra_approval_status != true && materialApproval.sra_reviewer)) return [3, 9];
                return [4, (0, agent_1.getReviewerAgentsInfo)(ctx, materialApproval.space, materialApproval.sra_reviewer)];
            case 8:
                sraAgents = _b.sent();
                approves = (0, lodash_1.concat)(approves, tslib_1.__assign(tslib_1.__assign({}, sraAgents), { type: consts_1.ProcessApprovalType.SRA }));
                _b.label = 9;
            case 9:
                if (!(materialApproval.ca_approval_status != true && materialApproval.ca_reviewer)) return [3, 11];
                return [4, (0, agent_1.getReviewerAgentsInfo)(ctx, materialApproval.space, materialApproval.ca_reviewer)];
            case 10:
                caAgents = _b.sent();
                approves = (0, lodash_1.concat)(approves, tslib_1.__assign(tslib_1.__assign({}, caAgents), { type: consts_1.ProcessApprovalType.CA }));
                _b.label = 11;
            case 11:
                if (!(materialApproval.child_files == 'yes' && materialApproval.kids_approval_status != true && materialApproval.kids_reviewer)) return [3, 13];
                return [4, (0, agent_1.getReviewerAgentsInfo)(ctx, materialApproval.space, materialApproval.kids_reviewer)];
            case 12:
                kidsAgents = _b.sent();
                approves = (0, lodash_1.concat)(approves, tslib_1.__assign(tslib_1.__assign({}, kidsAgents), { type: consts_1.ProcessApprovalType.Kids }));
                _b.label = 13;
            case 13: return [3, 21];
            case 14: return [4, (0, agent_1.getReviewerAgentsInfo)(ctx, materialApproval.space, materialApproval.reviewer)];
            case 15:
                perAgents = _b.sent();
                approves = (0, lodash_1.concat)(approves, tslib_1.__assign(tslib_1.__assign({}, perAgents), { type: consts_1.ProcessApprovalType.guding }));
                if (!(materialApproval.child_files == 'yes' && materialApproval.kids_approval_status != true)) return [3, 17];
                return [4, (0, agent_1.getReviewerAgentsInfo)(ctx, materialApproval.space, materialApproval.kids_reviewer)];
            case 16:
                kidsAgents = _b.sent();
                approves = (0, lodash_1.concat)(approves, tslib_1.__assign(tslib_1.__assign({}, kidsAgents), { type: consts_1.ProcessApprovalType.Kids }));
                _b.label = 17;
            case 17: return [3, 21];
            case 18:
                approves = (0, lodash_1.concat)(approves, {
                    userIds: [materialApproval.owner],
                    type: consts_1.ProcessApprovalType.Others
                });
                return [3, 21];
            case 19:
                approves = (0, lodash_1.concat)(approves, {
                    userIds: [materialApproval.material_owner_id],
                    type: consts_1.ProcessApprovalType.Others
                });
                return [3, 21];
            case 20: return [3, 21];
            case 21: return [2, (0, lodash_1.uniq)(approves)];
        }
    });
}); };
var canSubmit = function (materialApproval) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    return tslib_1.__generator(this, function (_a) {
        if (materialApproval.review_status === consts_1.ReviewStatus.terminated) {
            throw new Error("已中止审核.");
        }
        if (materialApproval.current_step === consts_1.Step.conclusion) {
            throw new Error("已审核完成.");
        }
        return [2, true];
    });
}); };
var getReviewStatus = function (nextStep) {
    if (nextStep === consts_1.Step.draft) {
        return consts_1.ReviewStatus.draft;
    }
    else if (nextStep === consts_1.Step.conclusion) {
        return true ? consts_1.ReviewStatus.approved : consts_1.ReviewStatus.rejected;
    }
    else {
        return consts_1.ReviewStatus.under_review;
    }
};
var updateUserStepStatus = function (ctx, materialApproval, _a) {
    var approvalStatus = _a.approvalStatus, approveField = _a.approveField;
    return tslib_1.__awaiter(void 0, void 0, void 0, function () {
        var user, filters, process, process_1, process_1_1, item, processOthers, processOthers_1, processOthers_1_1, item_1, e_1_1, e_2_1;
        var e_2, _b, e_1, _c;
        return tslib_1.__generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    user = ctx.meta.user;
                    filters = [
                        ["owner", "=", user.userId],
                        ["pepsico_material_approval", "=", materialApproval._id],
                        ["current_step", "=", materialApproval.current_step],
                        ["space", "=", materialApproval.space],
                        ["approved", "=", 'progess']
                    ];
                    if (approveField && approveField === 'kids_approval_status') {
                        filters.push(["type", "=", 'Kids']);
                    }
                    return [4, ctx.getObject("pepsico_approval_process").find({
                            filters: filters,
                            top: 1,
                            sort: "modified asc"
                        })];
                case 1:
                    process = _d.sent();
                    _d.label = 2;
                case 2:
                    _d.trys.push([2, 15, 16, 17]);
                    process_1 = tslib_1.__values(process), process_1_1 = process_1.next();
                    _d.label = 3;
                case 3:
                    if (!!process_1_1.done) return [3, 14];
                    item = process_1_1.value;
                    return [4, ctx.getObject("pepsico_approval_process").update(item._id, {
                            submitted: new Date(),
                            modified: new Date(),
                            modified_by: user.userId,
                            approved: approvalStatus || 'submit',
                            name: ctx.params.comment
                        })];
                case 4:
                    _d.sent();
                    return [4, ctx.getObject("pepsico_approval_process").find({
                            filters: [
                                ["owner", "!=", user.userId],
                                ["pepsico_material_approval", "=", materialApproval._id],
                                ["current_step", "=", materialApproval.current_step],
                                ["space", "=", materialApproval.space],
                                ["approved", "=", 'progess'],
                                ["type", "=", item.type]
                            ],
                            sort: "modified desc"
                        })];
                case 5:
                    processOthers = _d.sent();
                    _d.label = 6;
                case 6:
                    _d.trys.push([6, 11, 12, 13]);
                    processOthers_1 = (e_1 = void 0, tslib_1.__values(processOthers)), processOthers_1_1 = processOthers_1.next();
                    _d.label = 7;
                case 7:
                    if (!!processOthers_1_1.done) return [3, 10];
                    item_1 = processOthers_1_1.value;
                    return [4, ctx.getObject("pepsico_approval_process").update(item_1._id, {
                            modified: new Date(),
                            modified_by: user.userId,
                            approved: ''
                        })];
                case 8:
                    _d.sent();
                    _d.label = 9;
                case 9:
                    processOthers_1_1 = processOthers_1.next();
                    return [3, 7];
                case 10: return [3, 13];
                case 11:
                    e_1_1 = _d.sent();
                    e_1 = { error: e_1_1 };
                    return [3, 13];
                case 12:
                    try {
                        if (processOthers_1_1 && !processOthers_1_1.done && (_c = processOthers_1.return)) _c.call(processOthers_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                    return [7];
                case 13:
                    process_1_1 = process_1.next();
                    return [3, 3];
                case 14: return [3, 17];
                case 15:
                    e_2_1 = _d.sent();
                    e_2 = { error: e_2_1 };
                    return [3, 17];
                case 16:
                    try {
                        if (process_1_1 && !process_1_1.done && (_b = process_1.return)) _b.call(process_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                    return [7];
                case 17: return [2];
            }
        });
    });
};
var updateApproveFieldStatus = function (ctx, recordId, approveField, approveFieldValue) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var userId, set, approvalNew, approvals, index;
    var _a;
    return tslib_1.__generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                userId = ctx.meta.user.userId;
                if (!approveField) return [3, 4];
                set = (_a = {},
                    _a[approveField] = approveFieldValue,
                    _a);
                if (!userId) return [3, 2];
                return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
            case 1:
                approvalNew = _b.sent();
                approvals = approvalNew.person_pending_approve || [];
                index = (0, lodash_1.findIndex)(approvals, function (item) { return item === userId; });
                if (index !== -1) {
                    (0, lodash_1.pullAt)(approvals, index);
                }
                set.person_pending_approve = approvals;
                set.$push = {
                    person_approved: userId,
                    person_done: userId
                };
                _b.label = 2;
            case 2:
                console.log('[updateApproveFieldStatus]', JSON.stringify({ recordId: recordId, set: set }));
                return [4, ctx.getObject('pepsico_material_approval').update(recordId, set)];
            case 3:
                _b.sent();
                _b.label = 4;
            case 4: return [2];
        }
    });
}); };
var changeApprovalProcess = function (ctx, materialApproval, _a) {
    var nextStep = _a.nextStep, nextApprovers = _a.nextApprovers, description = _a.description;
    return tslib_1.__awaiter(void 0, void 0, void 0, function () {
        var user, count, now, sUsers, _b, nextApprovers_1, nextApprovers_1_1, nextApprover, _c, _d, userId, spaceUsers, e_3_1, e_4_1;
        var e_4, _e, e_3, _f, _g;
        return tslib_1.__generator(this, function (_h) {
            switch (_h.label) {
                case 0:
                    console.log("[changeApprovalProcess]", nextStep, nextApprovers, description);
                    user = ctx.meta.user;
                    if (!(!materialApproval.current_step || materialApproval.current_step == consts_1.Step.draft)) return [3, 3];
                    return [4, ctx.getObject("pepsico_approval_process").count({
                            filters: [
                                ["pepsico_material_approval", "=", materialApproval._id],
                                ["space", "=", materialApproval.space]
                            ]
                        })];
                case 1:
                    count = _h.sent();
                    if (!(count == 0)) return [3, 3];
                    now = new Date();
                    return [4, ctx.getObject('pepsico_approval_process').insert({
                            pepsico_material_approval: materialApproval._id,
                            owner: user.userId,
                            review_department: user.organization._id,
                            current_step: consts_1.Step.draft,
                            space: materialApproval.space,
                            created: now,
                            created_by: user.userId,
                            modified: now,
                            modified_by: user.userId,
                            name: description,
                            submitted: now,
                            approved: 'submit'
                        })];
                case 2:
                    _h.sent();
                    _h.label = 3;
                case 3:
                    sUsers = null;
                    _b = nextStep;
                    switch (_b) {
                        case consts_1.Step.draft: return [3, 4];
                        case consts_1.Step.ai_review: return [3, 4];
                        case consts_1.Step.departmental_review: return [3, 4];
                        case consts_1.Step.personnel_review: return [3, 4];
                        case consts_1.Step.submitter_revisions: return [3, 4];
                        case consts_1.Step.awaiting_deployment: return [3, 4];
                        case consts_1.Step.conclusion: return [3, 21];
                    }
                    return [3, 23];
                case 4:
                    _h.trys.push([4, 18, 19, 20]);
                    nextApprovers_1 = tslib_1.__values(nextApprovers), nextApprovers_1_1 = nextApprovers_1.next();
                    _h.label = 5;
                case 5:
                    if (!!nextApprovers_1_1.done) return [3, 17];
                    nextApprover = nextApprovers_1_1.value;
                    _h.label = 6;
                case 6:
                    _h.trys.push([6, 12, 13, 14]);
                    _c = (e_3 = void 0, tslib_1.__values(nextApprover.userIds)), _d = _c.next();
                    _h.label = 7;
                case 7:
                    if (!!_d.done) return [3, 11];
                    userId = _d.value;
                    return [4, ctx.getObject('space_users').directFind({ filters: [['user', '=', userId], ['space', '=', materialApproval.space]] })];
                case 8:
                    spaceUsers = _h.sent();
                    return [4, ctx.getObject('pepsico_approval_process').insert({
                            pepsico_material_approval: materialApproval._id,
                            owner: userId,
                            type: nextApprover.type,
                            review_department: spaceUsers.length > 0 ? spaceUsers[0].organization : null,
                            current_step: nextStep,
                            approved: "progess",
                            space: materialApproval.space,
                            created: new Date(),
                            created_by: user.userId,
                            modified: new Date(),
                            modified_by: user.userId,
                            name: description
                        })];
                case 9:
                    _h.sent();
                    _h.label = 10;
                case 10:
                    _d = _c.next();
                    return [3, 7];
                case 11: return [3, 14];
                case 12:
                    e_3_1 = _h.sent();
                    e_3 = { error: e_3_1 };
                    return [3, 14];
                case 13:
                    try {
                        if (_d && !_d.done && (_f = _c.return)) _f.call(_c);
                    }
                    finally { if (e_3) throw e_3.error; }
                    return [7];
                case 14:
                    if (!nextApprover.type) return [3, 16];
                    return [4, ctx.getObject('pepsico_material_approval').directUpdate(materialApproval._id, (_g = {},
                            _g["handler_".concat((0, lodash_1.toLower)(nextApprover.type))] = nextApprover.userIds,
                            _g))];
                case 15:
                    _h.sent();
                    _h.label = 16;
                case 16:
                    nextApprovers_1_1 = nextApprovers_1.next();
                    return [3, 5];
                case 17: return [3, 20];
                case 18:
                    e_4_1 = _h.sent();
                    e_4 = { error: e_4_1 };
                    return [3, 20];
                case 19:
                    try {
                        if (nextApprovers_1_1 && !nextApprovers_1_1.done && (_e = nextApprovers_1.return)) _e.call(nextApprovers_1);
                    }
                    finally { if (e_4) throw e_4.error; }
                    return [7];
                case 20: return [3, 24];
                case 21: return [4, ctx.getObject('pepsico_approval_process').insert({
                        pepsico_material_approval: materialApproval._id,
                        current_step: consts_1.Step.conclusion,
                        space: materialApproval.space,
                        created: new Date(),
                        created_by: user.userId,
                        modified: new Date(),
                        modified_by: user.userId,
                        name: description
                    })];
                case 22:
                    _h.sent();
                    return [3, 24];
                case 23: return [3, 24];
                case 24: return [2];
            }
        });
    });
};
var setPersonView = function (ctx, materialApproval) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var approvalType, personView;
    return tslib_1.__generator(this, function (_a) {
        switch (_a.label) {
            case 0: return [4, getApproveType(ctx, materialApproval)];
            case 1:
                approvalType = _a.sent();
                personView = [];
                if (approvalType === consts_1.Step.personnel_review) {
                    personView = (0, lodash_1.concat)(materialApproval.reviewer, materialApproval.assistance);
                }
                else {
                    personView = (0, lodash_1.concat)(materialApproval.sra_reviewer, materialApproval.ns_reviewer, materialApproval.ca_reviewer, materialApproval.legal_reviewer, materialApproval.sra_assistance, materialApproval.ns_assistance, materialApproval.ca_assistance, materialApproval.legal_assistance);
                }
                if (materialApproval.child_files == 'yes') {
                    personView = (0, lodash_1.concat)(personView, materialApproval.kids_reviewer, materialApproval.kids_assistance);
                }
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(materialApproval._id, {
                        $push: {
                            person_view: {
                                $each: (0, lodash_1.compact)((0, lodash_1.uniq)(personView))
                            }
                        },
                        approval_type: approvalType
                    })];
            case 2:
                _a.sent();
                return [2];
        }
    });
}); };
var advanceApproval = function (ctx, recordId, currentStepApprovalStatus) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var actionLabel, user, record, nextStep, skipApprover, nextApprovers, _nextApprovers, nextApprovers_2, nextApprovers_2_1, reviewer, fieldName, status, e_5_1, nextApproversUserIds_1, nextApproversClientUserIds_1, setDoc, nextApprovers_3, nextApprovers_3_1, nextApprover, e_6_1, setDoc_1, isConclusionApproved, error_1;
    var e_5, _a, _b, _c, e_6, _d;
    return tslib_1.__generator(this, function (_e) {
        switch (_e.label) {
            case 0:
                _e.trys.push([0, 69, , 70]);
                actionLabel = '请查看';
                user = ctx.meta.user;
                return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
            case 1:
                record = _e.sent();
                console.log('[advanceApproval]', record.current_step, record.person_pending_approve, user.userId);
                if (record.current_step === consts_1.Step.personnel_review && record.child_files === 'yes' && !_.isEmpty(record.kids_reviewer)) {
                    if (!hasReviewed(record.approval_status) || !hasReviewed(record.kids_approval_status)) {
                        console.log('[advanceApproval]: 专员或kids未完成审批, 跳过步骤推进.');
                        return [2, {}];
                    }
                }
                return [4, canSubmit(record)];
            case 2:
                _e.sent();
                return [4, getNextStep(ctx, record, currentStepApprovalStatus)];
            case 3:
                nextStep = _e.sent();
                return [4, isSkipApprover(ctx, record)];
            case 4:
                skipApprover = _e.sent();
                if (!(nextStep === consts_1.Step.conclusion && skipApprover)) return [3, 8];
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(record._id, {
                        is_skip_approver: true,
                        approved_time: new Date()
                    })];
            case 5:
                _e.sent();
                return [4, ctx.getObject('pepsico_material').directUpdateMany(['pepsico_material_approval', '=', record._id], {
                        is_skip_approver: true,
                        approved_time: new Date()
                    })];
            case 6:
                _e.sent();
                return [4, setPersonView(ctx, record)];
            case 7:
                _e.sent();
                _e.label = 8;
            case 8:
                if (!(nextStep === consts_1.Step.conclusion && record.current_step === consts_1.Step.draft)) return [3, 11];
                if (!_.includes(const_1.DCO_TYPES, record.classification)) return [3, 11];
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(record._id, {
                        approved_time: new Date()
                    })];
            case 9:
                _e.sent();
                return [4, ctx.getObject('pepsico_material').directUpdateMany(['pepsico_material_approval', '=', record._id], {
                        approved_time: new Date()
                    })];
            case 10:
                _e.sent();
                _e.label = 11;
            case 11: return [4, getNextApprovers(ctx, record, nextStep)];
            case 12:
                nextApprovers = _e.sent();
                if (!(record.current_step === consts_1.Step.submitter_revisions && (nextStep === consts_1.Step.departmental_review || nextStep === consts_1.Step.personnel_review))) return [3, 26];
                _nextApprovers = [];
                _e.label = 13;
            case 13:
                _e.trys.push([13, 21, 22, 23]);
                nextApprovers_2 = tslib_1.__values(nextApprovers), nextApprovers_2_1 = nextApprovers_2.next();
                _e.label = 14;
            case 14:
                if (!!nextApprovers_2_1.done) return [3, 20];
                reviewer = nextApprovers_2_1.value;
                fieldName = (0, material_1.getApproverFieldByType)(reviewer.type);
                console.log("getApproverFieldByType", reviewer.type, fieldName);
                if (!fieldName) {
                    return [3, 19];
                }
                return [4, (0, material_1.getUserReviewedAllMaterialsStatus)(ctx, record._id, fieldName)];
            case 15:
                status = _e.sent();
                console.log("getUserReviewedAllMaterialsStatus", record._id, fieldName, status);
                if (!(status === consts_1.ApprovalStatus.approved)) return [3, 17];
                console.log("[advanceApproval] \u81EA\u52A8\u66F4\u65B0\u5BA1\u6279\u5355\u4E0A\u7684\u72B6\u6001\u5B57\u6BB5", recordId, (_b = {},
                    _b[fieldName] = consts_1.ApprovalStatus.approved,
                    _b));
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, (_c = {},
                        _c[fieldName] = true,
                        _c))];
            case 16:
                _e.sent();
                return [3, 18];
            case 17:
                _nextApprovers.push(reviewer);
                _e.label = 18;
            case 18:
                ;
                _e.label = 19;
            case 19:
                nextApprovers_2_1 = nextApprovers_2.next();
                return [3, 14];
            case 20: return [3, 23];
            case 21:
                e_5_1 = _e.sent();
                e_5 = { error: e_5_1 };
                return [3, 23];
            case 22:
                try {
                    if (nextApprovers_2_1 && !nextApprovers_2_1.done && (_a = nextApprovers_2.return)) _a.call(nextApprovers_2);
                }
                finally { if (e_5) throw e_5.error; }
                return [7];
            case 23:
                if (!(_nextApprovers.length > 0)) return [3, 24];
                nextApprovers = _nextApprovers;
                return [3, 26];
            case 24:
                nextStep = consts_1.Step.conclusion;
                return [4, getNextApprovers(ctx, record, nextStep)];
            case 25:
                nextApprovers = _e.sent();
                _e.label = 26;
            case 26:
                console.log("[advanceApproval] currentStepApprovalStatus:", currentStepApprovalStatus, " nextStep:", nextStep, " nextApprovers:", nextApprovers);
                nextApproversUserIds_1 = [];
                nextApproversClientUserIds_1 = [];
                (0, lodash_1.map)(nextApprovers, function (item) {
                    nextApproversUserIds_1 = (0, lodash_1.concat)(nextApproversUserIds_1, item.userIds);
                    nextApproversClientUserIds_1 = (0, lodash_1.concat)(nextApproversClientUserIds_1, item.clientUserIds);
                });
                setDoc = {
                    current_step: nextStep,
                    review_status: getReviewStatus(nextStep),
                    person_pending_approve: nextApproversUserIds_1,
                    $push: {
                        person_view: {
                            $each: (0, lodash_1.compact)((0, lodash_1.uniq)((0, lodash_1.difference)(nextApproversClientUserIds_1, nextApproversUserIds_1)))
                        },
                        person_approved: {
                            $each: record.person_pending_approve
                        }
                    }
                };
                if (record.current_step === consts_1.Step.submitter_revisions) {
                    setDoc.person_done = [];
                }
                if (!(record.current_step === consts_1.Step.draft)) return [3, 28];
                setDoc.draft_submitted = new Date();
                return [4, ctx.getObject('pepsico_material').directUpdateMany(['pepsico_material_approval', '=', record._id], {
                        draft_submitted: setDoc.draft_submitted
                    })];
            case 27:
                _e.sent();
                _e.label = 28;
            case 28:
                if (record.current_step === consts_1.Step.ai_review) {
                    setDoc.ai_reviewed_date = new Date();
                }
                if (record.current_step === consts_1.Step.departmental_review || record.current_step === consts_1.Step.personnel_review) {
                    setDoc.re_reviewed_date = new Date();
                }
                if (record.current_step === consts_1.Step.awaiting_deployment) {
                    setDoc.awaiting_deployment_date = new Date();
                }
                if (record.current_step === consts_1.Step.conclusion) {
                    setDoc.conclusion_date = new Date();
                }
                if (record.current_step === consts_1.Step.submitter_revisions) {
                    setDoc.submitter_revision_date = new Date();
                }
                return [4, ctx.getObject('pepsico_material_approval').update(recordId, setDoc)];
            case 29:
                _e.sent();
                return [4, changeApprovalProcess(ctx, record, {
                        nextStep: nextStep,
                        nextApprovers: nextApprovers,
                        description: ""
                    })];
            case 30:
                _e.sent();
                if (!(false && nextStep === consts_1.Step.ai_review)) return [3, 32];
                console.time('callAIReview: ' + recordId);
                return [4, (0, AI_1.callAIReview)(ctx, recordId)];
            case 31:
                _e.sent();
                console.timeEnd('callAIReview: ' + recordId);
                _e.label = 32;
            case 32:
                _e.trys.push([32, 53, 54, 55]);
                nextApprovers_3 = tslib_1.__values(nextApprovers), nextApprovers_3_1 = nextApprovers_3.next();
                _e.label = 33;
            case 33:
                if (!!nextApprovers_3_1.done) return [3, 52];
                nextApprover = nextApprovers_3_1.value;
                if (!(nextApprover.type === consts_1.ProcessApprovalType.CA)) return [3, 36];
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, {
                        ca_approval_status: ''
                    })];
            case 34:
                _e.sent();
                return [4, ctx.getObject('pepsico_material').directUpdateMany([['pepsico_material_approval', '=', recordId], ['ca_approval_status', '=', false]], {
                        ca_approval_status: ''
                    })];
            case 35:
                _e.sent();
                _e.label = 36;
            case 36:
                if (!(nextApprover.type === consts_1.ProcessApprovalType.Legal)) return [3, 39];
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, {
                        legal_approval_status: ''
                    })];
            case 37:
                _e.sent();
                return [4, ctx.getObject('pepsico_material').directUpdateMany([['pepsico_material_approval', '=', recordId], ['legal_approval_status', '=', false]], {
                        legal_approval_status: ''
                    })];
            case 38:
                _e.sent();
                _e.label = 39;
            case 39:
                if (!(nextApprover.type === consts_1.ProcessApprovalType.NS)) return [3, 42];
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, {
                        ns_approval_status: ''
                    })];
            case 40:
                _e.sent();
                return [4, ctx.getObject('pepsico_material').directUpdateMany([['pepsico_material_approval', '=', recordId], ['ns_approval_status', '=', false]], {
                        ns_approval_status: ''
                    })];
            case 41:
                _e.sent();
                _e.label = 42;
            case 42:
                if (!(nextApprover.type === consts_1.ProcessApprovalType.SRA)) return [3, 45];
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, {
                        sra_approval_status: ''
                    })];
            case 43:
                _e.sent();
                return [4, ctx.getObject('pepsico_material').directUpdateMany([['pepsico_material_approval', '=', recordId], ['sra_approval_status', '=', false]], {
                        sra_approval_status: ''
                    })];
            case 44:
                _e.sent();
                _e.label = 45;
            case 45:
                if (!(nextApprover.type === consts_1.ProcessApprovalType.guding)) return [3, 48];
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, {
                        approval_status: ''
                    })];
            case 46:
                _e.sent();
                return [4, ctx.getObject('pepsico_material').directUpdateMany([['pepsico_material_approval', '=', recordId], ['approval_status', '=', false]], {
                        approval_status: ''
                    })];
            case 47:
                _e.sent();
                _e.label = 48;
            case 48:
                if (!(nextApprover.type === consts_1.ProcessApprovalType.Kids)) return [3, 51];
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, {
                        kids_approval_status: ''
                    })];
            case 49:
                _e.sent();
                return [4, ctx.getObject('pepsico_material').directUpdateMany([['pepsico_material_approval', '=', recordId], ['kids_approval_status', '=', false]], {
                        kids_approval_status: ''
                    })];
            case 50:
                _e.sent();
                _e.label = 51;
            case 51:
                nextApprovers_3_1 = nextApprovers_3.next();
                return [3, 33];
            case 52: return [3, 55];
            case 53:
                e_6_1 = _e.sent();
                e_6 = { error: e_6_1 };
                return [3, 55];
            case 54:
                try {
                    if (nextApprovers_3_1 && !nextApprovers_3_1.done && (_d = nextApprovers_3.return)) _d.call(nextApprovers_3);
                }
                finally { if (e_6) throw e_6.error; }
                return [7];
            case 55:
                if (!(nextStep === consts_1.Step.departmental_review || nextStep === consts_1.Step.personnel_review)) return [3, 57];
                return [4, setPersonView(ctx, record)];
            case 56:
                _e.sent();
                _e.label = 57;
            case 57:
                if (!(record.current_step === consts_1.Step.departmental_review || record.current_step === consts_1.Step.personnel_review)) return [3, 61];
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, {
                        materials_remove_share_link_from_onedrive_status: 'pending'
                    })];
            case 58:
                _e.sent();
                if (!(nextStep != consts_1.Step.submitter_revisions)) return [3, 61];
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(record._id, {
                        approved_time: new Date()
                    })];
            case 59:
                _e.sent();
                return [4, ctx.getObject('pepsico_material').directUpdateMany(['pepsico_material_approval', '=', record._id], {
                        approved_time: new Date()
                    })];
            case 60:
                _e.sent();
                _e.label = 61;
            case 61:
                if (!(nextStep === consts_1.Step.awaiting_deployment || nextStep === consts_1.Step.conclusion)) return [3, 63];
                return [4, pendingDeployment(ctx, recordId)];
            case 62:
                _e.sent();
                _e.label = 63;
            case 63:
                if (!(nextStep === consts_1.Step.awaiting_deployment || (nextStep === consts_1.Step.conclusion && record.materials_download_from_onedrive_status === 'not_started'))) return [3, 65];
                setDoc_1 = {
                    materials_download_from_onedrive_status: 'pending'
                };
                return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, setDoc_1)];
            case 64:
                _e.sent();
                _e.label = 65;
            case 65:
                if (currentStepApprovalStatus === consts_1.ApprovalStatus.rejected) {
                    actionLabel = '内容审批被驳回';
                }
                if (currentStepApprovalStatus === consts_1.ApprovalStatus.approved
                    && (nextStep === consts_1.Step.departmental_review || nextStep === consts_1.Step.personnel_review)) {
                    actionLabel = '请审批';
                }
                if (nextStep === consts_1.Step.awaiting_deployment) {
                    actionLabel = "\u5185\u5BB9\u5BA1\u6279\u5DF2\u901A\u8FC7\u5F85\u4F20\u8F93";
                }
                isConclusionApproved = nextStep === consts_1.Step.conclusion && currentStepApprovalStatus === consts_1.ApprovalStatus.approved;
                if (isConclusionApproved) {
                    actionLabel = '内容审批已通过';
                }
                return [4, (0, notification_1.sendNotifications)(ctx, record, nextApproversUserIds_1, actionLabel)];
            case 66:
                _e.sent();
                if (!isConclusionApproved) return [3, 68];
                return [4, (0, notification_1.sendNotifications)(ctx, record, [record.owner], actionLabel)];
            case 67:
                _e.sent();
                _e.label = 68;
            case 68: return [2, {}];
            case 69:
                error_1 = _e.sent();
                console.log("advanceApproval:", recordId, error_1);
                return [2, {
                        msg: error_1.message,
                        status: 500
                    }];
            case 70: return [2];
        }
    });
}); };
var terminate = function (ctx, recordId, description) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var user, record, records, records_1, records_1_1, process_2, e_7_1;
    var e_7, _a;
    return tslib_1.__generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                user = ctx.meta.user;
                return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
            case 1:
                record = _b.sent();
                if (!(record.owner === user.userId || user.is_space_admin || (0, lodash_1.includes)(record.person_pending_approve, user.userId))) return [3, 13];
                return [4, ctx.getObject('pepsico_approval_process').insert({
                        pepsico_material_approval: record._id,
                        current_step: consts_1.Step.conclusion,
                        owner: user.userId,
                        space: record.space,
                        created: new Date(),
                        created_by: user.userId,
                        modified: new Date(),
                        modified_by: user.userId,
                        approvalStatus: 'terminate',
                        name: description
                    })];
            case 2:
                _b.sent();
                return [4, ctx.getObject('pepsico_approval_process').directFind({
                        filters: [['pepsico_material_approval', '=', record._id], ['approved', '=', 'progess']]
                    })];
            case 3:
                records = _b.sent();
                _b.label = 4;
            case 4:
                _b.trys.push([4, 9, 10, 11]);
                records_1 = tslib_1.__values(records), records_1_1 = records_1.next();
                _b.label = 5;
            case 5:
                if (!!records_1_1.done) return [3, 8];
                process_2 = records_1_1.value;
                return [4, ctx.getObject('pepsico_approval_process').directUpdate(process_2._id, {
                        approved: '',
                        modified: new Date(),
                        modified_by: user.userId,
                    })];
            case 6:
                _b.sent();
                _b.label = 7;
            case 7:
                records_1_1 = records_1.next();
                return [3, 5];
            case 8: return [3, 11];
            case 9:
                e_7_1 = _b.sent();
                e_7 = { error: e_7_1 };
                return [3, 11];
            case 10:
                try {
                    if (records_1_1 && !records_1_1.done && (_a = records_1.return)) _a.call(records_1);
                }
                finally { if (e_7) throw e_7.error; }
                return [7];
            case 11: return [4, ctx.getObject('pepsico_material_approval').update(recordId, {
                    current_step: consts_1.Step.conclusion,
                    review_status: consts_1.ReviewStatus.terminated,
                    termination_date: new Date(),
                    person_pending_approve: [],
                    termination_type: record.owner === user.userId ? '发起人中止' : '审批人中止'
                })];
            case 12:
                _b.sent();
                return [2, {}];
            case 13: throw new Error('Sorry, you don’t have permission to terminate the review.');
        }
    });
}); };
exports.terminate = terminate;
var pendingDeployment = function (ctx, recordId) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4, ctx.getObject('pepsico_material_approval').update(recordId, {
                        launch: 'pending'
                    })];
                case 1:
                    _a.sent();
                    return [2];
            }
        });
    });
};
var confirmDeployment = function (ctx, recordId, data) {
    if (data === void 0) { data = {
        content_rule: null
    }; }
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var user, record;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = ctx.meta.user;
                    return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
                case 1:
                    record = _a.sent();
                    if (user.userId !== record.material_owner_id) {
                        throw new Error('只有材料拥有者才能执行此操作.');
                    }
                    if (record.current_step != consts_1.Step.draft && !(0, lodash_1.includes)(record.person_pending_approve, user.userId)) {
                        return [2, {}];
                    }
                    return [4, updateUserStepStatus(ctx, record, { approvalStatus: consts_1.ApprovalStatus.submit, approveField: '' })];
                case 2:
                    _a.sent();
                    if (!(record.current_step === consts_1.Step.awaiting_deployment && (0, lodash_1.includes)(record.person_pending_approve, user.userId))) return [3, 6];
                    return [4, ctx.getObject('pepsico_material_approval').update(recordId, {
                            launch: 'launched',
                            content_rule: data.content_rule,
                            aunch_time: new Date()
                        })];
                case 3:
                    _a.sent();
                    return [4, advanceApproval(ctx, recordId, consts_1.ApprovalStatus.submit)];
                case 4:
                    _a.sent();
                    return [4, (0, content_hub_1.inventoryApprovalMaterial)(ctx, recordId)];
                case 5:
                    _a.sent();
                    _a.label = 6;
                case 6: return [2, {}];
            }
        });
    });
};
exports.confirmDeployment = confirmDeployment;
var postponeDeployment = function (ctx, recordId, data) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var user, record;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    user = ctx.meta.user;
                    return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
                case 1:
                    record = _a.sent();
                    if (user.userId !== record.material_owner_id) {
                        throw new Error('只有材料拥有者才能执行此操作.');
                    }
                    if (!(record.current_step === consts_1.Step.awaiting_deployment && (0, lodash_1.includes)(record.person_pending_approve, user.userId))) return [3, 3];
                    return [4, ctx.getObject('pepsico_material_approval').update(recordId, {
                            launch: 'postpone',
                            postpone_launch_date: data.postpone_launch_date
                        })];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3: return [2, {}];
            }
        });
    });
};
exports.postponeDeployment = postponeDeployment;
function checkAllDepartmentsApproved(approvalNew) {
    var allApproved = true;
    if (!_.isEmpty(approvalNew.handler_ca)) {
        allApproved = allApproved && approvalNew.ca_approval_status;
        console.log("checkAllDepartmentsApproved approvalNew.handler_ca", allApproved, approvalNew.handler_ca, approvalNew.ca_approval_status);
    }
    if (!_.isEmpty(approvalNew.handler_ns)) {
        allApproved = allApproved && approvalNew.ns_approval_status;
        console.log("checkAllDepartmentsApproved approvalNew.handler_ns", allApproved, approvalNew.handler_ns, approvalNew.ns_approval_status);
    }
    if (!_.isEmpty(approvalNew.handler_legal)) {
        allApproved = allApproved && approvalNew.legal_approval_status;
        console.log("checkAllDepartmentsApproved approvalNew.handler_legal", allApproved, approvalNew.handler_legal, approvalNew.legal_approval_status);
    }
    if (!_.isEmpty(approvalNew.handler_sra)) {
        allApproved = allApproved && approvalNew.sra_approval_status;
        console.log("checkAllDepartmentsApproved approvalNew.handler_sra", allApproved, approvalNew.handler_sra, approvalNew.sra_approval_status);
    }
    console.log("checkAllDepartmentsApproved:", allApproved);
    return allApproved;
}
var approvalContent = function (ctx, recordId, _a) {
    var approveField = _a.approveField;
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var user, approvalOld, approvalNew, currentStepApprovalStatus, pendingDepartments, allApproved;
        return tslib_1.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    user = ctx.meta.user;
                    return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
                case 1:
                    approvalOld = _b.sent();
                    if (approvalOld.current_step != consts_1.Step.draft && !(0, lodash_1.includes)(approvalOld.person_pending_approve, user.userId)) {
                        return [2, {}];
                    }
                    if ((0, lodash_1.includes)(approvalOld.person_done, user.userId)) {
                        console.log('[approvalContent]: 用户已在 person_done 中, 不允许重复审核.');
                        return [2, {}];
                    }
                    return [4, updateApproveFieldStatus(ctx, recordId, approveField, true)];
                case 2:
                    _b.sent();
                    return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
                case 3:
                    approvalNew = _b.sent();
                    return [4, updateUserStepStatus(ctx, approvalNew, { approvalStatus: consts_1.ApprovalStatus.approved, approveField: approveField })];
                case 4:
                    _b.sent();
                    currentStepApprovalStatus = consts_1.ApprovalStatus.approved;
                    if (!(approvalNew.current_step === consts_1.Step.departmental_review)) return [3, 7];
                    pendingDepartments = [];
                    if (!_.isEmpty(approvalNew.handler_ca) && !hasReviewed(approvalNew.ca_approval_status)) {
                        pendingDepartments.push('CA');
                    }
                    if (!_.isEmpty(approvalNew.handler_ns) && !hasReviewed(approvalNew.ns_approval_status)) {
                        pendingDepartments.push('NS');
                    }
                    if (!_.isEmpty(approvalNew.handler_legal) && !hasReviewed(approvalNew.legal_approval_status)) {
                        pendingDepartments.push('Legal');
                    }
                    if (!_.isEmpty(approvalNew.handler_sra) && !hasReviewed(approvalNew.sra_approval_status)) {
                        pendingDepartments.push('SRA');
                    }
                    if (!(pendingDepartments.length > 0)) return [3, 6];
                    console.log("[approvalContent]: \u6709\u5176\u4ED6\u90E8\u95E8\u672A\u5BA1\u6279 (".concat(pendingDepartments.join(', '), "), \u53EA\u7ED3\u675F\u5F53\u524D\u7528\u6237\u5BA1\u6279\u4EFB\u52A1,\u4E0D\u63A8\u8FDB\u5BA1\u6279\u8FDB\u5EA6."));
                    return [4, (0, notification_1.sendDepartmentReviewProgressNotification)(ctx, approvalNew)];
                case 5:
                    _b.sent();
                    return [2, {}];
                case 6:
                    allApproved = checkAllDepartmentsApproved(approvalNew);
                    currentStepApprovalStatus = allApproved ? consts_1.ApprovalStatus.approved : consts_1.ApprovalStatus.rejected;
                    console.log('[approvalContent]: 部门复审完成, 结果为:', currentStepApprovalStatus);
                    return [3, 11];
                case 7:
                    if (!(approvalNew.current_step === consts_1.Step.personnel_review)) return [3, 11];
                    if (!!hasReviewed(approvalNew.approval_status)) return [3, 10];
                    console.log('[approvalContent]: 审核专员未审批, 只结束当前用户审批任务,不推进审批进度.');
                    if (!(approveField === 'kids_approval_status' && hasReviewed(approvalNew.kids_approval_status))) return [3, 9];
                    return [4, (0, notification_1.sendPersonnelReviewProgressNotification)(ctx, approvalNew)];
                case 8:
                    _b.sent();
                    _b.label = 9;
                case 9: return [2, {}];
                case 10:
                    currentStepApprovalStatus = approvalNew.approval_status ? consts_1.ApprovalStatus.approved : consts_1.ApprovalStatus.rejected;
                    console.log('[approvalContent]: 审核专员复审完成, 结果为:', currentStepApprovalStatus);
                    _b.label = 11;
                case 11:
                    if (!(approvalNew.child_files == 'yes')) return [3, 15];
                    if (!!hasReviewed(approvalNew.kids_approval_status)) return [3, 14];
                    console.log('[approvalContent]: kids审核人未审批, 只结束当前用户审批任务,不推进审批进度.');
                    if (!(approveField !== 'kids_approval_status' && hasReviewed(approvalNew.approval_status))) return [3, 13];
                    return [4, (0, notification_1.sendPersonnelReviewProgressNotification)(ctx, approvalNew)];
                case 12:
                    _b.sent();
                    _b.label = 13;
                case 13: return [2, {}];
                case 14:
                    if (approvalNew.kids_approval_status == false) {
                        currentStepApprovalStatus = consts_1.ApprovalStatus.rejected;
                    }
                    console.log('[approvalContent]: kids审核完成, 结果为:', currentStepApprovalStatus);
                    _b.label = 15;
                case 15:
                    console.log("[approvalContent] \u63A8\u8FDB\u5BA1\u6279\u8FDB\u5EA6,\u53C2\u6570\u4E3A \u5BA1\u6279\u5355: ".concat(recordId, " \u5F53\u524D\u6B65\u9AA4: ").concat(approvalNew.current_step, " \u5BA1\u6279\u7ED3\u679C\u4E3A: ").concat(currentStepApprovalStatus));
                    return [4, advanceApproval(ctx, recordId, currentStepApprovalStatus)];
                case 16:
                    _b.sent();
                    return [2, {}];
            }
        });
    });
};
exports.approvalContent = approvalContent;
var rejectContent = function (ctx, recordId, _a) {
    var approveField = _a.approveField;
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var user, approvalOld, approvalNew, currentStepApprovalStatus, departmentsToCheck, hasPending;
        return tslib_1.__generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    user = ctx.meta.user;
                    return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
                case 1:
                    approvalOld = _b.sent();
                    if (approvalOld.current_step != consts_1.Step.draft && !(0, lodash_1.includes)(approvalOld.person_pending_approve, user.userId)) {
                        return [2, {}];
                    }
                    if ((0, lodash_1.includes)(approvalOld.person_done, user.userId)) {
                        console.log('[rejectContent]: 用户已在 person_done 中, 不允许重复审核.');
                        return [2, {}];
                    }
                    return [4, updateApproveFieldStatus(ctx, recordId, approveField, false)];
                case 2:
                    _b.sent();
                    return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
                case 3:
                    approvalNew = _b.sent();
                    currentStepApprovalStatus = consts_1.ApprovalStatus.rejected;
                    return [4, updateUserStepStatus(ctx, approvalNew, { approvalStatus: consts_1.ApprovalStatus.rejected, approveField: approveField })];
                case 4:
                    _b.sent();
                    if (!(approvalNew.current_step === consts_1.Step.departmental_review)) return [3, 7];
                    departmentsToCheck = [];
                    if (!_.isEmpty(approvalNew.handler_ca))
                        departmentsToCheck.push('ca_approval_status');
                    if (!_.isEmpty(approvalNew.handler_ns))
                        departmentsToCheck.push('ns_approval_status');
                    if (!_.isEmpty(approvalNew.handler_legal))
                        departmentsToCheck.push('legal_approval_status');
                    if (!_.isEmpty(approvalNew.handler_sra))
                        departmentsToCheck.push('sra_approval_status');
                    hasPending = departmentsToCheck.some(function (field) { return !hasReviewed(approvalNew[field]); });
                    if (!hasPending) return [3, 6];
                    console.log('[rejectContent]: 有其他部门未审批, 只结束当前用户审批任务,不推进审批进度.');
                    return [4, (0, notification_1.sendDepartmentReviewProgressNotification)(ctx, approvalNew)];
                case 5:
                    _b.sent();
                    return [2, {}];
                case 6:
                    console.log('[rejectContent]: 部门复审完成');
                    return [3, 11];
                case 7:
                    if (!(approvalNew.current_step === consts_1.Step.personnel_review)) return [3, 11];
                    if (!!hasReviewed(approvalNew.approval_status)) return [3, 10];
                    console.log('[rejectContent]: 审核专员未审批, 只结束当前用户审批任务,不推进审批进度.');
                    if (!(approveField === 'kids_approval_status' && hasReviewed(approvalNew.kids_approval_status))) return [3, 9];
                    return [4, (0, notification_1.sendPersonnelReviewProgressNotification)(ctx, approvalNew)];
                case 8:
                    _b.sent();
                    _b.label = 9;
                case 9: return [2, {}];
                case 10:
                    console.log('[rejectContent]: 审核专员复审完成');
                    _b.label = 11;
                case 11:
                    if (!(approvalNew.child_files == 'yes')) return [3, 15];
                    if (!!hasReviewed(approvalNew.kids_approval_status)) return [3, 14];
                    console.log('[rejectContent]: kids审核人未审批, 只结束当前用户审批任务,不推进审批进度.');
                    if (!(approveField !== 'kids_approval_status' && hasReviewed(approvalNew.approval_status))) return [3, 13];
                    return [4, (0, notification_1.sendPersonnelReviewProgressNotification)(ctx, approvalNew)];
                case 12:
                    _b.sent();
                    _b.label = 13;
                case 13: return [2, {}];
                case 14:
                    console.log('[rejectContent]: kids审核完成');
                    _b.label = 15;
                case 15:
                    console.log("[rejectContent] \u63A8\u8FDB\u5BA1\u6279\u8FDB\u5EA6,\u53C2\u6570\u4E3A \u5BA1\u6279\u5355: ".concat(recordId, " \u5F53\u524D\u6B65\u9AA4: ").concat(approvalNew.current_step, " \u5BA1\u6279\u7ED3\u679C\u4E3A: ").concat(currentStepApprovalStatus));
                    return [4, advanceApproval(ctx, recordId, currentStepApprovalStatus)];
                case 16:
                    _b.sent();
                    return [2, {}];
            }
        });
    });
};
exports.rejectContent = rejectContent;
var submitKidsContent = function (ctx, recordId, currentStepApprovalStatus) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var approveField;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (currentStepApprovalStatus != consts_1.ApprovalStatus.approved && currentStepApprovalStatus != consts_1.ApprovalStatus.rejected) {
                        throw new Error('无效的审核状态.');
                    }
                    approveField = "kids_approval_status";
                    if (!(currentStepApprovalStatus === consts_1.ApprovalStatus.approved)) return [3, 2];
                    return [4, (0, exports.approvalContent)(ctx, recordId, { approveField: approveField })];
                case 1:
                    _a.sent();
                    return [3, 4];
                case 2: return [4, (0, exports.rejectContent)(ctx, recordId, { approveField: approveField })];
                case 3:
                    _a.sent();
                    _a.label = 4;
                case 4: return [2];
            }
        });
    });
};
exports.submitKidsContent = submitKidsContent;
var submitContent = function (ctx, recordId, currentStepApprovalStatus, skip) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var approvalNew, user, allow, aProcess, aProcess_1, aProcess_1_1, item, e_8_1, pepsicoMaterial, spaceUsers, owner, approvalType, allTrue1, allTrue, spaceUsers, owner, materials, pendingUploadMaterials;
        var e_8, _a;
        return tslib_1.__generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
                case 1:
                    approvalNew = _b.sent();
                    user = ctx.meta.user;
                    allow = false;
                    if (!(approvalNew.current_step === consts_1.Step.ai_review && user.is_space_admin && skip === true)) return [3, 10];
                    console.log("".concat(user.name, "(").concat(user.userId, ")\u63D0\u4EA4\u4E86AI\u5BA1\u6838\u6B65\u9AA4:"), recordId);
                    allow = true;
                    return [4, ctx.getObject("pepsico_approval_process").find({
                            filters: [
                                ["owner", "=", process.env.PEPSICO_CONTENT_APPROVAL_AI_USERID],
                                ["pepsico_material_approval", "=", recordId],
                                ["current_step", "=", consts_1.Step.ai_review],
                                ["space", "=", approvalNew.space],
                                ["approved", "=", 'progess']
                            ],
                            top: 1,
                            sort: "modified desc"
                        })];
                case 2:
                    aProcess = _b.sent();
                    console.log('管理员提交了AI审核步骤, 修改审批历史: process.length:', aProcess.length, JSON.stringify({
                        filters: [
                            ["owner", "=", process.env.PEPSICO_CONTENT_APPROVAL_AI_USERID],
                            ["pepsico_material_approval", "=", recordId],
                            ["current_step", "=", consts_1.Step.ai_review],
                            ["space", "=", approvalNew.space],
                            ["approved", "=", 'progess']
                        ],
                        top: 1,
                        sort: "modified desc"
                    }));
                    _b.label = 3;
                case 3:
                    _b.trys.push([3, 8, 9, 10]);
                    aProcess_1 = tslib_1.__values(aProcess), aProcess_1_1 = aProcess_1.next();
                    _b.label = 4;
                case 4:
                    if (!!aProcess_1_1.done) return [3, 7];
                    item = aProcess_1_1.value;
                    console.log('管理员提交了AI审核步骤, 修改审批历史: process Id:', item._id);
                    return [4, ctx.getObject("pepsico_approval_process").directUpdate(item._id, {
                            submitted: new Date(),
                            modified: new Date(),
                            modified_by: user.userId,
                            approved: 'skip'
                        })];
                case 5:
                    _b.sent();
                    _b.label = 6;
                case 6:
                    aProcess_1_1 = aProcess_1.next();
                    return [3, 4];
                case 7: return [3, 10];
                case 8:
                    e_8_1 = _b.sent();
                    e_8 = { error: e_8_1 };
                    return [3, 10];
                case 9:
                    try {
                        if (aProcess_1_1 && !aProcess_1_1.done && (_a = aProcess_1.return)) _a.call(aProcess_1);
                    }
                    finally { if (e_8) throw e_8.error; }
                    return [7];
                case 10:
                    if (allow != true && approvalNew.current_step != consts_1.Step.draft && !(0, lodash_1.includes)(approvalNew.person_pending_approve, user.userId)) {
                        return [2, {}];
                    }
                    if (!(approvalNew.current_step === consts_1.Step.draft)) return [3, 12];
                    return [4, ctx.getObject('pepsico_material').find({ filters: ['pepsico_material_approval', '=', recordId], fields: ['material'] })];
                case 11:
                    pepsicoMaterial = _b.sent();
                    if (pepsicoMaterial.length === 0) {
                        throw new Error('请先「上传审核文件」');
                    }
                    _b.label = 12;
                case 12:
                    if (!(approvalNew.is_external && approvalNew.current_step === consts_1.Step.draft && approvalNew.external_submitted != true)) return [3, 19];
                    if (!(approvalNew.owner === user.userId)) return [3, 18];
                    if (!approvalNew.material_owner) {
                        throw new Error('请先选择材料owner');
                    }
                    return [4, ctx.getObject('space_users').find({
                            filters: [['email', '=', approvalNew.material_owner], ['space', '=', approvalNew.space]]
                        })];
                case 13:
                    spaceUsers = _b.sent();
                    if (!(spaceUsers && spaceUsers.length > 0)) return [3, 16];
                    owner = spaceUsers[0];
                    return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, {
                            owner: owner.user,
                            owner_department: owner.organization,
                            external_submitted: true,
                            internal_collaborator_edit: approvalNew.material_owner,
                            internal_collaborator: owner.user,
                        })];
                case 14:
                    _b.sent();
                    return [4, ctx.getObject('pepsico_material_approval').findOne(recordId)];
                case 15:
                    approvalNew = _b.sent();
                    _b.label = 16;
                case 16: return [4, (0, notification_1.sendNotifications)(ctx, approvalNew, [approvalNew.internal_collaborator], '协助提交材料审批单')];
                case 17:
                    _b.sent();
                    _b.label = 18;
                case 18: return [2];
                case 19:
                    if (!(approvalNew.current_step === consts_1.Step.draft)) return [3, 27];
                    return [4, getApproveType(ctx, approvalNew)];
                case 20:
                    approvalType = _b.sent();
                    return [4, ctx.getObject('pepsico_material_approval').directUpdate(approvalNew._id, {
                            approval_type: approvalType
                        })];
                case 21:
                    _b.sent();
                    if (!false) return [3, 24];
                    return [4, (0, material_1.deleteBulkDocOneDriveShareLink)(ctx, recordId)];
                case 22:
                    allTrue1 = _b.sent();
                    if (allTrue1 != true) {
                        return [2, {
                                status: 500,
                                msg: '更新素材失败, 请稍后重试',
                                data: {}
                            }];
                    }
                    return [4, (0, material_1.downloadBulkFromOneDriveDoc)(ctx, recordId)];
                case 23:
                    allTrue = _b.sent();
                    if (allTrue != true) {
                        return [2, {
                                status: 500,
                                msg: '更新素材失败, 请稍后重试',
                                data: {}
                            }];
                    }
                    _b.label = 24;
                case 24:
                    if (!(approvalNew && approvalNew.material_owner)) return [3, 27];
                    return [4, ctx.getObject('space_users').find({
                            filters: [['email', '=', approvalNew.material_owner], ['space', '=', approvalNew.space]]
                        })];
                case 25:
                    spaceUsers = _b.sent();
                    if (!(spaceUsers && spaceUsers.length > 0)) return [3, 27];
                    owner = spaceUsers[0];
                    return [4, ctx.getObject('pepsico_material_approval').directUpdate(recordId, {
                            material_owner_id: owner.user
                        })];
                case 26:
                    _b.sent();
                    _b.label = 27;
                case 27:
                    console.log("[submitContent] \u6B65\u9AA4\u63D0\u4EA4\uFF0C\u53C2\u6570\u4E3A \u5BA1\u6279\u5355: ".concat(recordId, " \u5F53\u524D\u6B65\u9AA4: ").concat(approvalNew.current_step, " \u5BA1\u6279\u7ED3\u679C\u4E3A: ").concat(currentStepApprovalStatus));
                    if (!(approvalNew.current_step === consts_1.Step.ai_review && currentStepApprovalStatus === consts_1.ApprovalStatus.approved)) return [3, 32];
                    return [4, (0, material_1.getOneDriveMaterials)(ctx, recordId)];
                case 28:
                    materials = _b.sent();
                    if (!(approvalNew.materials_uploaded_to_onedrive_status != 'completed')) return [3, 32];
                    console.log('materials:', materials.length);
                    if (!(materials.length === 0)) return [3, 30];
                    return [4, ctx.getObject('pepsico_material_approval').directUpdate(approvalNew._id, {
                            materials_uploaded_to_onedrive_status: 'no_materials',
                            materials_xml_to_word_status: 'no_materials'
                        })];
                case 29:
                    _b.sent();
                    return [3, 32];
                case 30:
                    pendingUploadMaterials = materials.filter(function (material) {
                        return material.uploaded_to_onedrive !== true;
                    });
                    console.log('pendingUploadMaterials:', pendingUploadMaterials.length);
                    if (!(pendingUploadMaterials.length > 0)) return [3, 32];
                    return [4, ctx.getObject('pepsico_material_approval').directUpdate(approvalNew._id, {
                            materials_uploaded_to_onedrive_status: 'pending'
                        })];
                case 31:
                    _b.sent();
                    return [2];
                case 32:
                    console.time('updateUserStepStatus: ' + recordId);
                    return [4, updateUserStepStatus(ctx, approvalNew, { approvalStatus: currentStepApprovalStatus, approveField: '' })];
                case 33:
                    _b.sent();
                    console.timeEnd('updateUserStepStatus: ' + recordId);
                    console.time('advanceApproval: ' + recordId);
                    return [4, advanceApproval(ctx, recordId, currentStepApprovalStatus)];
                case 34:
                    _b.sent();
                    console.timeEnd('advanceApproval: ' + recordId);
                    return [2];
            }
        });
    });
};
exports.submitContent = submitContent;
var hasReviewed = function (approvalStatus) {
    if (approvalStatus === true || approvalStatus === false) {
        return true;
    }
    return false;
};
//# sourceMappingURL=approval_engine.js.map