buy-now-controller.js 10.3 KB
/*
 * @Author: Targaryen
 * @Date: 2017-06-21 10:15:38
 * @Last Modified by: Targaryen
 * @Last Modified time: 2017-06-26 16:21:29
 */
const _ = require('lodash');
const co = require('bluebird').coroutine;
const headerModel = require('../../../doraemon/models/header');
const BuyNowModel = require('../models/buy-now-model');
const addressModel = require('../models/address');
const userModel = require('../models/user');
const orderModel = require('../models/order');
const utils = '../../../utils';
const paymentProcess = require(`${utils}/payment-process`);
const crypto = global.yoho.crypto;
const logger = global.yoho.logger;
const helpers = global.yoho.helpers;

// cookie 参数
const actCkOpthn = {
    path: '/cart/index'
};

class BuyNowController {
    /**
     * 确认订单页面
     * @param {*} req
     * @param {*} res
     * @param {*} next
     */
    orderEnsure(req, res, next) {
        let orderInfo;

        try {
            orderInfo = JSON.parse(req.cookies.buynow_info);
        } catch (e) {
            logger.info(`orderEnsure: get buynow-order-info from cookie error:${JSON.stringify(e)}`);
            orderInfo = {};
            res.clearCookie('buynow_info', actCkOpthn);
        }

        let product_sku = req.query.product_sku;
        let buy_number = req.query.buy_number;

        if (!product_sku || !buy_number) {
            return next();
        }

        co(function * () {
            let result = yield req.ctx(BuyNowModel).payment({
                uid: req.user.uid,
                product_sku: product_sku,
                sku_type: req.query.sku_type,
                buy_number: buy_number,
            });
            let computeData = yield req.ctx(BuyNowModel).compute({
                uid: req.user.uid,
                product_sku: product_sku,
                sku_type: req.query.sku_type,
                buy_number: buy_number,
                use_yoho_coin: parseInt(orderInfo.use_yoho_coin, 10)
            });
            let validCouponCount = yield req.ctx(BuyNowModel).countUsableCoupon({
                uid: req.user.uid,
                product_sku: req.query.product_sku,
                sku_type: req.query.sku_type,
                buy_number: buy_number
            });
            let headerData = headerModel.setNav({
                navTitle: '确认订单',
                navBtn: false
            });

            return res.render('buynow/order-ensure', {
                pageHeader: headerData,
                module: 'buynow',
                page: 'order-ensure',
                title: '确认订单',
                width750: true,
                localCss: true,
                product_sku: product_sku,
                orderEnsure: _.assign(
                    paymentProcess.tranformPayment(result.data, orderInfo, null, null, computeData.data),
                    {
                        coupon: paymentProcess.coupon(_.get(validCouponCount, 'data.count', 0), orderInfo, computeData),
                        selectAddressUrl: helpers.urlFormat('/cart/index/buynow/selectAddress', {
                            product_sku: product_sku,
                            buy_number: buy_number
                        }),
                        isOrdinaryCart: true
                    }
                )
            });

        })().catch(next);
    }

    /**
     * 参数更改,重新运算结算数据
     * @param {*} req
     * @param {*} res
     * @param {*} next
     */
    orderCompute(req, res, next) {
        co(function * () {
            let result = yield req.ctx(BuyNowModel).compute({
                uid: req.user.uid,
                cart_type: req.body.cart_type,
                delivery_way: req.body.delivery_way,
                payment_type: req.body.payment_type,
                product_sku: req.body.product_sku,
                buy_number: req.body.buy_number,
                coupon_code: req.body.coupon_code,
                use_yoho_coin: req.body.use_yoho_coin,
            });

            result.data.use_yoho_coin = paymentProcess.transPrice(result.data.use_yoho_coin);
            result.data.yohoCoinCompute = paymentProcess.yohoCoinCompute(result.data);
            return res.json(result.data);
        })().catch(next);
    }

    /**
     * 提交订单
     * @param {*} req
     * @param {*} res
     * @param {*} next
     */
    orderSub(req, res, next) {
        let params = {
            uid: req.user.uid,
            product_sku: req.body.product_sku,
            sku_type: req.body.sku_type,
            buy_number: req.body.buy_number,
            address_id: parseInt(crypto.decrypt('', req.body.address_id), 10),
            delivery_time: req.body.delivery_time,
            delivery_way: req.body.delivery_way,
            use_yoho_coin: req.body.use_yoho_coin,
            use_red_envelopes: req.body.use_red_envelopes,
            payment_id: req.body.payment_id,
            payment_type: req.body.payment_type,
            product_sku_list: req.body.product_sku_list,
            is_print_price: req.body.is_print_price,
            remark: req.body.remark,
            activity_id: req.body.activity_id
        };

        // 是否开发票
        if (req.body.invoice) {
            params.invoices_type = req.body.invoices_type; // 发票类型:纸质 1,电子 2
            params.invoices_title = req.body.invoices_title || '个人'; // 发票抬头,个人前端不传此值
            params.receiverMobile = req.body.receiverMobile; // 接收人电话

            // 购买方纳税人识别号
            if (req.body.buyerTaxNumber) {
                params.buyerTaxNumber = req.body.buyerTaxNumber;
            }
        }

        co(function * () {
            let result = yield req.ctx(BuyNowModel).submit(params);

            // 提交成功清除Cookie
            res.clearCookie('buynow_info', actCkOpthn);

            return res.json(result);
        })().catch(next);
    }

    /**
     * 选择地址
     * @param {*} req
     * @param {*} res
     * @param {*} next
     */
    selectAddress(req, res, next) {
        let uid = req.user.uid;
        let product_sku = req.query.product_sku;
        let buy_number = req.query.buy_number;

        co(function * () {
            let address = yield addressModel.addressData(uid);
            let moreUrl = helpers.urlFormat('/cart/index/buynow/orderensure', {
                product_sku: product_sku,
                buy_number: buy_number
            });

            address = address.data;

            let headerData = headerModel.setNav({
                navTitle: '选择地址',
                navBtn: false,
                backUrl: moreUrl
            });

            res.render('select-address', {
                module: 'buynow',
                page: 'select-address',
                pageHeader: headerData,
                pageFooter: true,
                moreUrl,
                address,
                localCss: true
            });
        })().catch(next);
    }

    /**
     * 填写发票信息
     * @param {*} req
     * @param {*} res
     * @param {*} next
     */
    selectInvoice(req, res, next) {
        let product_sku = req.query.product_sku;
        let buy_number = req.query.buy_number;
        let uid = req.user.uid;
        let orderInfo;

        try {
            orderInfo = JSON.parse(req.cookies.buynow_info);
        } catch (e) {
            orderInfo = {};
        }

        co(function* () {
            let userData = yield userModel.queryProfile(uid);
            let mobile = _.get(userData, 'data.mobile', '');
            let addresslist = yield userModel.addressTextData(uid);
            let returnData = orderModel.processInvoiceData(orderInfo, mobile, addresslist);
            let headerData = headerModel.setNav({
                invoiceNotice: '发票须知',
                navTitle: '发票信息',
                navBtn: false
            });

            res.render('select-invoice', _.assign(returnData, {
                pageHeader: headerData,
                module: 'buynow',
                page: 'select-invoice',
                localCss: true,
                addressMore: helpers.urlFormat('/cart/index/buynow/orderensure', {
                    product_sku: product_sku,
                    buy_number: buy_number
                })
            }));
        })().catch(next);
    }

    /**
     * 选择优惠券页面
     */
    selectCoupon(req, res) {
        let headerData = headerModel.setNav({
            navTitle: '选择优惠券',
            navBtn: false
        });

        res.render('select-coupon', {
            module: 'buynow',
            page: 'select-coupon',
            title: '选择优惠券',
            selectCouponPage: true,
            pageHeader: headerData,
            pageFooter: true,
            localCss: true
        });
    }

    /**
     * 获取用户可用和不可用优惠券列表
     * @param {*} req
     * @param {*} res
     * @param {*} next
     */
    listCoupon(req, res, next) {
        co(function* () {
            let result = yield req.ctx(BuyNowModel).listCoupon({
                uid: req.user.uid,
                product_sku: req.query.product_sku,
                sku_type: req.query.sku_type,
                buy_number: req.query.buy_number
            });

            res.json(result);
        })().catch(next);
    }

    /**
     * 使用优惠券
     * @param {*} req
     * @param {*} res
     * @param {*} next
     */
    useCoupon(req, res, next) {
        co(function* () {
            let result = yield req.ctx(BuyNowModel).useCoupon({
                uid: req.user.uid,
                product_sku: req.body.product_sku,
                sku_type: req.body.sku_type,
                buy_number: req.body.buy_number,
                coupon_code: req.body.coupon_code
            });

            res.json(result);
        })().catch(next);
    }

    /**
     * 输入优惠券码使用优惠券
     */
    usePromotionCode(req, res, next) {
        co(function* () {
            let result = yield req.ctx(BuyNowModel).usePromotionCode({
                uid: req.user.uid,
                product_sku: req.body.product_sku,
                sku_type: req.body.sku_type,
                buy_number: req.body.buy_number,
                promotion_code: req.body.promotion_code
            });

            res.json(result);
        })().catch(next);
    }
}

module.exports = new BuyNowController();