coupon.js 4.44 KB
/**
 * 优惠券管理controller
 * @author: leo <y.huang@yoho.cn>
 * @date: 08/08/2018
 */

const _ = require('lodash');
const CouponModel = require('../models/coupon');
const moment = require('moment');
const excelExport = require('excel-export');
const INVALID_PARAMS = '参数错误';


const xlsx = require('xlsx');
const DO_SUCCESS = '操作成功';
const GET_SUCCESS = '获取成功';

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));
};

const timeFormat = (time) => {
    if (_.isNumber(time)) {
        time = moment.unix(time);
    }

    return moment(time).format('YYYY-MM-DD HH:mm:ss');
};

const couponController = {
    async loadCouponNoList(req, res, next) {
        let file = req.files.up_excel;
        let id = req.body.id;

        let data = await loadExcel(file.path);

        // let arr = [];
        //
        // for (let item of data) {
        //     let rowArr = [id];
        //
        //     rowArr.push(item.couponNo);
        //     arr.push(rowArr);
        // }

        try {
            for (let item of data) {
                let param = {couponId: id, couponNo: item.couponNo};

                await req.ctx(CouponModel).couponNoAdd(param);
            }
            return res.json({
                code: 200,
                message: DO_SUCCESS
            });
        } catch (e) {
            next;
        }
    },
    couponListPage(req, res) {
        res.render('coupon/list', {
            bodyClass: 'nav-md',
            module: 'admin',
            page: 'coupon'
        });
    },

    async couponOptionPage(req, res) {
        let result = await req.ctx(CouponModel).couponById(req.query.id);

        if (result instanceof Array) {
            result = result[0];
        }
        res.render('coupon/coupon-option', {
            bodyClass: 'nav-md',
            module: 'admin',
            content: result,
            page: 'coupon-option'
        });
    },
    async couponList(req, res) {
        const pageNo = req.query.pageNo || 1;
        const pageSize = req.query.pageSize || 20;

        let totalCount = await req.ctx(CouponModel).allCouponNum();
        let list = await req.ctx(CouponModel).couponList({pageNo, pageSize});

        res.json({
            code: 200,
            data: list,
            pageNo: +pageNo,
            pageSize: +pageSize,
            totalCount,
            totalPage: Math.ceil(totalCount / pageSize),
            message: GET_SUCCESS
        });

    },
    async modifyCoupon(req, res, next) {
        try {
            await req.ctx(CouponModel).couponModify(req.body);
            res.json({
                code: 200,
                message: DO_SUCCESS
            });
        } catch (e) {
            next;
        }
    },
    downloadNoList(req, res, next) {
        const couponId = req.query.id;

        if (!couponId) {
            return res.json({
                code: 400,
                message: INVALID_PARAMS
            });
        }

        let conf = {
            name: 'mysheet',
            cols: [
                {
                    caption: '券ID',
                    type: 'number'
                },
                {
                    caption: '券码',
                    type: 'string'
                },
                {
                    caption: '用户id',
                    type: 'number'
                },
                {
                    caption: '创建时间',
                    type: 'string'
                }
            ],
            rows: []
        };

        req.ctx(CouponModel).couponNoListJoinUser(couponId)
            .then(result => {
                let temp = [];

                _.each(result, item => {
                    temp = [];
                    temp.push(couponId);
                    temp.push(item.couponNo);
                    temp.push(item.userId);
                    temp.push(timeFormat(item.createTime));
                    conf.rows.push(temp);
                });

                let exportFile = excelExport.execute(conf);

                res.setHeader('Content-Type', 'application/vnd.openxmlformats');
                res.setHeader('Content-Disposition', 'attachment; filename=couponList.xlsx');
                res.end(exportFile, 'binary');
            })
            .catch(next);

    },

};

module.exports = couponController;