coupon.js 6.29 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 INVALID_PARAMS = '参数错误';
const xlsx = require('xlsx');
const DO_SUCCESS = '操作成功';
const GET_SUCCESS = '获取成功';
const {excel_export} = require('../../../utils/excel');

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 = {
    loadCouponNoList: async function(req, res, next) {
        let file = req.files.up_excel;
        let id = req.body.id;

        res.setTimeout(1000 * 60 * 3 + 1000);

        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: '通用券已有数据'
                    });
                }

            }

            await req.ctx(CouponModel).couponNoAdd({couponId: id, couponNos: data});
            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) {
        return excel_export({
            title: ['couponNo'],
            data: [['c3236233105'], ['c3236233105']],
            fileName: 'couponNoTpl',
            sheetName: '优惠券',
            res
        });
    },
    downloadNoList(req, res, next) {
        const couponId = req.query.id;

        res.setTimeout(1000 * 60 * 3 + 1000);

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

        let conf = {
            name: 'mysheet',
            cols: ['券ID', '券码', '用户id', '领取时间'],
            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);
                });
                return excel_export({
                    title: conf.cols,
                    data: conf.rows,
                    fileName: 'couponList',
                    sheetName: conf.name,
                    res
                });
            })
            .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;