coupon.js 7.01 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);

        if (!data.length) {
            return res.json({
                code: 201,
                result: false,
                message: '文件内容为空'
            });
        }

        try {
            // 通用券只允许导入一条数据
            let coupon = await req.ctx(CouponModel).couponById(id);

            if (coupon[0].type === 3) {
                return res.json({
                    code: 204,
                    result: false,
                    message: '无码券不允许导入数据'
                });
            }
            if (coupon[0].type === 1) {
                if (data.length > 1) {
                    return res.json({
                        code: 202,
                        result: false,
                        message: '通用券只允许导入一条数据'
                    });
                }
                let count = await req.ctx(CouponModel).couponNoCid(id);

                if (count[0].count) {
                    return res.json({
                        code: 203,
                        result: false,
                        message: '通用券已有数据'
                    });
                }

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

                await req.ctx(CouponModel).couponNoAdd(param);
            }
            return res.json({
                code: 200,
                result: true,
                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;
        const status = req.query.status;

        let totalCount = await req.ctx(CouponModel).allCouponNum(status);

        totalCount = totalCount[0].total;
        let list = await req.ctx(CouponModel).couponList({pageNo, pageSize, status});

        _.each(list, item => {
            item.createTime = timeFormat(item.createTime);
        });

        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;
        }
    },
    downloadTpl(req, res) {
        let conf = {
            name: 'mysheet',
            cols: [
                {
                    caption: 'couponNo',
                    type: 'String'
                }
            ],
            rows: [['c3236233105'], ['c3236233105']]
        };
        let exportFile = excelExport.execute(conf);

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

    },
    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);
                    if (item.createTime) {
                        temp.push(timeFormat(item.createTime));
                    } else {
                        temp.push('');
                    }
                    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);

    },
    deleteCoupon: async function(req, res) {
        let id = req.query.id;

        // 查询有没有用户表里有没,如有返回不给删
        let userData = await req.ctx(CouponModel).couponUserListByCId(id);

        if (userData.length) {
            return res.json({
                code: 201,
                result: false,
                message: '删除失败,有用户数据'
            });
        }

        // 查询查no表里并且删除
        await req.ctx(CouponModel).deleteCouponNoByCId(id);

        // 删除主表
        await req.ctx(CouponModel).deleteCouponById(id);

        return res.json({
            code: 200,
            result: true,
            message: DO_SUCCESS
        });
    }

};

module.exports = couponController;