payment-process.js 14.1 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 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
'use strict';
const helpers = global.yoho.helpers;
const crypto = global.yoho.crypto;
const _ = require('lodash');
const logger = global.yoho.logger;
const authcode = require('./authcode');

/**
 * 转换价格
 *
 * @param float|string $price 价格
 * @param boolean $isSepcialZero 是否需要特殊的0,默认否
 * @return float|string 转换之后的价格
 */
function transPrice(price, isSepcialZero) {
    if (!price) {
        price = 0;
    }

    if (!isSepcialZero) {
        isSepcialZero = false;
    }

    if ((price || isSepcialZero) && _.isNumber(price)) {
        return price.toFixed(2);
    } else {
        return price;
    }
}

/**
 * 有货币使用前端方案显示及是否可单击判断
 */
function yohoCoinCompute(orderCompute) {
    let yohoCoinData = {
        totalYohoCoinNum: (orderCompute.total_yoho_coin_num || 0) * 1,
        yohoCoin: (orderCompute.yoho_coin || 0) * 1,
        useYohoCoin: (orderCompute.use_yoho_coin || 0) * 1,
        yohoCoinClick: 0,
        yohoCoinMsg: '',
        yoho_coin_pay_rule: orderCompute.yoho_coin_pay_rule || {}
    };

    if (!orderCompute) {
        return yohoCoinData;
    }

    if (yohoCoinData.yohoCoin > 0) {
        yohoCoinData.yohoCoin = yohoCoinData.yohoCoin.toFixed(2);
    }

    if (yohoCoinData.useYohoCoin > 0) {
        yohoCoinData.useYohoCoin = yohoCoinData.useYohoCoin.toFixed(2);
    }

    if (yohoCoinData.totalYohoCoinNum < 100) {
        yohoCoinData.yohoCoinMsg = `共${yohoCoinData.totalYohoCoinNum}有货币,满${
            _.get(orderCompute, 'yoho_coin_pay_rule.num_limit', '100')}可用`;
    } else if (yohoCoinData.useYohoCoin > 0 || yohoCoinData.yohoCoin > 0) {
        yohoCoinData.yohoCoinMsg = '可抵¥' + (yohoCoinData.useYohoCoin > 0 ?
            yohoCoinData.useYohoCoin : yohoCoinData.yohoCoin);
        yohoCoinData.yohoCoinClick = 1;
    } else {
        yohoCoinData.yohoCoinMsg = '不满足有货币使用条件';
    }

    return yohoCoinData;
}

/**
 * 转换 原始结算数据 ,适应模板
 * TODO: 其他结算,如果有 相似的 结构,可以移出去
 * @param data 结算页面数据
 * @param orderInfo
 *    orderInfo.paymentType 用户支付常用方式
 * @param cartType
 * @param skuList
 * @param orderComputeData [option]  app.shopping.compute 返回的data数据
 *
 * TODO:
 *     与秒杀结算 一起测试
 */
function tranformPayment(data, orderInfo, cartType, skuList, orderComputeData) {
    orderInfo = orderInfo || {};
    let result = {};
    let isSunfengSupport;

    // orderComputeData 覆盖 data中对应的值
    if (orderComputeData && !_.isEmpty(orderComputeData)) {
        _.assign(data, orderComputeData);
        _.set(data, 'shopping_cart_data.promotion_formula_list', orderComputeData.promotion_formula_list);
        _.set(data, 'shopping_cart_data.last_order_amount', orderComputeData.last_order_amount);
        _.set(data, 'delivery_way', orderComputeData.delivery_way);
    }

    // delivery_address 中 提取信息
    if (data.hasOwnProperty('delivery_address') && !_.isEmpty(data.delivery_address)) {
        let cookieAddress = orderInfo.address;
        let addressData = data.delivery_address;
        let isSupport = cookieAddress ? cookieAddress.is_support : addressData.is_support;

        result.name = cookieAddress ? cookieAddress.consignee : addressData.consignee;
        result.phoneNum = cookieAddress ? cookieAddress.mobile : addressData.mobile;
        result.addressId = cookieAddress ?
            parseInt(crypto.decrypt(null, cookieAddress.address_id), 10) : addressData.address_id;
        result.addressInfo = cookieAddress ?
            cookieAddress.address_info : [addressData.area, addressData.address].join(' ');

        result.addressId = crypto.encryption(null, result.addressId + '');
        isSunfengSupport = isSupport === 'Y';

    }

    // delivery_way 配送信息
    if (data.delivery_way) {
        let arr = [];
        let cookieWayId = orderInfo.deliveryId;
        let deliveryWay = data.delivery_way;
        let isDeliveryId = true;
        let defaultKey = 0;

        deliveryWay.forEach((way, index) => {
            if (way.delivery_way_name === '顺丰速运' && !isSunfengSupport) {
                return;
            }

            let obj = {};

            (way.default === 'Y') && (defaultKey = index);

            if (cookieWayId && (way.delivery_way_id === cookieWayId)) {
                obj.isSelected = true;
                isDeliveryId = false;
            }

            arr.push(
                Object.assign({
                    id: way.delivery_way_id,
                    name: way.delivery_way_name,
                    cost: way.delivery_way_cost,
                }, obj)
            );
        });

        if (isDeliveryId) {
            arr[defaultKey].isSelected = true;
        }

        result.dispatchMode = arr;
    }

    // delivery_time 配送时间
    if (data.delivery_time) {
        let cookieTimeId = orderInfo.deliveryTimeId;
        let defaultKey = 0;
        let times = data.delivery_time;

        times = times.map((time, index) => {
            (time.default === 'Y') && (defaultKey = index);

            return {
                isSelected: false,
                id: time.delivery_time_id,
                name: time.delivery_time_string
            };
        });

        times[defaultKey].isSelected = true;

        if (cookieTimeId) {
            let selectTime = times.find(time => time.id === cookieTimeId);

            if (selectTime) {
                times[defaultKey].isSelected = false;
                selectTime.isSelected = true;
            }
        }

        result.dispatchTime = times;
    }

    // goods_list 订单商品
    if (data.goods_list) {
        let goods = data.goods_list;
        let goodsPrice = 0;

        goods = goods.map(good => {
            var obj = {};

            obj.id = good.product_sku;
            obj.thumb = helpers.image(good.goods_images, 120, 160);
            obj.name = good.product_name;
            obj.color = good.color_name;
            obj.size = good.size_name;
            obj.count = good.buy_number;
            obj.price = good.sales_price;
            obj.isLimitSkn = good.is_limit_skn === 'Y';
            obj.notSevenExchange = _.get(good, 'tags[0]', '');

            if (good.goods_type === 'gift') {
                obj.gift = true;
                obj.price = good.is_advance === 'Y' ? good.sale_price : good.last_price;
            } else if (good.goods_type === 'price_gift') { // eslint-disable-line
                obj.advanceBuy = true;
                obj.price = good.last_price;
            }

            // Total Price
            goodsPrice += obj.count * obj.price;

            return obj;
        });

        result.goods = goods;
        result.goodsPrice = goodsPrice.toFixed(2);
    }

    // 支付方式
    if (data.payment_way) {
        let payway = data.payment_way;

        payway = payway.filter(obj => obj.is_support === 'Y')
            .map(way => {
                let obj = {};

                obj.id = way.payment_id;
                obj.paymentType = way.payment_type;
                obj.name = way.payment_type_name;
                obj.isSupport = way.is_support === 'Y';
                obj.isSupportMessage = way.payment_type === 2 ? _.get(way, 'is_support_message', false) : false;

                return obj;
            });

        payway.some(way => {
            let bool = way.paymentType === orderInfo.paymentType;

            if (bool) {
                way.recommend = true;
            }

            return bool;
        }) || (payway[0].recommend = true);

        result.paymentWay = payway;
    }

    // 发票
    if (data.invoices) {
        let invTypes = data.invoices.invoiceContentList || [];

        invTypes = invTypes.map(type => {
            return {
                id: type.invoices_type_id,
                name: type.invoices_type_name
            };
        });

        result.invoice = invTypes;

        if (orderInfo.invoice) {
            result.needInvoice = orderInfo.invoice;

            if (orderInfo.invoices_title) {
                if (orderInfo.invoices_title.length > 10) {
                    orderInfo.invoices_title = orderInfo.invoices_title.substring(0, 10) + '...';
                }

                result.invoiceText = `电子发票(${orderInfo.invoices_title})`;
            } else {
                result.invoiceText = orderInfo.invoices_title_personal ?
                    `电子发票(${orderInfo.invoices_title_personal})` : '电子发票(个人)';
            }
        }
    }

    // 订单数据
    if (data.shopping_cart_data) {
        let cartData = data.shopping_cart_data;

        // 判断 是否为jit商品
        if (cartData.is_multi_package === 'Y') {
            result.isJit = true;

            let jitInfo = {};

            if (orderInfo) {
                jitInfo = {
                    deliveryId: orderInfo.deliveryId,
                    paymentType: orderInfo.paymentType,
                    couponCode: orderInfo.couponCode,
                    yohoCoin: orderInfo.yohoCoin
                };
            }

            let param = Object.assign({
                cartType: cartType,
                skuList: skuList
            }, jitInfo);

            if (_.get(orderInfo, 'product_sku', '')) {
                result.jitDetailUrl = helpers.urlFormat('/cart/index/new/jitDetail', {
                    buynow: 'Y',
                    product_sku: _.get(orderInfo, 'product_sku', '')
                });
            } else {
                result.jitDetailUrl = helpers.urlFormat('/cart/index/new/jitDetail', param);
            }

            result.packageTitle = cartData.package_title;
        }

        result.cartPayData = cartData.promotion_formula_list;
        result.num = cartData.goods_count;
        result.goodsPrice = cartData.str_order_amount;
        result.price = orderComputeData && _.isNumber(orderComputeData.last_order_amount) ?
            orderComputeData.last_order_amount : cartData.last_order_amount;

        if (cartData.gain_yoho_coin > 0) {
            result.yohoCoinNum = cartData.gain_yoho_coin;
            result.returnYohoCoin = true;
        }

    }

    // 有货币
    result.yohoCoinCompute = yohoCoinCompute(data);

    // 留言
    orderInfo.msg && (result.msg = orderInfo.msg);
    result.isPrintPrice = true; // 是否不打印价格,默认不勾选,预留

    return result;
}

/**
 *  优惠券数据
 *  @param count int 用户有效优惠券
 *  @param orderComputeData obj app.Shopping.compute返回的data数据
 *  @param orderInfo cookie中的数据
 *  @return obj
 */
function coupon(count, orderInfo, orderComputeData) {
    let coupons = {
        count: count,
        selectedAmount: 0,
        info: ''
    };

    let couponAmount = _.get(orderComputeData, 'coupon_amount', false);

    if (_.get(orderInfo, 'usable_usual_code', null)) {
        coupons.selectedAmount++;
    }

    if (_.get(orderInfo, 'usable_free_code', null)) {
        coupons.selectedAmount++;
    }

    if (count) {
        if (coupons.selectedAmount) {
            coupons.info = `-${couponAmount.toFixed(2)}`;
        } else {
            coupons.info = '未使用';
        }
    } else {
        coupons.info = '无可用';
    }

    return coupons;
}

/**
 * JIT 拆单数据处理
 */
function transformJit(packageList) {
    let result = {
        packages: []
    };

    _.forEach(packageList, (pValue, pKey) => {
        result.packages[pKey] = {
            packageType: (pKey + 1) + ':' + pValue.title
        };

        _.forEach(pValue.goods_list, (gValue, gKey) => {
            result.packages[pKey].goods = [];
            result.packages[pKey].goods[gKey] = {
                thumb: gValue.goods_images
            };

            switch (gValue.goods_type) {
                case 'price_gift' :
                    // 加价购
                    result.packages[pKey].goods[gKey].isAdd = true;
                    break;
                case 'gift' :
                    // 赠品
                    result.packages[pKey].goods[gKey].isGift = true;
                    break;
                default:
                    break;
            }
        });

        if (pValue.shopping_cost !== '0.00') {
            result.packages[pKey].expressCost = pValue.shopping_cost;
        }
        if (pValue.shopping_cut_cost !== '0.00') {
            result.packages[pKey].discount = pValue.shopping_cut_cost;
        }
    });

    return result;
}

/**
 * 联盟相关
 * @param {*} cookies
 * @param {*} uid
 */
function unionInfoHandle(cookies, uid) {
    /* 判断是否是友盟过来的用户 */
    let userAgent = null;
    let unionKey = '';
    let unionInfo = {};
    let clientId = null;

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

        if (!unionKey) {
            let encryData = crypto.decrypt('', decodeURIComponent(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:${cookies._QYH_UNION}`);
        }

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

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

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

    /* 模拟APP的User-Agent */
    let clientIdSub = _.split(clientId, ',')[0];

    userAgent = clientIdSub ? 'YOHO!Buy/3.8.2.259(Model/H5;Channel/' +
        clientIdSub + ';uid/' + uid + ')' : null;

    return {
        unionKey: unionKey,
        userAgent: userAgent
    };
}

module.exports = {
    transPrice,
    tranformPayment,
    yohoCoinCompute,
    coupon,
    transformJit,
    unionInfoHandle
};