"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendPersonnelReviewProgressNotification = exports.sendDepartmentReviewProgressNotification = exports.sendDelayNotifications = exports.sendNotifications = void 0;
var tslib_1 = require("tslib");
var lodash_1 = require("lodash");
var moment = require('moment');
var sendNotifications = function (ctx, materialApproval, nextApprovers, actionLabel) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var nextApprovers_1, nextApprovers_1_1, to, e_1_1, spaceUsers, spaceUsers_1, spaceUsers_1_1, spaceUser, error_1, e_2_1, error_2;
    var e_1, _a, e_2, _b;
    return tslib_1.__generator(this, function (_c) {
        switch (_c.label) {
            case 0:
                console.log("sendNotifications", materialApproval._id, materialApproval.name, nextApprovers, actionLabel);
                _c.label = 1;
            case 1:
                _c.trys.push([1, 21, , 22]);
                _c.label = 2;
            case 2:
                _c.trys.push([2, 7, 8, 9]);
                nextApprovers_1 = tslib_1.__values(nextApprovers), nextApprovers_1_1 = nextApprovers_1.next();
                _c.label = 3;
            case 3:
                if (!!nextApprovers_1_1.done) return [3, 6];
                to = nextApprovers_1_1.value;
                if (!to) return [3, 5];
                return [4, ctx.broker.call('notifications.add', {
                        message: {
                            name: "".concat(actionLabel, ": ").concat(materialApproval.name),
                            body: "",
                            related_to: {
                                o: "pepsico_material_approval",
                                ids: [materialApproval._id]
                            },
                            related_name: materialApproval.name,
                            from: materialApproval.owner,
                            space: materialApproval.space
                        },
                        from: materialApproval.owner,
                        to: to
                    })];
            case 4:
                _c.sent();
                _c.label = 5;
            case 5:
                nextApprovers_1_1 = nextApprovers_1.next();
                return [3, 3];
            case 6: return [3, 9];
            case 7:
                e_1_1 = _c.sent();
                e_1 = { error: e_1_1 };
                return [3, 9];
            case 8:
                try {
                    if (nextApprovers_1_1 && !nextApprovers_1_1.done && (_a = nextApprovers_1.return)) _a.call(nextApprovers_1);
                }
                finally { if (e_1) throw e_1.error; }
                return [7];
            case 9: return [4, ctx.getObject('space_users').find({ filters: [['user', '=', nextApprovers], ['space', '=', materialApproval.space]] })];
            case 10:
                spaceUsers = _c.sent();
                _c.label = 11;
            case 11:
                _c.trys.push([11, 18, 19, 20]);
                spaceUsers_1 = tslib_1.__values(spaceUsers), spaceUsers_1_1 = spaceUsers_1.next();
                _c.label = 12;
            case 12:
                if (!!spaceUsers_1_1.done) return [3, 17];
                spaceUser = spaceUsers_1_1.value;
                if (!(spaceUser.email && spaceUser.email_notification)) return [3, 16];
                _c.label = 13;
            case 13:
                _c.trys.push([13, 15, , 16]);
                return [4, ctx.broker.call('@builder6/email.send', {
                        to: spaceUser.email,
                        subject: "".concat(actionLabel, ": ").concat(materialApproval.name),
                        html: "\n                            <p>\u60A8\u6709\u4E00\u4EFD\u6587\u4EF6\u9700\u8981\u67E5\u770B\u548C\u5904\u7406\u3002\u8BF7\u70B9\u51FB\u4E0B\u9762\u7684\u94FE\u63A5\u6765\u8BBF\u95EE\u8BE5\u6587\u4EF6\uFF1A</p>\n                            <a href=\"".concat(process.env.ROOT_URL, "/app/pepsico_content_review/pepsico_material_approval/view/").concat(materialApproval._id, "?side_object=pepsico_material_approval&side_listview_id=pending\">").concat(materialApproval.name, "</a>\n                        ")
                    })];
            case 14:
                _c.sent();
                return [3, 16];
            case 15:
                error_1 = _c.sent();
                console.log(error_1);
                return [3, 16];
            case 16:
                spaceUsers_1_1 = spaceUsers_1.next();
                return [3, 12];
            case 17: return [3, 20];
            case 18:
                e_2_1 = _c.sent();
                e_2 = { error: e_2_1 };
                return [3, 20];
            case 19:
                try {
                    if (spaceUsers_1_1 && !spaceUsers_1_1.done && (_b = spaceUsers_1.return)) _b.call(spaceUsers_1);
                }
                finally { if (e_2) throw e_2.error; }
                return [7];
            case 20:
                console.log('sendNotifications-email: ' + nextApprovers.length);
                return [3, 22];
            case 21:
                error_2 = _c.sent();
                console.log(error_2);
                return [3, 22];
            case 22: return [2];
        }
    });
}); };
exports.sendNotifications = sendNotifications;
var sendDelayNotifications = function (ctx, intervalMinutes) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var triggerTime, records, records_1, records_1_1, record, e_3_1;
    var e_3, _a;
    return tslib_1.__generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                console.time("sendDelayNotifications");
                triggerTime = moment();
                return [4, ctx.getObject('pepsico_material_approval').find({
                        filters: [
                            ['launch', '=', 'postpone'],
                            ['postpone_launch_date', '>=', triggerTime.toDate()],
                            ['postpone_launch_date', '<=', moment(triggerTime).add(intervalMinutes, 'minute').toDate()]
                        ]
                    })];
            case 1:
                records = _b.sent();
                console.log("sendDelayNotifications count:", records.length, {
                    filters: [
                        ['launch', '=', 'postpone'],
                        ['postpone_launch_date', '>=', triggerTime.toDate()],
                        ['postpone_launch_date', '<=', moment(triggerTime).add(intervalMinutes, 'minute').toDate()]
                    ]
                });
                _b.label = 2;
            case 2:
                _b.trys.push([2, 7, 8, 9]);
                records_1 = tslib_1.__values(records), records_1_1 = records_1.next();
                _b.label = 3;
            case 3:
                if (!!records_1_1.done) return [3, 6];
                record = records_1_1.value;
                if (!record.material_owner_id) return [3, 5];
                return [4, (0, exports.sendNotifications)(ctx, record, [record.material_owner_id], '请数据传输')];
            case 4:
                _b.sent();
                _b.label = 5;
            case 5:
                records_1_1 = records_1.next();
                return [3, 3];
            case 6: return [3, 9];
            case 7:
                e_3_1 = _b.sent();
                e_3 = { error: e_3_1 };
                return [3, 9];
            case 8:
                try {
                    if (records_1_1 && !records_1_1.done && (_a = records_1.return)) _a.call(records_1);
                }
                finally { if (e_3) throw e_3.error; }
                return [7];
            case 9:
                console.timeEnd("sendDelayNotifications");
                return [2];
        }
    });
}); };
exports.sendDelayNotifications = sendDelayNotifications;
var sendDepartmentReviewProgressNotification = function (ctx, approval) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var departments, approved, rejected, pending, departments_1, departments_1_1, dept, parts, actionLabel, message, error_3, spaceUsers, spaceUsers_2, spaceUsers_2_1, spaceUser, statusRows, e_4_1, error_4;
    var e_5, _a, e_4, _b;
    return tslib_1.__generator(this, function (_c) {
        switch (_c.label) {
            case 0:
                departments = [
                    { name: 'CA', handler: approval.handler_ca, status: approval.ca_approval_status },
                    { name: 'NS', handler: approval.handler_ns, status: approval.ns_approval_status },
                    { name: 'Legal', handler: approval.handler_legal, status: approval.legal_approval_status },
                    { name: 'SRA', handler: approval.handler_sra, status: approval.sra_approval_status },
                ];
                if (approval.child_files === 'yes' && !(0, lodash_1.isEmpty)(approval.handler_kids)) {
                    departments.push({ name: 'Kids', handler: approval.handler_kids, status: approval.kids_approval_status });
                }
                approved = [];
                rejected = [];
                pending = [];
                try {
                    for (departments_1 = tslib_1.__values(departments), departments_1_1 = departments_1.next(); !departments_1_1.done; departments_1_1 = departments_1.next()) {
                        dept = departments_1_1.value;
                        if ((0, lodash_1.isEmpty)(dept.handler))
                            continue;
                        if (dept.status === true) {
                            approved.push(dept.name);
                        }
                        else if (dept.status === false) {
                            rejected.push(dept.name);
                        }
                        else {
                            pending.push(dept.name);
                        }
                    }
                }
                catch (e_5_1) { e_5 = { error: e_5_1 }; }
                finally {
                    try {
                        if (departments_1_1 && !departments_1_1.done && (_a = departments_1.return)) _a.call(departments_1);
                    }
                    finally { if (e_5) throw e_5.error; }
                }
                parts = [];
                if (approved.length > 0) {
                    parts.push(approved.map(function (d) { return "".concat(d, "\u5DF2\u6838\u51C6"); }).join('、'));
                }
                if (rejected.length > 0) {
                    parts.push(rejected.map(function (d) { return "".concat(d, "\u5DF2\u9A73\u56DE"); }).join('、'));
                }
                actionLabel = '部门审批进度';
                message = parts.join('、');
                if (pending.length > 0) {
                    if (message) {
                        actionLabel = message + ", \u5269\u4F59".concat(pending.join('、'), "\u5F85\u5904\u7406");
                    }
                    else {
                        actionLabel = "\u5269\u4F59".concat(pending.join('、'), "\u5F85\u5904\u7406");
                    }
                }
                else if (message) {
                    actionLabel = message;
                }
                _c.label = 1;
            case 1:
                _c.trys.push([1, 4, , 5]);
                if (!approval.owner) return [3, 3];
                return [4, ctx.broker.call('notifications.add', {
                        message: {
                            name: "".concat(actionLabel, ": ").concat(approval.name),
                            body: "",
                            related_to: {
                                o: "pepsico_material_approval",
                                ids: [approval._id]
                            },
                            related_name: approval.name,
                            from: approval.owner,
                            space: approval.space
                        },
                        from: approval.owner,
                        to: approval.owner
                    })];
            case 2:
                _c.sent();
                _c.label = 3;
            case 3: return [3, 5];
            case 4:
                error_3 = _c.sent();
                console.log('sendDepartmentReviewProgressNotification-notification error:', error_3);
                return [3, 5];
            case 5:
                _c.trys.push([5, 15, , 16]);
                return [4, ctx.getObject('space_users').find({ filters: [['user', '=', approval.owner], ['space', '=', approval.space]] })];
            case 6:
                spaceUsers = _c.sent();
                _c.label = 7;
            case 7:
                _c.trys.push([7, 12, 13, 14]);
                spaceUsers_2 = tslib_1.__values(spaceUsers), spaceUsers_2_1 = spaceUsers_2.next();
                _c.label = 8;
            case 8:
                if (!!spaceUsers_2_1.done) return [3, 11];
                spaceUser = spaceUsers_2_1.value;
                if (!spaceUser.email) return [3, 10];
                statusRows = departments
                    .filter(function (dept) { return !(0, lodash_1.isEmpty)(dept.handler); })
                    .map(function (dept) {
                    var statusText = '待处理';
                    var color = '#999';
                    if (dept.status === true) {
                        statusText = '已核准';
                        color = '#52c41a';
                    }
                    else if (dept.status === false) {
                        statusText = '已驳回';
                        color = '#f5222d';
                    }
                    return "<tr><td style=\"padding:6px 12px;border:1px solid #eee;\">".concat(dept.name, "</td><td style=\"padding:6px 12px;border:1px solid #eee;color:").concat(color, ";\">").concat(statusText, "</td></tr>");
                })
                    .join('');
                console.log('sendDepartmentReviewProgressNotification-email @builder6/email.send:', {
                    to: spaceUser.email,
                    subject: "\u90E8\u95E8\u5BA1\u6279\u8FDB\u5EA6\u901A\u77E5: ".concat(approval.name),
                    html: "\n                        <p>\u60A8\u7684\u5BA1\u6279\u5355 <b>".concat(approval.name, "</b> \u90E8\u95E8\u5BA1\u6279\u8FDB\u5EA6\u5982\u4E0B\uFF1A</p>\n                        <table style=\"border-collapse:collapse;margin:12px 0;\">\n                            <tr style=\"background:#fafafa;\"><th style=\"padding:6px 12px;border:1px solid #eee;\">\u90E8\u95E8</th><th style=\"padding:6px 12px;border:1px solid #eee;\">\u72B6\u6001</th></tr>\n                            ").concat(statusRows, "\n                        </table>\n                        <p>").concat(actionLabel, "</p>\n                        <p>\u8BF7\u70B9\u51FB\u4E0B\u9762\u7684\u94FE\u63A5\u67E5\u770B\u5BA1\u6279\u5355\u8BE6\u60C5\uFF1A</p>\n                        <a href=\"").concat(process.env.ROOT_URL, "/app/pepsico_content_review/pepsico_material_approval/view/").concat(approval._id, "\">").concat(approval.name, "</a>\n                    ")
                });
                return [4, ctx.broker.call('@builder6/email.send', {
                        to: spaceUser.email,
                        subject: "\u90E8\u95E8\u5BA1\u6279\u8FDB\u5EA6\u901A\u77E5: ".concat(approval.name),
                        html: "\n                        <p>\u60A8\u7684\u5BA1\u6279\u5355 <b>".concat(approval.name, "</b> \u90E8\u95E8\u5BA1\u6279\u8FDB\u5EA6\u5982\u4E0B\uFF1A</p>\n                        <table style=\"border-collapse:collapse;margin:12px 0;\">\n                            <tr style=\"background:#fafafa;\"><th style=\"padding:6px 12px;border:1px solid #eee;\">\u90E8\u95E8</th><th style=\"padding:6px 12px;border:1px solid #eee;\">\u72B6\u6001</th></tr>\n                            ").concat(statusRows, "\n                        </table>\n                        <p>").concat(actionLabel, "</p>\n                        <p>\u8BF7\u70B9\u51FB\u4E0B\u9762\u7684\u94FE\u63A5\u67E5\u770B\u5BA1\u6279\u5355\u8BE6\u60C5\uFF1A</p>\n                        <a href=\"").concat(process.env.ROOT_URL, "/app/pepsico_content_review/pepsico_material_approval/view/").concat(approval._id, "\">").concat(approval.name, "</a>\n                    ")
                    })];
            case 9:
                _c.sent();
                _c.label = 10;
            case 10:
                spaceUsers_2_1 = spaceUsers_2.next();
                return [3, 8];
            case 11: return [3, 14];
            case 12:
                e_4_1 = _c.sent();
                e_4 = { error: e_4_1 };
                return [3, 14];
            case 13:
                try {
                    if (spaceUsers_2_1 && !spaceUsers_2_1.done && (_b = spaceUsers_2.return)) _b.call(spaceUsers_2);
                }
                finally { if (e_4) throw e_4.error; }
                return [7];
            case 14: return [3, 16];
            case 15:
                error_4 = _c.sent();
                console.log('sendDepartmentReviewProgressNotification-email error:', error_4);
                return [3, 16];
            case 16: return [2];
        }
    });
}); };
exports.sendDepartmentReviewProgressNotification = sendDepartmentReviewProgressNotification;
var sendPersonnelReviewProgressNotification = function (ctx, approval) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
    var reviewers, approved, rejected, pending, reviewers_1, reviewers_1_1, reviewer, parts, actionLabel, message, error_5, spaceUsers, spaceUsers_3, spaceUsers_3_1, spaceUser, statusRows, e_6_1, error_6;
    var e_7, _a, e_6, _b;
    return tslib_1.__generator(this, function (_c) {
        switch (_c.label) {
            case 0:
                reviewers = [
                    { name: '专员', handler: approval.person_pending_approve, status: approval.approval_status },
                ];
                if (approval.child_files === 'yes' && !(0, lodash_1.isEmpty)(approval.handler_kids)) {
                    reviewers.push({ name: 'Kids', handler: approval.handler_kids, status: approval.kids_approval_status });
                }
                approved = [];
                rejected = [];
                pending = [];
                try {
                    for (reviewers_1 = tslib_1.__values(reviewers), reviewers_1_1 = reviewers_1.next(); !reviewers_1_1.done; reviewers_1_1 = reviewers_1.next()) {
                        reviewer = reviewers_1_1.value;
                        if ((0, lodash_1.isEmpty)(reviewer.handler))
                            continue;
                        if (reviewer.status === true) {
                            approved.push(reviewer.name);
                        }
                        else if (reviewer.status === false) {
                            rejected.push(reviewer.name);
                        }
                        else {
                            pending.push(reviewer.name);
                        }
                    }
                }
                catch (e_7_1) { e_7 = { error: e_7_1 }; }
                finally {
                    try {
                        if (reviewers_1_1 && !reviewers_1_1.done && (_a = reviewers_1.return)) _a.call(reviewers_1);
                    }
                    finally { if (e_7) throw e_7.error; }
                }
                parts = [];
                if (approved.length > 0) {
                    parts.push(approved.map(function (d) { return "".concat(d, "\u5DF2\u6838\u51C6"); }).join('、'));
                }
                if (rejected.length > 0) {
                    parts.push(rejected.map(function (d) { return "".concat(d, "\u5DF2\u9A73\u56DE"); }).join('、'));
                }
                actionLabel = '审批进度';
                message = parts.join('、');
                if (pending.length > 0) {
                    if (message) {
                        actionLabel = message + ", \u5269\u4F59".concat(pending.join('、'), "\u5F85\u5904\u7406");
                    }
                    else {
                        actionLabel = "\u5269\u4F59".concat(pending.join('、'), "\u5F85\u5904\u7406");
                    }
                }
                else if (message) {
                    actionLabel = message;
                }
                _c.label = 1;
            case 1:
                _c.trys.push([1, 4, , 5]);
                if (!approval.owner) return [3, 3];
                return [4, ctx.broker.call('notifications.add', {
                        message: {
                            name: "".concat(actionLabel, ": ").concat(approval.name),
                            body: "",
                            related_to: {
                                o: "pepsico_material_approval",
                                ids: [approval._id]
                            },
                            related_name: approval.name,
                            from: approval.owner,
                            space: approval.space
                        },
                        from: approval.owner,
                        to: approval.owner
                    })];
            case 2:
                _c.sent();
                _c.label = 3;
            case 3: return [3, 5];
            case 4:
                error_5 = _c.sent();
                console.log('sendPersonnelReviewProgressNotification-notification error:', error_5);
                return [3, 5];
            case 5:
                _c.trys.push([5, 15, , 16]);
                return [4, ctx.getObject('space_users').find({ filters: [['user', '=', approval.owner], ['space', '=', approval.space]] })];
            case 6:
                spaceUsers = _c.sent();
                _c.label = 7;
            case 7:
                _c.trys.push([7, 12, 13, 14]);
                spaceUsers_3 = tslib_1.__values(spaceUsers), spaceUsers_3_1 = spaceUsers_3.next();
                _c.label = 8;
            case 8:
                if (!!spaceUsers_3_1.done) return [3, 11];
                spaceUser = spaceUsers_3_1.value;
                if (!spaceUser.email) return [3, 10];
                statusRows = reviewers
                    .filter(function (r) { return !(0, lodash_1.isEmpty)(r.handler); })
                    .map(function (r) {
                    var statusText = '待处理';
                    var color = '#999';
                    if (r.status === true) {
                        statusText = '已核准';
                        color = '#52c41a';
                    }
                    else if (r.status === false) {
                        statusText = '已驳回';
                        color = '#f5222d';
                    }
                    return "<tr><td style=\"padding:6px 12px;border:1px solid #eee;\">".concat(r.name, "</td><td style=\"padding:6px 12px;border:1px solid #eee;color:").concat(color, ";\">").concat(statusText, "</td></tr>");
                })
                    .join('');
                return [4, ctx.broker.call('@builder6/email.send', {
                        to: spaceUser.email,
                        subject: "\u5BA1\u6279\u8FDB\u5EA6\u901A\u77E5: ".concat(approval.name),
                        html: "\n                        <p>\u60A8\u7684\u5BA1\u6279\u5355 <b>".concat(approval.name, "</b> \u5BA1\u6279\u8FDB\u5EA6\u5982\u4E0B\uFF1A</p>\n                        <table style=\"border-collapse:collapse;margin:12px 0;\">\n                            <tr style=\"background:#fafafa;\"><th style=\"padding:6px 12px;border:1px solid #eee;\">\u5BA1\u6838\u4EBA</th><th style=\"padding:6px 12px;border:1px solid #eee;\">\u72B6\u6001</th></tr>\n                            ").concat(statusRows, "\n                        </table>\n                        <p>").concat(actionLabel, "</p>\n                        <p>\u8BF7\u70B9\u51FB\u4E0B\u9762\u7684\u94FE\u63A5\u67E5\u770B\u5BA1\u6279\u5355\u8BE6\u60C5\uFF1A</p>\n                        <a href=\"").concat(process.env.ROOT_URL, "/app/pepsico_content_review/pepsico_material_approval/view/").concat(approval._id, "\">").concat(approval.name, "</a>\n                    ")
                    })];
            case 9:
                _c.sent();
                _c.label = 10;
            case 10:
                spaceUsers_3_1 = spaceUsers_3.next();
                return [3, 8];
            case 11: return [3, 14];
            case 12:
                e_6_1 = _c.sent();
                e_6 = { error: e_6_1 };
                return [3, 14];
            case 13:
                try {
                    if (spaceUsers_3_1 && !spaceUsers_3_1.done && (_b = spaceUsers_3.return)) _b.call(spaceUsers_3);
                }
                finally { if (e_6) throw e_6.error; }
                return [7];
            case 14: return [3, 16];
            case 15:
                error_6 = _c.sent();
                console.log('sendPersonnelReviewProgressNotification-email error:', error_6);
                return [3, 16];
            case 16: return [2];
        }
    });
}); };
exports.sendPersonnelReviewProgressNotification = sendPersonnelReviewProgressNotification;
//# sourceMappingURL=notification.js.map