"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var actions = require("./actions");
var methods = require("./methods");
var consts_1 = require("./methods/consts");
var notification_1 = require("./methods/notification");
var pls_1 = require("./methods/pls");
var lodash_1 = require("lodash");
var objectql = require('@steedos/objectql');
var path = require('path');
var project = require('../package.json');
var packageName = project.name;
var CronMixin = require("moleculer-cron");
var packageLoader = require('@steedos/service-package-loader');
var moment = require('moment');
function getCollection(name) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var adapter;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    adapter = objectql.getDataSource('default').adapter;
                    return [4, adapter.connect()];
                case 1:
                    _a.sent();
                    return [2, adapter.collection(name)];
            }
        });
    });
}
var STEEDOS_CRON_ENABLED = process.env.STEEDOS_CRON_ENABLED;
var PEPSICO_CRON_SEND_DELAY_NOTIFICATION_INTERVAL_MINUTES = Number(process.env.PEPSICO_CRON_SEND_DELAY_NOTIFICATION_INTERVAL_MINUTES || 5);
var cronJobs = [
    {
        name: "materialsUploadToOneDriveJob",
        cronTime: process.env.PEPSICO_CRON_MATERIAL_UPLOAD_ONEDRIVE,
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var e_1;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            console.log('materialsUploadToOneDriveJob run', new Date());
                            return [4, this.broker.call("".concat(packageName, ".materialsUploadToOneDrive"))];
                        case 1:
                            _a.sent();
                            return [3, 3];
                        case 2:
                            e_1 = _a.sent();
                            console.log("materialsUploadToOneDriveJob error ", e_1);
                            return [3, 3];
                        case 3: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("materialsUploadToOneDriveJob");
        },
        onComplete: function () {
            console.log("materialsUploadToOneDriveJob is stopped");
        }
    },
    {
        name: "materialsDownloadFromOneDriveJob",
        cronTime: process.env.PEPSICO_CRON_MATERIAL_DOWNLOAD_ONEDRIVE,
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var e_2;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            console.log('materialsDownloadFromOneDriveJob run', new Date());
                            return [4, this.broker.call("".concat(packageName, ".materialsDownloadFromOneDrive"))];
                        case 1:
                            _a.sent();
                            return [3, 3];
                        case 2:
                            e_2 = _a.sent();
                            console.log("materialsDownloadFromOneDriveJob error ", e_2);
                            return [3, 3];
                        case 3: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("materialsDownloadFromOneDriveJob");
        },
        onComplete: function () {
            console.log("materialsDownloadFromOneDriveJob is stopped");
        }
    },
    {
        name: "materialsRemoveShareLinkToOneDriveJob",
        cronTime: process.env.PEPSICO_CRON_MATERIAL_DOWNLOAD_ONEDRIVE,
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var e_3;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            console.log('materialsRemoveShareLinkToOneDriveJob run', new Date());
                            return [4, this.broker.call("".concat(packageName, ".materialsRemoveShareLinkToOneDrive"))];
                        case 1:
                            _a.sent();
                            return [3, 3];
                        case 2:
                            e_3 = _a.sent();
                            console.log("materialsRemoveShareLinkToOneDriveJob error ", e_3);
                            return [3, 3];
                        case 3: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("materialsRemoveShareLinkToOneDriveJob");
        },
        onComplete: function () {
            console.log("materialsRemoveShareLinkToOneDriveJob is stopped");
        }
    },
    {
        name: "sendDelayNotificationsJob",
        cronTime: "0 */".concat(PEPSICO_CRON_SEND_DELAY_NOTIFICATION_INTERVAL_MINUTES, " * * * *"),
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var e_4;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            console.log('sendDelayNotificationsJob run', new Date());
                            return [4, this.broker.call("".concat(packageName, ".sendDelayNotifications"))];
                        case 1:
                            _a.sent();
                            return [3, 3];
                        case 2:
                            e_4 = _a.sent();
                            console.log("sendDelayNotificationsJob error ", e_4);
                            return [3, 3];
                        case 3: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("sendDelayNotificationsJob");
        },
        onComplete: function () {
            console.log("sendDelayNotificationsJob is stopped");
        }
    }, {
        name: "checkPasswordExpiryJob",
        cronTime: process.env.PEPSICO_CRON_CHECK_PASSWORD_EXPIRY || '0 0 10 * * *',
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var e_5;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            console.log('checkPasswordExpiryJob run', new Date());
                            return [4, this.broker.call("".concat(packageName, ".checkPasswordExpiry"))];
                        case 1:
                            _a.sent();
                            return [3, 3];
                        case 2:
                            e_5 = _a.sent();
                            console.log("checkPasswordExpiryJob error ", e_5);
                            return [3, 3];
                        case 3: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("checkPasswordExpiryJob");
        },
        onComplete: function () {
            console.log("checkPasswordExpiryJob is stopped");
        }
    }, {
        name: "syncDashboard",
        cronTime: process.env.PEPSICO_CRON_DASHBOARD_SYNC_DATA || '0 3 * * *',
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var e_6;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            console.log('syncDashboard run', new Date());
                            return [4, this.broker.call("".concat(packageName, ".dashboardSyncData"))];
                        case 1:
                            _a.sent();
                            return [3, 3];
                        case 2:
                            e_6 = _a.sent();
                            console.log("syncDashboard error ", e_6);
                            return [3, 3];
                        case 3: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("syncDashboard");
        },
        onComplete: function () {
            console.log("syncDashboard is stopped");
        }
    }, {
        name: "scanPLSFiles",
        cronTime: process.env.PEPSICO_CRON_PLS_SCAN || '0 23 * * *',
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var e_7;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            console.log('scanPLSFiles run', new Date());
                            return [4, this.broker.call("".concat(packageName, ".scanPLSFiles"))];
                        case 1:
                            _a.sent();
                            return [3, 3];
                        case 2:
                            e_7 = _a.sent();
                            console.log("scanPLSFiles error ", e_7);
                            return [3, 3];
                        case 3: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("scanPLSFiles");
        },
        onComplete: function () {
            console.log("scanPLSFiles is stopped");
        }
    }, {
        name: "scanInactiveUsers",
        cronTime: process.env.PEPSICO_CRON_INACTIVE_USERS_SCAN || '0 1 * * *',
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var e_8;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 2, , 3]);
                            console.log('scanInactiveUsers run', new Date());
                            return [4, this.broker.call("".concat(packageName, ".scanInactiveUsers"))];
                        case 1:
                            _a.sent();
                            return [3, 3];
                        case 2:
                            e_8 = _a.sent();
                            console.log("scanInactiveUsers error ", e_8);
                            return [3, 3];
                        case 3: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("scanInactiveUsers");
        },
        onComplete: function () {
            console.log("scanInactiveUsers is stopped");
        }
    }, {
        name: "sendMonthlySpotCheckReportJob",
        cronTime: process.env.PEPSICO_CRON_SEND_SPOT_REPORT || '0 10 * * *',
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var rid, e_9;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 4, , 5]);
                            console.log('sendMonthlySpotCheckReportJob run', new Date());
                            return [4, this.broker.call("".concat(packageName, ".getReportId"))];
                        case 1:
                            rid = _a.sent();
                            if (!rid) return [3, 3];
                            return [4, this.broker.call("".concat(packageName, ".sendMonthlySpotCheckReport"), { rid: rid })];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3: return [3, 5];
                        case 4:
                            e_9 = _a.sent();
                            console.log("sendMonthlySpotCheckReportJob error ", e_9);
                            return [3, 5];
                        case 5: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("sendMonthlySpotCheckReportJob");
        },
        onComplete: function () {
            console.log("sendMonthlySpotCheckReportJob is stopped");
        }
    }, {
        name: "sendMonthlySpotCheckPoolJob",
        cronTime: process.env.PEPSICO_CRON_SEND_SPOT_POOL || '0 10 * * *',
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var pid, e_10;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 4, , 5]);
                            console.log('sendMonthlySpotCheckPoolJob run', new Date());
                            return [4, this.broker.call("".concat(packageName, ".getPoolId"))];
                        case 1:
                            pid = _a.sent();
                            if (!pid) return [3, 3];
                            return [4, this.broker.call("".concat(packageName, ".generateSpotCheckPool"), { pid: pid })];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3: return [3, 5];
                        case 4:
                            e_10 = _a.sent();
                            console.log("sendMonthlySpotCheckPoolJob error ", e_10);
                            return [3, 5];
                        case 5: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("sendMonthlySpotCheckPoolJob");
        },
        onComplete: function () {
            console.log("sendMonthlySpotCheckPoolJob is stopped");
        }
    },
    {
        name: "scanApprovalAndDeletedMaterialFromSharepointJob",
        cronTime: process.env.PEPSICO_CRON_DELETE_MATERIAL_FROM_SHAREPOINT || '0 2 * * *',
        timeZone: process.env.STEEDOS_CRON_TIME_ZONE || 'Asia/Shanghai',
        manualStart: false,
        onTick: function () {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var e_11;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 4, , 5]);
                            console.log('scanApprovalAndDeletedMaterialFromSharepointJob run', new Date());
                            if (!(process.env.PEPSICO_CRON_DELETE_MATERIAL_FROM_SHAREPOINT_DISABLE == 'true')) return [3, 1];
                            console.log('已停用自动批量删除Sharepoint过期素材');
                            return [3, 3];
                        case 1: return [4, this.broker.call("".concat(packageName, ".scanApprovalAndDeletedMaterialFromSharepoint"))];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3: return [3, 5];
                        case 4:
                            e_11 = _a.sent();
                            console.log("scanApprovalAndDeletedMaterialFromSharepointJob error ", e_11);
                            return [3, 5];
                        case 5: return [2];
                    }
                });
            });
        },
        onInitialize: function () {
            this.startJob("scanApprovalAndDeletedMaterialFromSharepointJob");
        },
        onComplete: function () {
            console.log("scanApprovalAndDeletedMaterialFromSharepointJob is stopped");
        }
    }
];
module.exports = {
    name: packageName,
    namespace: "steedos",
    mixins: [packageLoader, CronMixin],
    settings: {
        cronJobs: STEEDOS_CRON_ENABLED == true || STEEDOS_CRON_ENABLED == 'true' ? cronJobs : null,
    },
    metadata: {
        $package: {
            name: project.name,
            path: path.join(__dirname, ".."),
            isPackage: true
        }
    },
    dependencies: ['@steedos/standard-objects'],
    actions: tslib_1.__assign(tslib_1.__assign({}, actions), { materialsUploadToOneDrive: function (ctx) {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var logger, pendingApprovals, pendingApprovals_1, pendingApprovals_1_1, pendingApproval, allTrue, error_1, e_12_1;
                var e_12, _a;
                return tslib_1.__generator(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4, this.getLogger()];
                        case 1:
                            logger = _b.sent();
                            return [4, this.getObject('pepsico_material_approval').find({
                                    filters: [
                                        ['current_step', '=', 'ai_review'],
                                        ['materials_uploaded_to_onedrive_status', 'in', ['pending', 'failed']],
                                    ],
                                    top: 10,
                                    sort: "modified desc"
                                })];
                        case 2:
                            pendingApprovals = _b.sent();
                            console.log("定时任务[素材上传到oneDrive] count: " + pendingApprovals.length, { objectName: 'pepsico_material_approval', count: pendingApprovals.length, approvals: (0, lodash_1.map)(pendingApprovals, function (item) { return (0, lodash_1.pick)(item, ['_id', 'materials_uploaded_to_onedrive_failed_count', 'current_step', 'materials_uploaded_to_onedrive_status']); }) });
                            ctx.meta.user = {
                                userId: process.env.PEPSICO_CONTENT_APPROVAL_AI_USERID
                            };
                            ctx.getObject = this.getObject;
                            ctx.logger = logger;
                            _b.label = 3;
                        case 3:
                            _b.trys.push([3, 13, 14, 15]);
                            pendingApprovals_1 = tslib_1.__values(pendingApprovals), pendingApprovals_1_1 = pendingApprovals_1.next();
                            _b.label = 4;
                        case 4:
                            if (!!pendingApprovals_1_1.done) return [3, 12];
                            pendingApproval = pendingApprovals_1_1.value;
                            if (!(!pendingApproval.materials_uploaded_to_onedrive_failed_count || pendingApproval.materials_uploaded_to_onedrive_failed_count < 5)) return [3, 11];
                            _b.label = 5;
                        case 5:
                            _b.trys.push([5, 9, , 11]);
                            return [4, this.uploadBulkDocToOneDrive(ctx, pendingApproval._id)];
                        case 6:
                            allTrue = _b.sent();
                            if (!allTrue) return [3, 8];
                            return [4, this.submitContent(ctx, pendingApproval._id, consts_1.ApprovalStatus.approved)];
                        case 7:
                            _b.sent();
                            _b.label = 8;
                        case 8: return [3, 11];
                        case 9:
                            error_1 = _b.sent();
                            return [4, this.getObject('pepsico_material_approval').directUpdate(pendingApproval._id, {
                                    materials_uploaded_to_onedrive_status: 'failed',
                                    $inc: {
                                        materials_uploaded_to_onedrive_failed_count: 1
                                    }
                                })];
                        case 10:
                            _b.sent();
                            logger.error("".concat(pendingApproval._id, "-[\u7D20\u6750\u4E0A\u4F20\u5230oneDrive\u5931\u8D25]:").concat(error_1.message), { objectName: 'pepsico_material_approval', _id: pendingApproval._id });
                            return [3, 11];
                        case 11:
                            pendingApprovals_1_1 = pendingApprovals_1.next();
                            return [3, 4];
                        case 12: return [3, 15];
                        case 13:
                            e_12_1 = _b.sent();
                            e_12 = { error: e_12_1 };
                            return [3, 15];
                        case 14:
                            try {
                                if (pendingApprovals_1_1 && !pendingApprovals_1_1.done && (_a = pendingApprovals_1.return)) _a.call(pendingApprovals_1);
                            }
                            finally { if (e_12) throw e_12.error; }
                            return [7];
                        case 15: return [2];
                    }
                });
            });
        }, materialsDownloadFromOneDrive: function (ctx) {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var logger, pendingApprovals, pendingApprovals_2, pendingApprovals_2_1, pendingApproval, error_2, e_13_1;
                var e_13, _a;
                return tslib_1.__generator(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4, this.getLogger()];
                        case 1:
                            logger = _b.sent();
                            return [4, this.getObject('pepsico_material_approval').find({
                                    filters: [
                                        ['current_step', '=', ['awaiting_deployment', 'conclusion']],
                                        ['materials_download_from_onedrive_status', 'in', ['pending', 'failed']],
                                    ],
                                    top: 10,
                                    sort: "modified desc"
                                })];
                        case 2:
                            pendingApprovals = _b.sent();
                            console.log("定时任务[从oneDrive下载素材] count: " + pendingApprovals.length, { objectName: 'pepsico_material_approval', count: pendingApprovals.length, approvals: (0, lodash_1.map)(pendingApprovals, function (item) { return (0, lodash_1.pick)(item, ['_id', 'materials_download_from_onedrive_failed_count', 'current_step', 'materials_download_from_onedrive_status']); }) });
                            ctx.meta.user = {
                                userId: process.env.PEPSICO_CONTENT_APPROVAL_AI_USERID
                            };
                            ctx.getObject = this.getObject;
                            ctx.logger = logger;
                            _b.label = 3;
                        case 3:
                            _b.trys.push([3, 11, 12, 13]);
                            pendingApprovals_2 = tslib_1.__values(pendingApprovals), pendingApprovals_2_1 = pendingApprovals_2.next();
                            _b.label = 4;
                        case 4:
                            if (!!pendingApprovals_2_1.done) return [3, 10];
                            pendingApproval = pendingApprovals_2_1.value;
                            if (!(!pendingApproval.materials_download_from_onedrive_failed_count || pendingApproval.materials_download_from_onedrive_failed_count < 5)) return [3, 9];
                            _b.label = 5;
                        case 5:
                            _b.trys.push([5, 7, , 9]);
                            return [4, this.downloadBulkFromOneDriveDoc(ctx, pendingApproval._id)];
                        case 6:
                            _b.sent();
                            return [3, 9];
                        case 7:
                            error_2 = _b.sent();
                            return [4, this.getObject('pepsico_material_approval').directUpdate(pendingApproval._id, {
                                    materials_download_from_onedrive_status: 'failed',
                                    $inc: {
                                        materials_download_from_onedrive_failed_count: 1
                                    }
                                })];
                        case 8:
                            _b.sent();
                            logger.error("".concat(pendingApproval._id, "-[\u4ECEoneDrive\u4E0B\u8F7D\u7D20\u6750\u5931\u8D25]:").concat(error_2.message), { objectName: 'pepsico_material_approval', _id: pendingApproval._id });
                            return [3, 9];
                        case 9:
                            pendingApprovals_2_1 = pendingApprovals_2.next();
                            return [3, 4];
                        case 10: return [3, 13];
                        case 11:
                            e_13_1 = _b.sent();
                            e_13 = { error: e_13_1 };
                            return [3, 13];
                        case 12:
                            try {
                                if (pendingApprovals_2_1 && !pendingApprovals_2_1.done && (_a = pendingApprovals_2.return)) _a.call(pendingApprovals_2);
                            }
                            finally { if (e_13) throw e_13.error; }
                            return [7];
                        case 13: return [2];
                    }
                });
            });
        }, materialsRemoveShareLinkToOneDrive: function (ctx) {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var logger, pendingApprovals, pendingApprovals_3, pendingApprovals_3_1, pendingApproval, error_3, e_14_1;
                var e_14, _a;
                return tslib_1.__generator(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4, this.getLogger()];
                        case 1:
                            logger = _b.sent();
                            return [4, this.getObject('pepsico_material_approval').find({
                                    filters: [
                                        ['current_step', '=', ['awaiting_deployment', 'conclusion']],
                                        ['materials_remove_share_link_from_onedrive_status', 'in', ['pending', 'failed']],
                                    ],
                                    top: 10,
                                    sort: "modified desc"
                                })];
                        case 2:
                            pendingApprovals = _b.sent();
                            console.log("定时任务[从oneDrive删除共享连接] count: " + pendingApprovals.length, { objectName: 'pepsico_material_approval', count: pendingApprovals.length, approvals: (0, lodash_1.map)(pendingApprovals, function (item) { return (0, lodash_1.pick)(item, ['_id', 'materials_remove_share_link_from_onedrive_failed_count', 'current_step', 'materials_remove_share_link_from_onedrive_status']); }) });
                            ctx.meta.user = {
                                userId: process.env.PEPSICO_CONTENT_APPROVAL_AI_USERID
                            };
                            ctx.getObject = this.getObject;
                            ctx.logger = logger;
                            _b.label = 3;
                        case 3:
                            _b.trys.push([3, 11, 12, 13]);
                            pendingApprovals_3 = tslib_1.__values(pendingApprovals), pendingApprovals_3_1 = pendingApprovals_3.next();
                            _b.label = 4;
                        case 4:
                            if (!!pendingApprovals_3_1.done) return [3, 10];
                            pendingApproval = pendingApprovals_3_1.value;
                            if (!(!pendingApproval.materials_remove_share_link_from_onedrive_failed_count || pendingApproval.materials_remove_share_link_from_onedrive_failed_count < 5)) return [3, 9];
                            _b.label = 5;
                        case 5:
                            _b.trys.push([5, 7, , 9]);
                            return [4, this.deleteBulkDocOneDriveShareLink(ctx, pendingApproval._id)];
                        case 6:
                            _b.sent();
                            return [3, 9];
                        case 7:
                            error_3 = _b.sent();
                            return [4, this.getObject('pepsico_material_approval').directUpdate(pendingApproval._id, {
                                    materials_remove_share_link_from_onedrive_status: 'failed',
                                    $inc: {
                                        materials_remove_share_link_from_onedrive_failed_count: 1
                                    }
                                })];
                        case 8:
                            _b.sent();
                            logger.error("".concat(pendingApproval._id, "-[\u4ECEoneDrive\u5220\u9664\u5171\u4EAB\u8FDE\u63A5\u5931\u8D25]:").concat(error_3.message), { objectName: 'pepsico_material_approval', _id: pendingApproval._id });
                            return [3, 9];
                        case 9:
                            pendingApprovals_3_1 = pendingApprovals_3.next();
                            return [3, 4];
                        case 10: return [3, 13];
                        case 11:
                            e_14_1 = _b.sent();
                            e_14 = { error: e_14_1 };
                            return [3, 13];
                        case 12:
                            try {
                                if (pendingApprovals_3_1 && !pendingApprovals_3_1.done && (_a = pendingApprovals_3.return)) _a.call(pendingApprovals_3);
                            }
                            finally { if (e_14) throw e_14.error; }
                            return [7];
                        case 13: return [2];
                    }
                });
            });
        }, sendDelayNotifications: function (ctx) {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var logger;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.getLogger()];
                        case 1:
                            logger = _a.sent();
                            ctx.getObject = this.getObject;
                            ctx.logger = logger;
                            return [4, (0, notification_1.sendDelayNotifications)(ctx, PEPSICO_CRON_SEND_DELAY_NOTIFICATION_INTERVAL_MINUTES)];
                        case 2:
                            _a.sent();
                            return [2];
                    }
                });
            });
        }, checkPasswordExpiry: function (ctx) {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var logger;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.getLogger()];
                        case 1:
                            logger = _a.sent();
                            ctx.getObject = this.getObject;
                            ctx.logger = logger;
                            return [4, methods.checkPasswordExpiry(ctx)];
                        case 2:
                            _a.sent();
                            return [2];
                    }
                });
            });
        }, scanPLSFiles: {
            rest: {
                method: 'GET',
                fullPath: '/api/pepsico-content/scan/pls'
            },
            handler: function (ctx) {
                return tslib_1.__awaiter(this, void 0, void 0, function () {
                    var user, logger, addPLSCount;
                    return tslib_1.__generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                user = ctx.meta.user;
                                if (user && !user.is_space_admin) {
                                    return [2, { error: '没有权限' }];
                                }
                                return [4, this.getLogger()];
                            case 1:
                                logger = _a.sent();
                                ctx.getObject = this.getObject;
                                ctx.logger = logger;
                                return [4, (0, pls_1.scanPLSFiles)(ctx)];
                            case 2:
                                addPLSCount = _a.sent();
                                return [2, {
                                        '新增PLS记录数量': addPLSCount
                                    }];
                        }
                    });
                });
            }
        }, scanInactiveUsers: {
            rest: {
                method: 'GET',
                fullPath: '/api/pepsico-content/scan/inactive-users'
            },
            handler: function (ctx) {
                return tslib_1.__awaiter(this, void 0, void 0, function () {
                    var user, logger, today, ninetyDaysAgo, coll, suColl, users, users_1, users_1_1, user_1, e_15_1;
                    var e_15, _a;
                    return tslib_1.__generator(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                user = ctx.meta.user;
                                if (user && !user.is_space_admin) {
                                    return [2, { error: '没有权限' }];
                                }
                                return [4, this.getLogger()];
                            case 1:
                                logger = _b.sent();
                                ctx.getObject = this.getObject;
                                ctx.logger = logger;
                                today = new Date();
                                ninetyDaysAgo = new Date();
                                ninetyDaysAgo.setDate(today.getDate() - 90);
                                return [4, getCollection('users')];
                            case 2:
                                coll = _b.sent();
                                return [4, getCollection('space_users')];
                            case 3:
                                suColl = _b.sent();
                                return [4, coll.updateMany({}, {
                                        $set: {
                                            login_expired: false
                                        }
                                    })];
                            case 4:
                                _b.sent();
                                return [4, suColl.updateMany({}, {
                                        $set: {
                                            login_expired: false
                                        }
                                    })];
                            case 5:
                                _b.sent();
                                return [4, coll.find({
                                        $or: [
                                            {
                                                $and: [
                                                    { last_logon: { $ne: null } },
                                                    { last_logon: { $lt: ninetyDaysAgo } }
                                                ]
                                            },
                                            {
                                                $and: [
                                                    { last_logon: null },
                                                    { created: { $lt: ninetyDaysAgo } }
                                                ]
                                            }
                                        ]
                                    }).toArray()];
                            case 6:
                                users = _b.sent();
                                _b.label = 7;
                            case 7:
                                _b.trys.push([7, 13, 14, 15]);
                                users_1 = tslib_1.__values(users), users_1_1 = users_1.next();
                                _b.label = 8;
                            case 8:
                                if (!!users_1_1.done) return [3, 12];
                                user_1 = users_1_1.value;
                                return [4, this.getObject('users').directUpdate(user_1._id, {
                                        login_expired: true
                                    })];
                            case 9:
                                _b.sent();
                                return [4, this.getObject('space_users').directUpdateMany(['user', '=', user_1._id], {
                                        login_expired: true
                                    })];
                            case 10:
                                _b.sent();
                                _b.label = 11;
                            case 11:
                                users_1_1 = users_1.next();
                                return [3, 8];
                            case 12: return [3, 15];
                            case 13:
                                e_15_1 = _b.sent();
                                e_15 = { error: e_15_1 };
                                return [3, 15];
                            case 14:
                                try {
                                    if (users_1_1 && !users_1_1.done && (_a = users_1.return)) _a.call(users_1);
                                }
                                finally { if (e_15) throw e_15.error; }
                                return [7];
                            case 15: return [2, {
                                    '新增90天未登录用户数量': users.length
                                }];
                        }
                    });
                });
            }
        }, getReportId: function (ctx) {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var logger, lastMonth, report, day, dayOfWeek, spaces, newReport;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.getLogger()];
                        case 1:
                            logger = _a.sent();
                            ctx.getObject = this.getObject;
                            ctx.logger = logger;
                            lastMonth = moment().subtract(1, 'month').format('YYYY-MM');
                            return [4, ctx.getObject('pepsico_spot_check_report').directFind({
                                    filters: ['year_month', '=', lastMonth]
                                })];
                        case 2:
                            report = _a.sent();
                            if (report.length > 0) {
                                return [2];
                            }
                            day = moment().get('date');
                            dayOfWeek = moment().day();
                            return [4, ctx.getObject('spaces').find({ filters: [] })];
                        case 3:
                            spaces = _a.sent();
                            if (!(day >= 10 && dayOfWeek != 0 && dayOfWeek != 6)) return [3, 5];
                            return [4, ctx.getObject('pepsico_spot_check_report').directInsert({
                                    name: "Report-".concat(lastMonth),
                                    year_month: lastMonth,
                                    owner: spaces[0].owner,
                                    space: spaces[0]._id,
                                    created: new Date(),
                                    modified: new Date(),
                                    created_by: spaces[0].owner,
                                    modified_by: spaces[0].owner
                                })];
                        case 4:
                            newReport = _a.sent();
                            return [2, newReport._id];
                        case 5: return [2];
                    }
                });
            });
        }, getPoolId: function (ctx) {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var logger, lastMonth, pool, day, dayOfWeek, spaces, newPool;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4, this.getLogger()];
                        case 1:
                            logger = _a.sent();
                            ctx.getObject = this.getObject;
                            ctx.logger = logger;
                            lastMonth = moment().subtract(1, 'month').format('YYYY-MM');
                            return [4, ctx.getObject('pepsico_spot_check_pool').directFind({
                                    filters: ['year_month', '=', lastMonth]
                                })];
                        case 2:
                            pool = _a.sent();
                            if (pool.length > 0) {
                                return [2];
                            }
                            day = moment().get('date');
                            dayOfWeek = moment().day();
                            return [4, ctx.getObject('spaces').find({ filters: [] })];
                        case 3:
                            spaces = _a.sent();
                            if (!(day >= 1 && dayOfWeek != 0 && dayOfWeek != 6)) return [3, 5];
                            return [4, ctx.getObject('pepsico_spot_check_pool').directInsert({
                                    name: "Pool-".concat(lastMonth),
                                    year_month: lastMonth,
                                    owner: spaces[0].owner,
                                    space: spaces[0]._id,
                                    created: new Date(),
                                    modified: new Date(),
                                    created_by: spaces[0].owner,
                                    modified_by: spaces[0].owner
                                })];
                        case 4:
                            newPool = _a.sent();
                            return [2, newPool._id];
                        case 5: return [2];
                    }
                });
            });
        }, permanentDeleteMaterialFromSharePoint: {
            rest: {
                method: 'POST',
                fullPath: '/api/pepsico-content/material/permanent-delete'
            },
            handler: function (ctx) {
                return tslib_1.__awaiter(this, void 0, void 0, function () {
                    var user, id, material;
                    return tslib_1.__generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                user = ctx.meta.user;
                                if (user && !user.is_space_admin) {
                                    return [2, { error: '没有权限' }];
                                }
                                ctx.getObject = this.getObject;
                                id = ctx.params.id;
                                return [4, ctx.getObject('pepsico_material').findOne(id)];
                            case 1:
                                material = _a.sent();
                                if (!material) {
                                    return [2, { error: '无效的ID' }];
                                }
                                return [4, ctx.broker.call('content-version-bridge.material_permanentDeleteFromOneDrive', { material: material })];
                            case 2: return [2, _a.sent()];
                        }
                    });
                });
            }
        }, scanApprovalAndDeletedMaterialFromSharepoint: function (ctx) {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var logger, lastMonth, approvalRecords, approvalRecords_1, approvalRecords_1_1, approval, e_16_1;
                var e_16, _a;
                return tslib_1.__generator(this, function (_b) {
                    switch (_b.label) {
                        case 0: return [4, this.getLogger()];
                        case 1:
                            logger = _b.sent();
                            ctx.getObject = this.getObject;
                            ctx.logger = logger;
                            lastMonth = moment().subtract(3, 'month').toDate();
                            return [4, ctx.getObject('pepsico_material_approval').find({
                                    filters: [['permanent_deleted', '!=', true], ['review_status', '=', 'approved'], ['current_step', '=', 'conclusion'], ['modified', '<=', lastMonth]]
                                })];
                        case 2:
                            approvalRecords = _b.sent();
                            _b.label = 3;
                        case 3:
                            _b.trys.push([3, 8, 9, 10]);
                            approvalRecords_1 = tslib_1.__values(approvalRecords), approvalRecords_1_1 = approvalRecords_1.next();
                            _b.label = 4;
                        case 4:
                            if (!!approvalRecords_1_1.done) return [3, 7];
                            approval = approvalRecords_1_1.value;
                            return [4, this.permanentlyDeleteApprovalAllMaterialFromSharePoint(ctx, approval)];
                        case 5:
                            _b.sent();
                            _b.label = 6;
                        case 6:
                            approvalRecords_1_1 = approvalRecords_1.next();
                            return [3, 4];
                        case 7: return [3, 10];
                        case 8:
                            e_16_1 = _b.sent();
                            e_16 = { error: e_16_1 };
                            return [3, 10];
                        case 9:
                            try {
                                if (approvalRecords_1_1 && !approvalRecords_1_1.done && (_a = approvalRecords_1.return)) _a.call(approvalRecords_1);
                            }
                            finally { if (e_16) throw e_16.error; }
                            return [7];
                        case 10: return [2];
                    }
                });
            });
        }, permanentlyDeleteApprovalAllMaterialFromSharePoint: {
            rest: {
                method: 'POST',
                fullPath: '/api/pepsico-content/approval/permanent-delete'
            },
            handler: function (ctx) {
                return tslib_1.__awaiter(this, void 0, void 0, function () {
                    var user, logger, id, approval;
                    return tslib_1.__generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                user = ctx.meta.user;
                                if (user && !user.is_space_admin) {
                                    return [2, { error: '没有权限' }];
                                }
                                return [4, this.getLogger()];
                            case 1:
                                logger = _a.sent();
                                ctx.getObject = this.getObject;
                                ctx.logger = logger;
                                id = ctx.params.id;
                                return [4, ctx.getObject('pepsico_material_approval').findOne(id)];
                            case 2:
                                approval = _a.sent();
                                if (!approval) {
                                    return [2, { error: '无效的ID' }];
                                }
                                return [4, this.permanentlyDeleteApprovalAllMaterialFromSharePoint(ctx, approval)];
                            case 3:
                                _a.sent();
                                return [2, {}];
                        }
                    });
                });
            }
        } }),
    events: {
        'pepsico_material_approval.mentioned': function (ctx) {
            return tslib_1.__awaiter(this, void 0, void 0, function () {
                var _a, recordId, userId;
                return tslib_1.__generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _a = ctx.params, recordId = _a.recordId, userId = _a.userId;
                            console.log('EVENT[pepsico_material_approval.mentioned]', recordId, userId);
                            if (!(recordId && userId)) return [3, 2];
                            return [4, this.getObject('pepsico_material_approval').directUpdate(recordId, {
                                    $addToSet: {
                                        person_view: userId
                                    }
                                })];
                        case 1:
                            _b.sent();
                            _b.label = 2;
                        case 2: return [2];
                    }
                });
            });
        }
    },
    methods: tslib_1.__assign(tslib_1.__assign({}, methods), { permanentlyDeleteApprovalAllMaterialFromSharePoint: function (ctx, approval) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
            var materialRecords, allSuccessful, materialRecords_1, materialRecords_1_1, material, error_4, e_17_1, error_5;
            var e_17, _a;
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 21, , 23]);
                        return [4, ctx.getObject('pepsico_material').find({
                                filters: [['pepsico_material_approval', '=', approval._id], ['permanent_deleted', '!=', true], ['extension_type', 'in', ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']]]
                            })];
                    case 1:
                        materialRecords = _b.sent();
                        allSuccessful = true;
                        _b.label = 2;
                    case 2:
                        _b.trys.push([2, 15, 16, 17]);
                        materialRecords_1 = tslib_1.__values(materialRecords), materialRecords_1_1 = materialRecords_1.next();
                        _b.label = 3;
                    case 3:
                        if (!!materialRecords_1_1.done) return [3, 14];
                        material = materialRecords_1_1.value;
                        if (!(material.download_from_onedrive === true || material.void_material === true)) return [3, 11];
                        _b.label = 4;
                    case 4:
                        _b.trys.push([4, 8, , 10]);
                        return [4, ctx.broker.call('content-version-bridge.material_permanentDeleteFromOneDrive', {
                                material: material
                            })];
                    case 5:
                        _b.sent();
                        return [4, ctx.getObject('pepsico_material').directUpdate(material._id, {
                                permanent_deleted: true,
                                permanent_deleted_date: new Date()
                            })];
                    case 6:
                        _b.sent();
                        return [4, ctx.logger.info("[\u6C38\u4E45\u5220\u9664sharepoint\u7D20\u6750]-".concat(approval._id, "-").concat(material._id), {
                                pepsico_material_approval: approval._id,
                                material: material._id
                            })];
                    case 7:
                        _b.sent();
                        return [3, 10];
                    case 8:
                        error_4 = _b.sent();
                        allSuccessful = false;
                        console.log("error", error_4);
                        return [4, ctx.logger.error("[\u6C38\u4E45\u5220\u9664sharepoint\u7D20\u6750]-".concat(approval._id, "-").concat(material._id), {
                                pepsico_material_approval: approval._id,
                                material: material._id,
                                error: error_4.message
                            })];
                    case 9:
                        _b.sent();
                        return [3, 10];
                    case 10: return [3, 13];
                    case 11:
                        allSuccessful = false;
                        return [4, ctx.logger.error("[\u6C38\u4E45\u5220\u9664sharepoint\u7D20\u6750]-".concat(approval._id, "-").concat(material._id), {
                                pepsico_material_approval: approval._id,
                                material: material._id,
                                error: '还未从sharepoint下载素材到本地.'
                            })];
                    case 12:
                        _b.sent();
                        _b.label = 13;
                    case 13:
                        materialRecords_1_1 = materialRecords_1.next();
                        return [3, 3];
                    case 14: return [3, 17];
                    case 15:
                        e_17_1 = _b.sent();
                        e_17 = { error: e_17_1 };
                        return [3, 17];
                    case 16:
                        try {
                            if (materialRecords_1_1 && !materialRecords_1_1.done && (_a = materialRecords_1.return)) _a.call(materialRecords_1);
                        }
                        finally { if (e_17) throw e_17.error; }
                        return [7];
                    case 17:
                        if (!allSuccessful) return [3, 20];
                        return [4, ctx.getObject('pepsico_material_approval').directUpdate(approval._id, {
                                permanent_deleted: true,
                                permanent_deleted_date: new Date()
                            })];
                    case 18:
                        _b.sent();
                        return [4, ctx.logger.info("[\u6C38\u4E45\u5220\u9664sharepoint\u7D20\u6750]-".concat(approval._id), {
                                pepsico_material_approval: approval._id
                            })];
                    case 19:
                        _b.sent();
                        _b.label = 20;
                    case 20: return [3, 23];
                    case 21:
                        error_5 = _b.sent();
                        return [4, ctx.logger.info("[\u6C38\u4E45\u5220\u9664sharepoint\u7D20\u6750]-".concat(approval._id), {
                                pepsico_material_approval: approval._id,
                                error: error_5.message
                            })];
                    case 22:
                        _b.sent();
                        return [3, 23];
                    case 23: return [2];
                }
            });
        }); } }),
    created: function () {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            return tslib_1.__generator(this, function (_a) {
                return [2];
            });
        });
    },
    started: function () {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            return tslib_1.__generator(this, function (_a) {
                return [2];
            });
        });
    },
    stopped: function () {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            return tslib_1.__generator(this, function (_a) {
                return [2];
            });
        });
    }
};
//# sourceMappingURL=index.js.map