"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkPasswordExpiry = void 0;
var tslib_1 = require("tslib");
var lodash_1 = require("lodash");
var moment = require('moment');
function checkPasswordExpiry(ctx) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var logger, advanceDays, notifiedUserIds, spaces, spaces_1, spaces_1_1, space, expiryDays, thresholdDays, thresholdDate, spaceUsers, userIds, chunkSize, expiredCount, i, chunk, users, users_1, users_1_1, user, lastModified, actualExpiryDate, diffDays, expiryDesc, emailSubject, emailBody, emailError_1, e_1_1, e_2_1, e_3;
        var e_2, _a, e_1, _b;
        return tslib_1.__generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    logger = ctx.logger;
                    _c.label = 1;
                case 1:
                    _c.trys.push([1, 26, , 27]);
                    advanceDays = process.env.PEPSICO_PASSWORD_EXPIRY_ADVANCE_DAYS ? parseInt(process.env.PEPSICO_PASSWORD_EXPIRY_ADVANCE_DAYS) : 5;
                    notifiedUserIds = new Set();
                    return [4, ctx.getObject('spaces').find({
                            filters: [['password_expiry_days', '>', 0]],
                            fields: ['_id', 'name', 'password_expiry_days']
                        })];
                case 2:
                    spaces = _c.sent();
                    logger.info("\u5F00\u59CB\u68C0\u67E5\u5BC6\u7801\u8FC7\u671F, \u6D89\u53CASpaces\u6570\u91CF: ".concat(spaces.length, ", \u63D0\u524D\u63D0\u9192\u5929\u6570: ").concat(advanceDays));
                    _c.label = 3;
                case 3:
                    _c.trys.push([3, 23, 24, 25]);
                    spaces_1 = tslib_1.__values(spaces), spaces_1_1 = spaces_1.next();
                    _c.label = 4;
                case 4:
                    if (!!spaces_1_1.done) return [3, 22];
                    space = spaces_1_1.value;
                    expiryDays = space.password_expiry_days;
                    thresholdDays = expiryDays - advanceDays;
                    thresholdDate = moment().subtract(thresholdDays, 'days').toDate();
                    logger.info("\u68C0\u67E5 Space: ".concat(space.name, " (").concat(space._id, "), \u5BC6\u7801\u6709\u6548\u671F: ").concat(expiryDays, "\u5929, \u68C0\u67E5\u9608\u503C: < ").concat(moment(thresholdDate).format('YYYY-MM-DD')));
                    return [4, ctx.getObject('space_users').find({
                            filters: [['space', '=', space._id]],
                            fields: ['user']
                        })];
                case 5:
                    spaceUsers = _c.sent();
                    userIds = (0, lodash_1.map)(spaceUsers, 'user').filter(function (u) { return u; });
                    if (userIds.length === 0) {
                        return [3, 21];
                    }
                    logger.info("Space ".concat(space.name, " \u7528\u6237\u603B\u6570: ").concat(userIds.length));
                    chunkSize = 500;
                    expiredCount = 0;
                    i = 0;
                    _c.label = 6;
                case 6:
                    if (!(i < userIds.length)) return [3, 20];
                    chunk = userIds.slice(i, i + chunkSize);
                    return [4, ctx.getObject('users').find({
                            filters: [
                                ['_id', 'in', chunk],
                                ['password_modified_at', '<', thresholdDate],
                                ['is_active', '=', true]
                            ],
                            fields: ['_id', 'name', 'email', 'password_modified_at']
                        })];
                case 7:
                    users = _c.sent();
                    _c.label = 8;
                case 8:
                    _c.trys.push([8, 17, 18, 19]);
                    users_1 = (e_1 = void 0, tslib_1.__values(users)), users_1_1 = users_1.next();
                    _c.label = 9;
                case 9:
                    if (!!users_1_1.done) return [3, 16];
                    user = users_1_1.value;
                    if (notifiedUserIds.has(user._id)) {
                        return [3, 15];
                    }
                    expiredCount++;
                    if (!user.email) return [3, 14];
                    _c.label = 10;
                case 10:
                    _c.trys.push([10, 12, , 13]);
                    lastModified = moment(user.password_modified_at);
                    actualExpiryDate = lastModified.clone().add(expiryDays, 'days');
                    diffDays = actualExpiryDate.diff(moment(), 'days');
                    expiryDesc = "已过期";
                    if (diffDays >= 0) {
                        expiryDesc = "\u5C06\u5728 ".concat(diffDays, " \u5929\u5185\u8FC7\u671F");
                    }
                    emailSubject = "[".concat(space.name, "] \u5BC6\u7801\u8FC7\u671F\u63D0\u9192");
                    emailBody = "\n                                <p>\u5C0A\u656C\u7684 ".concat(user.name, ":</p>\n                                <p>\u60A8\u7684\u8D26\u6237\u5BC6\u7801\u5373\u5C06\u5728 ").concat(space.name, " \u8FC7\u671F (\u8BBE\u7F6E\u6709\u6548\u671F\u4E3A ").concat(expiryDays, " \u5929)\u3002</p>\n                                <p>\u5F53\u524D\u72B6\u6001: <strong style=\"color:red\">").concat(expiryDesc, "</strong></p>\n                                <p>\u60A8\u6700\u540E\u4E00\u6B21\u4FEE\u6539\u5BC6\u7801\u7684\u65F6\u95F4\u662F: ").concat(lastModified.format('YYYY-MM-DD HH:mm'), "</p>\n                                <p>\u8BF7\u5C3D\u5FEB\u767B\u5F55\u7CFB\u7EDF\u5E76\u4FEE\u6539\u60A8\u7684\u5BC6\u7801\u3002</p>\n                            ");
                    return [4, ctx.broker.call('@builder6/email.send', {
                            to: user.email,
                            from: "admin",
                            subject: emailSubject,
                            html: emailBody
                        })];
                case 11:
                    _c.sent();
                    logger.info("\u5DF2\u53D1\u9001\u5BC6\u7801\u8FC7\u671F\u90AE\u4EF6\u7ED9: ".concat(user.name, " (").concat(user.email, ")"));
                    notifiedUserIds.add(user._id);
                    return [3, 13];
                case 12:
                    emailError_1 = _c.sent();
                    logger.error("\u53D1\u9001\u90AE\u4EF6\u5931\u8D25: ".concat(user.name, " (").concat(user.email, ")"), emailError_1);
                    return [3, 13];
                case 13: return [3, 15];
                case 14:
                    logger.info("\u7528\u6237\u5BC6\u7801\u8FC7\u671F\u4F46\u65E0\u90AE\u7BB1: ".concat(user.name));
                    _c.label = 15;
                case 15:
                    users_1_1 = users_1.next();
                    return [3, 9];
                case 16: return [3, 19];
                case 17:
                    e_1_1 = _c.sent();
                    e_1 = { error: e_1_1 };
                    return [3, 19];
                case 18:
                    try {
                        if (users_1_1 && !users_1_1.done && (_b = users_1.return)) _b.call(users_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                    return [7];
                case 19:
                    i += chunkSize;
                    return [3, 6];
                case 20:
                    logger.info("Space ".concat(space.name, " \u68C0\u67E5\u5B8C\u6210, \u53D1\u9001\u63D0\u9192\u6570: ").concat(expiredCount));
                    _c.label = 21;
                case 21:
                    spaces_1_1 = spaces_1.next();
                    return [3, 4];
                case 22: return [3, 25];
                case 23:
                    e_2_1 = _c.sent();
                    e_2 = { error: e_2_1 };
                    return [3, 25];
                case 24:
                    try {
                        if (spaces_1_1 && !spaces_1_1.done && (_a = spaces_1.return)) _a.call(spaces_1);
                    }
                    finally { if (e_2) throw e_2.error; }
                    return [7];
                case 25: return [3, 27];
                case 26:
                    e_3 = _c.sent();
                    logger.error("checkPasswordExpiry 执行出错", e_3);
                    throw e_3;
                case 27: return [2];
            }
        });
    });
}
exports.checkPasswordExpiry = checkPasswordExpiry;
//# sourceMappingURL=checkPasswordExpiry.js.map