excel.js 9.17 KB
/**
 * Created by qiujun on 2018/1/9.
 */

const _ = require('lodash');
const xlsx = require('xlsx');
const mail = require('nodemailer');
const moment = require('moment');
const smtpTransport = require('nodemailer-smtp-transport');
const depart_names = ['活动', '技术', '零售', '媒体', '品牌', '上游资源', '市场会员', '运维', '战略发展'];
const ActivityModel = require('../../admin/models/activity');

let loadExcel = function(path) {
    let workbook = xlsx.readFile(path);
    const sheetNames = workbook.SheetNames;
    const worksheet = workbook.Sheets[sheetNames[0]];

    return Promise.resolve(xlsx.utils.sheet_to_json(worksheet));
};

let createY100Data = async function(req, res, next, actId, data, index) {

    if (index < data.length) {
        let item = data[index];
        let name = item.name;
        let content = '';
        let createTime = moment().format('YYYY-MM-DD hh:mm:ss');

        item.skns_1 = (item.skns_1 || '').replace(/ /g, '').replace(/\r/g, '').replace(/\n/g, '');
        item.skns_2 = (item.skns_2 || '').replace(/ /g, '').replace(/\r/g, '').replace(/\n/g, '');

        let skns = (item.skns_1 || '') + '||' + (item.skns_2 || '');
        let career = item.career || '';
        let interest = item.interest || '';
        let style = item.style;
        let tag = item.tag || '';
        let desc = item.desc || '';
        let top = item.top || 0;
        let head_url = item.head_url || '';
        let img_url = item.img_url || '';

        const articleId = await req.ctx(ActivityModel).createArticle({actId, name, content, createTime});
        const numRes = await req.ctx(ActivityModel).getY100ArticleNums(actId);
        const total_count = numRes[0].total_count;
        const y100ArticleId = await req.ctx(ActivityModel).createY100Article(actId, articleId, head_url, img_url, total_count + 1, name,
            tag, style, career, interest, skns, desc, top, createTime);

        if (y100ArticleId) {
            createY100Data(req, res, next, actId, data, index + 1);
        }
    } else {
        res.json({
            code: 200,
            data: data,
            message: '插入完成' + index + '条'
        });
    }
};

let deleteY100Data = async function(req, res, next, actId) {
    const result = await req.ctx(ActivityModel).deleteAllY100Articles(actId);

    return res.json({
        result
    });
};

const excelLoader = {
    /**
     * 年会用来读取人员名单的
     * @param req
     * @param res
     * @param next
     * @returns {Promise.<T>|*}
     */
    excelToXml(req, res, next) {
        return loadExcel('public/docs/users2019.xlsx').then(ret => {
            let results = [[], [], [], [], [], [], [], [], []];

            _.each(ret, item => {
                let depart_1 = item.block; // 第一级部门

                for (let i = 0; i < depart_names.length; i++) { // 按部门归入相应的数组
                    if (depart_1.indexOf(depart_names[i]) >= 0) {
                        results[i].push(item);
                    }
                }
            });

            let xml_result = '<?xml version="1.0" encoding="UTF-8"?>\n' +
                '<root>\n' +
                '\t<data>\n';

            _.each(results, item_arr => {
              console.log(item_arr.length);
                let xml_dep_f = '\t\t<department depid="0" name="' + item_arr[0].block +
                    '" total="' + item_arr.length + '" prizes="0">\n';
                let xml_person = '';

                _.each(item_arr, item => {
                    let xml_person_f = '\t\t\t<person>\n';
                    let xml_person_e = '\t\t\t</person>\n';
                    let depart_arr = [];

                    if (item.block) {
                        depart_arr.push(item.block);
                    }
                    if (item.center) {
                        depart_arr.push(item.center);
                    }
                    if (item.depart) {
                        depart_arr.push(item.depart.replace(/\d/g, ''));
                    }
                    if (item.depart_4) {
                        depart_arr.push(item.depart_4);
                    }

                    let xml_person_content = '\t\t\t\t<id>' + item.id + '</id>\n' +
                        '\t\t\t\t<name>' + item.name + '</name>\n' +
                        '\t\t\t\t<depart>' + depart_arr.join('-') + '</depart>\n' +
                        '\t\t\t\t<address>' + item.address + '</address>\n' +
                        '\t\t\t\t<code>' + item.code + '</code>\n' +
                        '\t\t\t\t<job>' + item.job + '</job>\n' +
                        '\t\t\t\t<phone>' + item.phone + '</phone>\n' +
                        '\t\t\t\t<email>' + item.email + '</email>\n' +
                        '\t\t\t\t<level>0</level>\n';

                    xml_person += xml_person_f + xml_person_content + xml_person_e;
                });

                let xml_dep_e = '\t\t</department>\n';

                xml_result += xml_dep_f + xml_person + xml_dep_e;
            });

            res.send(xml_result + '\t</data>\n</root>');


        }).catch(next);
    },
    getExcelData(req, res) {
        console.log(req);
        return loadExcel('public/docs/users2019.xlsx').then(ret => {
            res.json(ret);
        });
    },

    /**
     * 直接读取并插入Y100数据
     * @param req
     * @param res
     * @param next
     */
    getY100Data(req, res, next) {
        let {actId = 23, paths = 'public/docs/y100.xlsx'} = req.query;

        return loadExcel(paths).then(ret => {
            createY100Data(req, res, next, actId, ret, 0);
        });
    },

    /**
     * 读取EXCEL插入数据
     * @param req
     * @param res
     * @param next
     */
    getY100ExcelFile(req, res, next) {
        console.log(req.body, req.files);
        let file = req.files.up_excel;
        let actId = req.body.actId || 23;

        return loadExcel(file.path).then(ret => { // 删除所有数据之后,插入新的数据
            req.ctx(ActivityModel).deleteAllY100Articles(actId).then(() => {
                createY100Data(req, res, next, actId, ret, 0);
            });

        });
    },

    /**
     * 删除Y100数据
     * @param req
     * @param res
     * @param next
     * @returns {Promise}
     */
    deleteY100Data(req, res, next) {
        const {actId = 23} = req.query;

        return deleteY100Data(req, res, next, actId);
    },

    /**
     * 年会根据名单发送邮件
     * @param req
     * @param res
     * @param next
     * @returns {Promise.<T>|*}
     */
    sendMail(req, res, next) {
        return loadExcel('public/docs/youku.xlsx').then(ret => {
            // console.log(ret);
            let send_user = 'jun.qiu@yoho.cn';
            let send_pass = 'Robertqj1982';
            let sended_arr = [];
            let transporter = mail.createTransport(smtpTransport({
                service: 'QQex', // 此处对应的服务器列表https://github.com/nodemailer/nodemailer-wellknown/blob/master/services.json
                secure: true,
                secureConnection: true,
                port: 465,
                auth: {
                    user: send_user,
                    pass: send_pass
                }
            }));

            let send_mail = function(index, data) {
                if (index < data.length && data[index]) {
                    let mailOptions = {
                        from: send_user,
                        to: data[index].email || '8413750@qq.com',
                        subject: 'YOHO 2018 阳光普照奖品',
                        html: '<p>优酷会员1个月充值卡,帐号密码:</p>' +
                        '<p>' + data[index].account + '</p>' +
                        '<p>' + data[index].password + '</p>' +
                        '<p>注:奖品过期时间为2018年12月19日,如果您不需要此奖品,可以将奖品还给行政部张伟(w.zhang@yoho.cn)</p>' +
                        '<p>使用方法:1.进入优酷并登录自己的帐号 2.点自己的头像进入个人中心-我的-我的会员-会员卡 3.输入邮件中会员卡的密码即可</p>' +
                        '<p>感谢每一位同事一年来的辛勤劳动!</p>'
                    };

                    console.log('正在发送第' + (index + 1) + '个:' + mailOptions.to);

                    transporter.sendMail(mailOptions, function(error, info) {
                        sended_arr.push(mailOptions.to);
                        if (error) {
                            return res.json({
                                message: '出错:' + error,
                                data: [mailOptions],
                                sended: sended_arr
                            });
                        }
                        console.log('发送成功!:' + info.response);
                        index += 1;
                        setTimeout(send_mail, 3000, index, data);
                    });
                } else {
                    res.json({
                        message: '所有邮件发送成功!'
                    });
                }
            };

            if (ret.length > 0) {
                send_mail(0, ret);
            }
        }).catch(next);
    }
};

module.exports = excelLoader;