order.js 13.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
'use strict';
const _ = require('lodash');
const helpers = global.yoho.helpers;
const co = require('bluebird').coroutine;
const cartModel = require('../models/cart');
const headerModel = require('../../../doraemon/models/header');
const userModel = require('../models/user');
const addressModel = require('../models/address');
const orderModel = require('../models/order');
const crypto = global.yoho.crypto;
const authcode = require(global.utils + '/authcode');
const logger = global.yoho.logger;

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

exports.orderEnsure = (req, res, next) => {
    let headerData = headerModel.setNav({
        navTitle: '确认订单',
        navBtn: false
    });

    let uid = req.user.uid;
    let returnUrl = helpers.urlFormat('/cart/index/index');
    let cartType = req.query.cartType;
    let orderInfo;

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

    if (!cartType) {
        cartType = _.get(orderInfo, 'cartType', 'ordinary');
    }

    // 如果传递了code, skn, sku, buy_number 就代表限购商品
    let limitProductCode = req.query.limitproductcode || '';
    let sku = req.query.sku || '';
    let skn = req.query.skn || '';
    let buyNumber = req.query.buy_number || 1;

    if (limitProductCode) {
        headerData.backUrl = req.get('Referer') || returnUrl;
    } else {
        headerData.backUrl = returnUrl;
    }

    let orderPromise;

    if (req.query.cartType === 'bundle') {
        if (!req.cookies._cartType) {
            res.cookie('_cartType', 'bundle', actCkOpthn);
        }
        let activityInfo = JSON.parse(req.cookies['activity-info']);

        orderPromise = cartModel.cartPay(uid, cartType, orderInfo, null, sku, skn, buyNumber, activityInfo);
    } else {
        orderPromise = cartModel.cartPay(uid, cartType, orderInfo, sku, skn, buyNumber);
    }

    let allPromise = [
        orderPromise,
        userModel.queryProfile(uid),
        addressModel.addressData(uid)
    ];

    if (_.isUndefined(req.cookies._isNewUser)) {
        allPromise.push(orderModel.isNewUser(uid));
    }

    return Promise.all(allPromise).then(result => {
        let order = result[0];
        let userProfile = result[1];
        let address = result[2];
        let isNewUser = result[3];

        if (!_.isUndefined(isNewUser)) {
            if (isNewUser) {
                res.cookie('_isNewUser', true, actCkOpthn);
            } else {
                res.cookie('_isNewUser', false, actCkOpthn);
            }
        }

        if (order.cartUrl) {
            logger.info(`orderEnsure: order cartUrl has value:${order.cartUrl}, order data is null`);
            return res.redirect(order.cartUrl);
        }

        if (req.xhr) {
            logger.info(`orderEnsure: ajax request, return json:${JSON.stringify(order)}`);
            return res.json(order);
        }

        // 获取用户完整手机号
        let mobile = _.get(userProfile, 'data.mobile', '');
        let orderAddress = _.get(order, 'address', []);
        let addressList = _.get(address, 'data', []);

        orderAddress.length && _.forEach(addressList, address => { //eslint-disable-line
            if (address.address_id === orderAddress.address_id) {
                mobile = address.mobile;
                return false;
            }
        });

        let viewData = {
            orderEnsurePage: true,
            isOrdinaryCart: cartType !== 'advance',
            orderEnsure: _.assign(order, {
                isOrdinaryCart: cartType !== 'advance'
            }),
            userMobile: mobile,
            pageHeader: headerData,
            pageFooter: false,
            module: 'cart',
            page: 'order-ensure',
            width750: true,
            title: '确认订单',
            localCss: true
        };

        res.render('order-ensure', viewData);
    }).catch(next);
};

/**
 * 购物车选择改变字段,重新运算订单数据
 */
exports.orderCompute = (req, res, next) => {
    let cartType = req.body.cartType || 'ordinary';
    let deliveryId = req.body.deliveryId || 1;
    let paymentType = req.body.paymentType || 1;
    let couponCode = req.body.couponCode || null;
    let yohoCoin = req.body.yohoCoin || null;
    let productSku = req.body.productSku || null;
    let buyNumber = req.body.buyNumber || null;
    let uid = req.user.uid;
    let skuList = req.body.skuList;
    let type = req.body.type;

    if (type !== 'tickets') {
        if (req.body.cartType === 'bundle') {
            let activityInfo = JSON.parse(req.cookies['activity-info']);

            cartModel.orderCompute(uid, cartType, deliveryId, paymentType,
                couponCode, yohoCoin, null, activityInfo).then(result => {
                    res.json(result);
                }).catch(next);
        } else {
            cartModel.orderCompute(uid, cartType, deliveryId, paymentType,
                couponCode, yohoCoin, skuList).then(result => {
                    res.json(result);
                }).catch(next);
        }
    } else {
        cartModel.ticketsOrderCompute(uid, productSku, buyNumber, yohoCoin).then(result => {
            res.json(result);
        }).catch(next);
    }
};

/**
 * 确认结算订单
 */
exports.orderSub = (req, res, next) => {
    let uid = req.user.uid;
    let addressId = parseInt(crypto.decrypt('', req.body.addressId), 10);
    let cartType = req.body.cartType || 'ordinary';
    let deliveryTimeId = req.body.deliveryTimeId || 1;
    let deliveryId = req.body.deliveryId || 1;
    let paymentTypeId = req.body.paymentTypeId || 15;
    let paymentType = req.body.paymentType || 1;
    let msg = req.body.msg || null;
    let couponCode = req.body.couponCode || null;
    let yohoCoin = req.body.yohoCoin || 0;
    let skuList = req.body.skuList || '';
    let orderInfo;

    try {
        orderInfo = JSON.parse(req.cookies['order-info']);
    } catch (e) {
        orderInfo = {};
        res.cookie('order-info', null, actCkOpthn);
    }

    let times = req.body.times || 1;

    // 电子发票信息数组
    let invoices = {};

    if (orderInfo) {
        invoices = {
            invoices_type_id: orderInfo.invoiceType,
            invoices_type: orderInfo.invoicesType,
            receiverMobile: orderInfo.receiverMobile,
            invoices_title: orderInfo.invoiceText ? orderInfo.invoiceText : '个人'
        };
    }

    /* 判断是否是友盟过来的用户 */
    let userAgent = null;
    let unionKey = '';
    let unionInfo = {};
    let clientId = null;

    if (req.cookies.mkt_code || req.cookies._QYH_UNION) {
        /* tar modified 161108 添加新的联盟数据处理逻辑,兼容原有联盟数据处理,
                    区别是旧的北京写 cookie 加密过来,新的 node 写 cookie,没有加密 */
        if (req.cookies._QYH_UNION) {
            unionKey = authcode(req.cookies._QYH_UNION, 'q_union_yohobuy');

            if (!unionKey) {
                let encryData = crypto.decrypt('', decodeURIComponent(req.cookies._QYH_UNION));

                encryData = encryData.substr(0, encryData.lastIndexOf('}') + 1);
                let testQyhUnion = JSON.parse(encryData);

                unionKey = testQyhUnion.client_id ? encryData : '';
            }

            try {
                unionInfo = JSON.parse(unionKey);
            } catch (e) {
                unionInfo = {};
                logger.error(`orderEnsure: _QYH_UNION:${req.cookies._QYH_UNION}`);
            }

            clientId = unionInfo && unionInfo.client_id;
        } else {
            let unionObj = {
                client_id: req.cookies.mkt_code
            };

            if (req.cookies.union_data) {
                unionObj.union_data = req.cookies.union_data;
            }

            unionKey = JSON.stringify(unionObj);
            clientId = req.cookies.mkt_code;
        }

        /* 模拟APP的User-Agent */
        userAgent = clientId ? 'YOHO!Buy/3.8.2.259(Model/PC;Channel/' +
            clientId + ';uid/' + uid + ')' : null;
    }

    return co(function* () {
        let result;

        // 接口需要的其他参数
        let otherParams = {
            unionKey: unionKey, // 友盟数据
            userAgent: userAgent,
            isWechat: req.yoho.isWechat,
            ip: req.ip || '',
            udid: req.cookies._yasvd || 'yoho'
        };

        /* tar modified 161206 套餐 */
        if (req.body.cartType === 'bundle') {
            let activityInfo = JSON.parse(req.cookies['activity-info']);

            result = yield cartModel.orderSub(uid, addressId, 'bundle', deliveryTimeId,
                deliveryId, invoices, paymentTypeId, paymentType, msg, couponCode,
                yohoCoin, null, times, activityInfo, otherParams);
        } else {
            result = yield cartModel.orderSub(uid, addressId, cartType, deliveryTimeId,
                deliveryId, invoices, paymentTypeId, paymentType, msg, couponCode,
                yohoCoin, skuList, null, null, otherParams);
        }

        // 提交成功清除Cookie
        orderInfo = {};
        res.cookie('order-info', null, actCkOpthn);

        if (result.code === 409) {
            return res.json(decodeURI(result));
        } else {
            return res.json(result);
        }
    })().catch(next);
};

/**
 *  下单流程 选择优惠券
 */
exports.selectCoupon = (req, res) => {

    let headerData = headerModel.setNav({
        navTitle: '选择优惠券',
        navBtn: false
    });

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

/**
 * 购物车结算--获取优惠券列表
 */
exports.couponList = (req, res, next) => {
    let uid = req.user.uid;

    if (req.xhr) {
        return cartModel.getCouponList(uid)
            .then(data => {
                res.json(data);
            }).catch(next);
    } else {
        return next();
    }

};

/**
 * 购物车输入优惠券码使用优惠券
 */
exports.couponSearch = (req, res, next) => {
    let couponCode = req.body.couponCode || '';
    let uid = req.user.uid;

    co(function* () {
        if (req.xhr) {
            let result = yield cartModel.searchCoupon(uid, couponCode);

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

    })().catch(next);
};

/**
 * 选择地址
 */
exports.selectAddress = (req, res, next) => {
    let uid = req.user.uid;

    return addressModel.addressData(uid).then(address => {

        let moreUrl = (req.get('Referer') && !/\/home\/addressAct/.test(req.get('Referer')) &&
            !/selectAddress/.test(req.get('Referer'))) ?
            req.get('Referer') : ''; // 取跳过来的url

        address = address.data;

        // 购物车订单进来,秒杀进来
        if (
            moreUrl.indexOf('/cart/index/new/orderEnsure') !== -1 ||
            moreUrl.indexOf('/cart/index/seckill') !== -1
        ) {
            req.session.addressMore = moreUrl; // TODO: 注意cookie-session
        }

        moreUrl = req.session.addressMore || moreUrl || helpers.urlFormat('/cart/index/new/orderEnsure', {
            cartType: req.cookies._cartType
        });

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

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

/**
 * 发票信息
 */
exports.invoiceInfo = (req, res, next) => {
    let uid = req.user.uid;
    let orderInfo;

    try {
        orderInfo = JSON.parse(req.cookies['order-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({
            navTitle: '发票信息',
            navBtn: false
        });

        res.render('select-invoice', _.assign(returnData, {
            pageHeader: headerData,
            module: 'cart',
            page: 'select-invoice',
            localCss: true,
            addressMore: helpers.urlFormat('/cart/index/new/orderEnsure', {cartType: req.cookies._cartType})
        }));
    })().catch(next);
};

/**
 * JIT 拆单配送信息页面
 */
exports.jitDetail = (req, res, next) => {
    let cartType = req.query.cartType;
    let headerData = headerModel.setNav({
        navTitle: '配送信息',
        navBtn: false
    });

    cartModel.jitDetailData(
        req.user.uid,
        cartType,
        req.query.skuList,
        req.query.orderCode,
        req.session.TOKEN,
        req.query.deliveryId,
        req.query.paymentType,
        req.query.couponCode,
        req.query.yohoCoin
    ).then(result => {
        if (cartType) {
            _.assign(headerData, {
                backUrl: result.returnUrl
            });
        }

        res.render('jit-detail', _.assign(result, {
            pageHeader: headerData,
            jitDetailPage: true,
            module: 'cart',
            page: 'jit-detail',
        }));
    }).catch(next);
};