Blame view

apps/cart/models/cart-helper.js 24.1 KB
m  
刘传洋 authored
1 2 3 4 5
/**
 * Created by yoho on 2016-12-21.
 */
'use strict';
m  
刘传洋 authored
6 7 8
const _ = require('lodash');
const helpers = global.yoho.helpers;
const md5 = require('md5');
m  
刘传洋 authored
9
const logger = global.yoho.logger;
m  
刘传洋 authored
10 11

const PROMOTION_TYPE_TAG_MAP = {
yyq authored
12 13 14 15
    Cashreduce: '满减', // 满减
    Degressdiscount: '折扣', // 分件折扣
    Cheapestfree: '满减', // 满X免1
    Discount: '折扣', // 打折
m  
刘传洋 authored
16 17
    Gift: '赠品',
    Needpaygift: '加价购',
yyq authored
18
    SpecifiedAmount: '满减', // X件X元
m  
刘传洋 authored
19
    FreeShippingCost: '免运费',
周少峰 authored
20
    VipFreeShippingCost: '免运费',
周少峰 authored
21
    Payment: '折扣' // apple pay
m  
刘传洋 authored
22 23
};
m  
刘传洋 authored
24 25 26 27 28
const GOODS_TYPE_TAG_MAP = {
    gift: '赠品',
    price_gift: '加价购'
};
m  
刘传洋 authored
29 30 31 32 33 34 35 36
/**
 * 从用户加入购物车的COOKIE取出购物车凭证
 */
const getShoppingKeyByCookie = (req) => {

    return req.cookies._SPK || '';
};
m  
刘传洋 authored
37 38 39 40 41 42 43 44 45 46
/**
 * 转换价格
 *
 * @param float|string $price 价格
 * @return float|string 转换之后的价格
 */
const transPrice = (price) => {
    return price ? (price * 1).toFixed(2) : '0.00';
};
郝肖肖 authored
47
const identIconReplace = (ret) => {
48 49 50
    let repstr = '<span style=\'color:#ff575c\'>$&</span>';

    return ret && ret.replace(/¥/g, '¥').replace(/\d件/g, repstr).replace([.0-9]*元/g, repstr) || '';
m  
刘传洋 authored
51 52
};
m  
刘传洋 authored
53 54 55 56 57 58 59 60 61 62 63
/**
 * 生成公开的TOKEN凭证
 *
 * @param string $string 字符串
 * @return string
 */
const makeToken = (str) => {
    return md5(md5(str + '#@!@#'));
};

/**
m  
刘传洋 authored
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
 * cookie cart-del-list 的数据操作
 * @param req
 * @param res
 * @param addsStr 向删除列表中加入数据
 * @param delId 删除列表中移除某个 id 的产品
 */
const getCartDelList = (req, res, addsStr, delSkuId) => {

    let cartDelListStr = req.cookies['cart-del-list'] || '';
    let isMod = false;
    let cookieDelStr = '';

    try {
        let cartDelList = cartDelListStr ? JSON.parse(cartDelListStr) : [];
        let addList = addsStr ? JSON.parse(addsStr) : null;

        // 追加
        if (addList && addList.length && _.isArray(cartDelList)) {
            isMod = true;
            cartDelList = cartDelList.concat(addList);
        }

        if (delSkuId) {
            isMod = true;
            _.remove(cartDelList, it => {
                return Number(it.productSku) === Number(delSkuId);
            });
        }

        if (isMod) {

            if (cartDelList && cartDelList.length > 0) {
                cookieDelStr = JSON.stringify(cartDelList);
            }

            res.cookie('cart-del-list', cookieDelStr, {
                domain: '.yohobuy.com',
                path: '/'
            });
        }
        return cartDelList;
    } catch (err) {
        logger.error(err);
    }

    return null;
};

/**
m  
刘传洋 authored
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
 * 购物车商品
 * @param array cartGoods 购物车商品列表
 * @param bool isAdvanceCart 是否是预售购物车(和上市期有关)
 * @param bool inValid 是否是不可用商品(失效商品),默认不是(有效商品)
 * @param bool isOffShelves 是否卖光了, 默认否
 * @param array analysis 第三方数据分析用的
 * @return array 处理之后的购物车商品数据
 */
const formatCartGoods = (cartGoods, isAdvanceCart, inValid, isOffShelves, analysis) => {

    return _.map(cartGoods, (it) => {
        let goods = {
            id: it.product_sku,
            skn: it.product_skn,
            pid: it.product_id,
m  
刘传洋 authored
128
            brandId: it.brand_id,
m  
刘传洋 authored
129 130
            isChecked: it.selected === 'Y',
            productTitle: it.product_name,
OF1706 authored
131
            imgCover: it.goods_images ? helpers.image(it.goods_images, 64, 88) : '',
m  
刘传洋 authored
132 133
            productColor: it.factory_goods_name,
            productSize: it.size_name,
郝肖肖 authored
134
            productPrice: transPrice(it.sales_price),
m  
刘传洋 authored
135 136
            productNum: Number(it.buy_number),
            storageNum: Number(it.storage_number),
郝肖肖 authored
137
            isSoldOut: parseInt(it.storage_number, 10) === 0 || parseInt(it.off_shelves, 10) === 1, // 已售罄
138 139
            isVipPrice: it.discount_tag === 'V',
            isStuPrice: it.discount_tag === 'S',
OF1706 authored
140
            yohoIcon: Number(it.get_yoho_coin) || 0,
m  
刘传洋 authored
141 142
            productSubtotal: transPrice(it.last_vip_price * it.buy_number),
            promotionId: it.promotion_id || 0,
yyq authored
143
            isLimitSkn: it.is_limit_skn === 'Y', // is_limit_skn=Y 不支持7天无理由退货
m  
刘传洋 authored
144
            isAdvance: isAdvanceCart
m  
刘传洋 authored
145 146
        };
147
        // 划线的价格
148
        if (+it.last_vip_price < +it.sales_price) {
郝肖肖 authored
149 150
            goods.productPrice = transPrice(it.last_vip_price);
            goods.linePrice = transPrice(it.sales_price); // 划线的价格
151 152
        }
m  
刘传洋 authored
153
        if (it.min_buy_number) {
m  
刘传洋 authored
154
            goods.minBuyNumber = Number(it.min_buy_number);
m  
刘传洋 authored
155
m  
刘传洋 authored
156
            if (goods.minBuyNumber > 1) {
m  
刘传洋 authored
157 158
                goods.tipMessage = goods.minBuyNumber + '件起购';
            }
m  
刘传洋 authored
159 160
        }
m  
刘传洋 authored
161 162 163 164
        // 已下架
        if (isOffShelves) {
            goods.isTipNoStore = true;
            goods.tipMessage = '库存不足';
m  
刘传洋 authored
165
            goods.isOffShelve = true;
yyq authored
166
        } else if (!inValid) { // 有效
m  
刘传洋 authored
167
            if (goods.productNum > goods.storageNum) {
m  
刘传洋 authored
168 169
                goods.isTipNoStore = true; // 是否在结算时候显示库存不足
                goods.tipMessage = '库存不足';
OF1706 authored
170
            } else if (goods.storageNum <= 3) {
OF1706 authored
171
                goods.tipMessage = '仅剩' + goods.storageNum + '件';
m  
刘传洋 authored
172 173 174 175 176 177 178 179
            }
        } else { // 失效商品
            goods.inValid = true;
        }

        // advanceBuy=>是否加价购,soldOut=>失效商品;
        if (!it.goods_type) {
            goods.inValid = true;
yyq authored
180
        } else if (it.goods_type === 'gift') { // gift=>是否赠品    && it.isAdvanceBuy
m  
刘传洋 authored
181
            goods.isGift = true;
郝肖肖 authored
182 183
            goods.productPrice = transPrice(it.last_price);
            goods.linePrice = transPrice(it.sales_price); // 划线的价格
m  
刘传洋 authored
184 185 186
            goods.productSubtotal = it.subtotal ? transPrice(it.subtotal) : goods.productPrice;
        } else if (it.goods_type === 'price_gift') { // price_gift=>是否加价购
            goods.isPriceGift = true;
郝肖肖 authored
187 188
            goods.productPrice = transPrice(it.last_price);
            goods.linePrice = transPrice(it.sales_price); // 划线的价格
m  
刘传洋 authored
189
            goods.productSubtotal = it.subtotal ? transPrice(it.subtotal) : goods.productPrice;
yyq authored
190
        } else if (it.real_price === 0) { // 免单
郝肖肖 authored
191
            goods.productPrice = transPrice(it.sales_price);
m  
刘传洋 authored
192 193 194
            goods.xForOne = true;

            // 分析用: 商品ID列表
m  
刘传洋 authored
195
            if (_.isArray(_.get(analysis, 'ids'))) {
yyq authored
196
                analysis.ids.push(it.product_skn);
m  
刘传洋 authored
197
            }
m  
刘传洋 authored
198 199

            // 分析用: CRITEO
m  
刘传洋 authored
200 201 202 203 204 205 206
            if (_.isArray(_.get(analysis, 'criteo'))) {
                analysis.criteo.push({
                    id: it.product_skn,
                    quantity: Number(it.buy_number),
                    price: it.last_vip_price
                });
            }
m  
刘传洋 authored
207 208
        } else {
            // 分析用: 商品ID列表
m  
刘传洋 authored
209
            if (_.isArray(_.get(analysis, 'ids'))) {
周少峰 authored
210
                analysis.ids.push(it.product_skn);
m  
刘传洋 authored
211
            }
m  
刘传洋 authored
212 213

            // 分析用: CRITEO
m  
刘传洋 authored
214 215 216 217 218 219 220
            if (_.isArray(_.get(analysis, 'criteo'))) {
                analysis.criteo.push({
                    id: it.product_skn,
                    quantity: Number(it.buy_number),
                    price: it.last_vip_price
                });
            }
m  
刘传洋 authored
221 222
        }
m  
刘传洋 authored
223 224
        goods.tag = GOODS_TYPE_TAG_MAP[it.goods_type];
m  
刘传洋 authored
225 226 227 228 229 230 231 232 233
        // 商品类型:预售或普通
        goods.goodsType = isAdvanceCart ? 'advance' : 'ordinary';

        // 上市期
        if (isAdvanceCart && it.expect_arrival_time) {
            goods.preSellDate = it.expect_arrival_time;
        }

        // 商品链接
m  
OF1706 authored
234
        goods.link = helpers.getUrlBySkc(it.product_skn);
m  
刘传洋 authored
235 236 237 238 239 240 241 242 243

        return goods;
    });
};

/**
 * 购物车统计
 */
const formatShoppingCartData = (sc) => {
陈峰 authored
244 245 246
    if (!sc) {
        return {};
    }
m  
刘传洋 authored
247
    return {
yyq authored
248
        discountAmount: sc.discount_amount, // 活动价
m  
刘传洋 authored
249
        fastShoppingCost: sc.fast_shopping_cost,
yyq authored
250
        gainYohoCoin: sc.gain_yoho_coin, // 获赠有货币个数
m  
刘传洋 authored
251 252
        goodsCount: sc.goods_count,
        isMultiPackage: sc.is_multi_package,
yyq authored
253 254
        lastOrderAmount: (parseFloat(sc.last_order_amount)).toFixed(2), // 商品金额总计
        orderAmount: sc.order_amount, // 商品总价
m  
刘传洋 authored
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
        //  package_list,[],
        promotionFormula: sc.promotion_formula,
        promotionFormulaList: _.map(sc.promotion_formula_list, it => {
            return {
                promotion: it.promotion,
                promotionAmount: it.promotion_amount
            };
        }),
        selectedGoodsCount: sc.selected_goods_count,
        shippingCost: sc.shipping_cost,
        strDiscountAmount: sc.str_discount_amount,
        strOrderAmount: sc.str_order_amount
    };
};

/**
 * 全局优惠头部信息
 */
const formatPromotionInfos = (infoList) => {
    return _.map(infoList, it => {
        return {
            cutdownAmount: it.cutdown_amount,
            promotionId: it.promotion_id,
郝肖肖 authored
278
            promotionDesc: identIconReplace(it.promotion_title),
m  
刘传洋 authored
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
            promotionType: it.promotion_type,
            tag: PROMOTION_TYPE_TAG_MAP[it.promotion_type]
        };
    });
};

/**
 * 过时商品
 * offShelvesList 过时商品列表
 *
 */
const formatOffShelves = (offShelvesList, isAdvanceCart, analysis) => {
    return formatCartGoods(offShelvesList, isAdvanceCart, false, true, analysis);
};

/**
 * 售罄商品
 */
const formatSoldOuts = (soldOutsList, isAdvanceCart, analysis) => {
    return formatCartGoods(soldOutsList, isAdvanceCart, false, false, analysis);
};

/**
m  
刘传洋 authored
302
 * 格式化单个加价购商品
m  
刘传洋 authored
303
 */
m  
刘传洋 authored
304 305 306 307 308 309
const formatPriceGiftOne = (it) => {

    let gift = {
        // isShowGift: isGift, // 控制是否显示赠品
        // isFold: true, // 控制是否[展开]
        promotionId: it.promotion_id,
yyq authored
310
        promotionTitle: it.promotion_title,
郝肖肖 authored
311
        promotionDesc: identIconReplace(it.promotion_desc), // + '(注:您看到的商品可能因为下单时间差已售完)',  // subjoinType
m  
刘传洋 authored
312 313 314
        maxSelectNumber: it.max_select_number,
        promotionType: it.promotion_type,
        tag: PROMOTION_TYPE_TAG_MAP[it.promotion_type],
OF1706 authored
315 316
        isGift: it.promotion_type === 'Gift',
        isPriceGift: it.promotion_type === 'Needpaygift'
m  
刘传洋 authored
317
    };
m  
刘传洋 authored
318
m  
刘传洋 authored
319
    gift.goodsList = _.map(it.goods_list, (g) => {
m  
刘传洋 authored
320
m  
刘传洋 authored
321 322 323 324
        let goods = {
            id: g.product_id,
            skn: g.product_skn,
            subjoinTitle: g.product_name,
OF1706 authored
325
            imgCover: g.goods_images ? helpers.image(g.goods_images, 65, 90) : '',
m  
刘传洋 authored
326 327 328 329 330
            subjoinPrice: transPrice(g.last_price),
            marketPrice: gift.isGift ? '' : transPrice(g.market_price),
            yohoIcon: 0,
            isGift: gift.isGift,
            isPriceGift: gift.isPriceGift
m  
刘传洋 authored
331 332
        };
m  
刘传洋 authored
333 334
        // 商品链接
        if (g.goods_id) {
m  
OF1706 authored
335
            goods.subjoinLink = helpers.getUrlBySkc(g.product_skn);
m  
刘传洋 authored
336 337
        } else {
            let uri = `/product/show_${g.product_id}_${g.product_skn}/${makeToken(g.product_skn)}.html`;
m  
刘传洋 authored
338
m  
刘传洋 authored
339 340
            goods.subjoinLink = helpers.urlFormat(uri, null, 'item');
        }
m  
刘传洋 authored
341
m  
刘传洋 authored
342 343
        return goods;
    });
m  
刘传洋 authored
344
m  
刘传洋 authored
345 346
    return gift;
};
m  
刘传洋 authored
347
m  
刘传洋 authored
348 349 350 351 352
/**
 * 可选加价购
 * isGift 是否是赠品:true-赠品
 */
const formatPriceGifts = (giftList) => {
m  
刘传洋 authored
353
m  
刘传洋 authored
354 355
    return _.map(giftList, (it) => {
        return formatPriceGiftOne(it);
m  
刘传洋 authored
356 357 358 359 360 361
    });
};

/**
 * 购物车赠品
 */
m  
刘传洋 authored
362
/* const formatGifts = (giftList) => {
m  
刘传洋 authored
363 364
    return formatPriceGifts(giftList);
};*/
m  
刘传洋 authored
365
m  
刘传洋 authored
366
const checkGoodsIsSel = (goodsList, promotionId, selectedGiftsList) => {
m  
刘传洋 authored
367 368 369

    return _.map(goodsList, goods => {
m  
刘传洋 authored
370
        _.forEach((selectedGiftsList || []), gift => {
m  
刘传洋 authored
371
m  
刘传洋 authored
372
            if (goods.id === gift.id && promotionId === gift.promotionId) {
m  
刘传洋 authored
373 374 375 376 377 378 379 380 381 382 383
                goods.isCheckedGift = true;
                goods.checkedGiftPid = gift.pid;
                goods.checkedGiftSkn = gift.skn;
                return;
            }
        });

        return goods;
    });
};
m  
刘传洋 authored
384
/**
m  
刘传洋 authored
385
 * 格式化promotion 里的数据
m  
刘传洋 authored
386
 */
m  
刘传洋 authored
387 388
const formatPromotion = (it, selectedGiftsList) => {
389
    // "status": 0, // 状态 0 未满足 10 已满足 [20 售光 30 更换 ]
390
    let status = parseInt(it.status, 10);
391
    let tsPromotionIds = (it.ts_promotion_ids && it.ts_promotion_ids.join(',')) || it.promotion_id || '';
m  
刘传洋 authored
392 393
    let info = {
        status: status,
yyq authored
394
        conditionUnit: it.condition_unit, // 0满足,1 件,2金额
m  
刘传洋 authored
395
        conditionValue: it.condition_value,
yyq authored
396 397
        giftPrice: it.gift_price, // 赠品或加价购商品价格
        giftGoodsList: formatCartGoods(it.gift_goods_List), // 可供选择的赠品或加价购商品列表
398
        promotionId: tsPromotionIds, // 促销id
郝肖肖 authored
399
        promotionDesc: identIconReplace(it.promotion_desc),
yyq authored
400
        promotionType: it.promotion_type, // 促销类型
m  
刘传洋 authored
401
        // list.yohobuy.com?psp_id=10408
yyq authored
402
        promotionPageUrl: helpers.urlFormat('/list', {psp_id: tsPromotionIds}),
m  
刘传洋 authored
403 404 405 406
        tag: PROMOTION_TYPE_TAG_MAP[it.promotion_type],

        isGift: it.promotion_type === 'Gift',
        isPriceGift: it.promotion_type === 'Needpaygift',
yyq authored
407 408 409 410
        isNotReach: status === 0, // 未满足
        isReach: status === 10 || status === 30 || status === 20, // 满足条件
        isEmpty: status === 20, // 已售完
        isSelected: status === 30 // 已选择,可更换
m  
刘传洋 authored
411
    };
m  
刘传洋 authored
412
m  
刘传洋 authored
413 414
    // 判断赠品/加价购商品,是否被选中
    info.giftGoodsList = checkGoodsIsSel(info.giftGoodsList, info.promotionId, selectedGiftsList);
m  
刘传洋 authored
415
m  
刘传洋 authored
416 417 418
    if (info.giftGoodsList) {
        info.giftGoodsListStr = JSON.stringify(info.giftGoodsList);
    }
419
m  
刘传洋 authored
420 421
    return info;
};
m  
刘传洋 authored
422
m  
刘传洋 authored
423 424 425 426
/**
 * 优惠池头部优惠信息列表
 */
const formatPoolPromotionInfos = (infoList, selectedGiftsList) => {
m  
刘传洋 authored
427
m  
刘传洋 authored
428 429
    return _.map(infoList, it => {
        return formatPromotion(it, selectedGiftsList);
m  
刘传洋 authored
430 431 432 433 434 435
    });
};

/**
 * 格式化子优惠池信息,返回商品列表,子优惠列表放在每个商品中
 */
yyq authored
436
const formatSubPromotionPools = (pools, selectedGiftsList, isAdvance, analysis) => {
m  
刘传洋 authored
437 438 439

    let goodsListPool = _.map(pools, p => {
        let pool = {
m  
刘传洋 authored
440
            poolType: p.pool_type,
m  
刘传洋 authored
441
            isBrandGroup: Number(p.pool_type) === 1,
yyq authored
442
            goodsList: formatCartGoods(p.goods_list, isAdvance, false, false, analysis),
m  
刘传洋 authored
443
            promotionInfos: formatPoolPromotionInfos(p.promotion_list, selectedGiftsList)
m  
刘传洋 authored
444 445 446 447 448
        };

        let goodsList = pool.goodsList;

        if (goodsList && goodsList.length) {
m  
刘传洋 authored
449
            pool.goodsList = _.map(goodsList, g => {
m  
刘传洋 authored
450 451 452 453 454
                g.promotionInfos = pool.promotionInfos;
                return g;
            });
        }
m  
刘传洋 authored
455
        return pool;
m  
刘传洋 authored
456 457 458
    });

    // [ [goods, goods], [goods, ..], [] ] => [goods, goods ]
m  
刘传洋 authored
459 460 461
    // return _.flatten(goodsListPool);

    return goodsListPool;
m  
刘传洋 authored
462 463
};
郝肖肖 authored
464 465 466 467 468 469 470
const _disablePools = (goodsList, isCheck, isBtnDisab) => {
    return _.map(goodsList, p => {

        return Object.assign(p, {isCheck: isCheck, isBtnDisab: isBtnDisab});
    });
};
m  
刘传洋 authored
471
/**
m  
刘传洋 authored
472
 * giftsList, priceGifts 已选择的赠品和加价购,判断可选的赠品和加价购是否被选中
m  
刘传洋 authored
473 474
 * 优惠池
 */
yyq authored
475
const formatPromotionPools = (pools, selectedGiftsList, isAdvance, analysis) => {
m  
刘传洋 authored
476
    return _.map(pools, p => {
郝肖肖 authored
477
        p.pool_type = parseInt(p.pool_type, 10);
m  
刘传洋 authored
478 479

        let pool = {
郝肖肖 authored
480
            poolId: p.pool_id,
m  
刘传洋 authored
481
            poolTitle: p.pool_title,
郝肖肖 authored
482
            isChecked: p.selected === 'Y',
483 484 485
            batchNo: p.pool_batch_no,
            productNum: parseInt(p.pool_buy_number, 10),
            storageNum: parseInt(p.pool_storage_number, 10),
m  
刘传洋 authored
486
            poolType: p.pool_type,
郝肖肖 authored
487
            isBrandGroup: p.pool_type === 1,
yyq authored
488
            goodsList: formatCartGoods(p.goods_list, isAdvance, false, false, analysis),
m  
刘传洋 authored
489
            promotionInfos: formatPoolPromotionInfos(p.promotion_list, selectedGiftsList)
m  
刘传洋 authored
490 491
        };
m  
刘传洋 authored
492
        if (p.sub_pool) {
yyq authored
493
            pool.subs = formatSubPromotionPools(p.sub_pool, selectedGiftsList, isAdvance, analysis);
m  
刘传洋 authored
494
m  
刘传洋 authored
495
            /*
m  
刘传洋 authored
496 497
            if (_.isArray(goodsWithPromotion) && goodsWithPromotion.length) {
                pool.goodsList = goodsWithPromotion.concat(pool.goodsList);
m  
刘传洋 authored
498
            }*/
m  
刘传洋 authored
499 500
        }
郝肖肖 authored
501 502 503 504 505 506
        // 套餐不须要列表中有删除、收藏按钮
        if (p.pool_type === 3) {
            pool.goodsList = _disablePools(pool.goodsList, true, true);
            pool.minBuyNumber = 1;
        }
m  
刘传洋 authored
507 508 509
        return pool;
    });
};
郝肖肖 authored
510
郝肖肖 authored
511 512 513 514 515 516 517 518 519
// 失效处理
const formatSoldOutPools = (pools, selectedGiftsList, isAdvance, analysis) => {
    return _.map(pools, p => {
        p.pool_type = parseInt(p.pool_type, 10);

        let pool = {
            poolId: p.pool_id,
            poolTitle: p.pool_title,
            isChecked: p.selected === 'Y',
520 521 522
            batchNo: p.pool_batch_no,
            productNum: parseInt(p.pool_buy_number, 10),
            storageNum: parseInt(p.pool_storage_number, 10),
郝肖肖 authored
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
            poolType: p.pool_type,
            isBrandGroup: p.pool_type === 1,
            goodsList: formatCartGoods(p.goods_list, isAdvance, true, false, analysis),
            promotionInfos: formatPoolPromotionInfos(p.promotion_list, selectedGiftsList)
        };

        // 套餐不须要列表中有删除、收藏按钮
        if (p.pool_type === 3) {
            pool.goodsList = _disablePools(pool.goodsList, true, true);
            pool.minBuyNumber = 1;
            pool.inValid = true;
        }

        return pool;
    });
};
m  
刘传洋 authored
539
m  
刘传洋 authored
540 541 542 543 544
const formatCart = (cartDataRet, uid, shoppingKey, cartDelList) => {

    let analysisData = {
        ids: [],
        criteo: []
yyq authored
545
    }; // 存放分析用的数据
m  
刘传洋 authored
546 547 548 549

    let result = {
        isEmpty: false,
        isLogin: !!uid,
yyq authored
550
        searchUrl: helpers.urlFormat('', null, 'search'), // 搜索链接(再逛逛)
yyq authored
551
        listUrl: helpers.urlFormat('/list'),
m  
刘传洋 authored
552 553 554 555 556 557 558 559
        viewOrderUrl: helpers.urlFormat('/home/orders', {
            t: new Date().getTime()
        })
    };

    // 未登录
    if (!uid) {
        result.loginUrl = helpers.urlFormat('/signin.html', {
m  
刘传洋 authored
560
            refer: helpers.urlFormat('/cart/cart')
m  
刘传洋 authored
561 562 563 564 565 566 567 568 569
        });
    }

    // 调用接口,获取购物车数据
    // let cartDataRet = yield cartApi.cartData(uid, shoppingKey);
    let cartData = cartDataRet && cartDataRet.data;
    let advCartData = _.get(cartData, 'advance_cart_data');
    let ordCartData = _.get(cartData, 'ordinary_cart_data');
m  
刘传洋 authored
570 571 572
    // 移除的商品列表
    result.deleteShop = cartDelList;
m  
刘传洋 authored
573 574 575 576 577 578 579 580
    // 接口异常时,购物车置为空
    if (!cartData) {
        result.isEmpty = true;

        // UdpLog::info('【购物车】校验参数传递auth', 'uid:' . $uid . 'shoppingKey:' . $shoppingKey);
        return result;
    }
yyq authored
581 582 583 584

    // 预售购物车,普通购物车 凑单链接
    result.moreGoodsLink = '//list.yohobuy.com/new';
m  
刘传洋 authored
585 586 587
    result.advanceCart = {
        // 未参加活动的商品
        // goodsList: chelper.formatCartGoods(_.get(advCartData, 'goods_list'), true, false, false, analysisData),
yyq authored
588
        pools: formatPromotionPools(_.get(advCartData, 'goods_pool_list'), null, true, analysisData),
m  
刘传洋 authored
589 590 591 592
        offShelves: formatOffShelves(_.get(advCartData, 'off_shelves_goods_list'), true, analysisData),
        soldOuts: formatSoldOuts(_.get(advCartData, 'sold_out_goods_list'), true, analysisData),
        promotionInfos: formatPromotionInfos(_.get(advCartData, 'promotion_info')),
        stat: formatShoppingCartData(_.get(advCartData, 'shopping_cart_data')),
yyq authored
593 594
        isShippingCostFree: _.get(advCartData, 'shipping_cost_prompt.is_shipping_cost_free', '') === 'Y',
        tips: _.get(advCartData, 'shipping_cost_prompt.shipping_cost_tips', ''),
m  
刘传洋 authored
595 596 597 598 599
        ensureUrl: helpers.urlFormat('/cart/ensure', {
            type: 2
        })
    };
m  
刘传洋 authored
600 601
    // let giftsList = formatPriceGifts(_.get(ordCartData, 'gift_list'));
    // let priceGifts = formatPriceGifts(_.get(ordCartData, 'price_gift'));
m  
刘传洋 authored
602 603 604 605
    let goodsList = formatCartGoods(_.get(ordCartData, 'goods_list'), false, false, false, analysisData);

    result.ordinaryCart = {
        // 全场可选的赠品
m  
刘传洋 authored
606
        // gifts: giftsList,   // chelper.formatGifts(_.get(ordCartData, 'gift_list')),
m  
刘传洋 authored
607
        // 全场可选的加价购商品列表
m  
刘传洋 authored
608 609 610
        // priceGifts: priceGifts, // chelper.formatPriceGifts(_.get(ordCartData, 'price_gift')),
        giftsPromotionInfos: formatPoolPromotionInfos(_.get(ordCartData, 'g_gift_list')),
        priceGiftsPromotionInfos: formatPoolPromotionInfos(_.get(ordCartData, 'g_price_gift_list')),
m  
刘传洋 authored
611
m  
刘传洋 authored
612 613 614
        // 已选择的全场加价购和赠品
        goodsList: goodsList,
yyq authored
615
        pools: formatPromotionPools(_.get(ordCartData, 'goods_pool_list'), goodsList, false, analysisData),
m  
刘传洋 authored
616 617 618

        offShelves: formatOffShelves(_.get(ordCartData, 'off_shelves_goods_list'), false, analysisData),
        soldOuts: formatSoldOuts(_.get(ordCartData, 'sold_out_goods_list'), false, analysisData),
郝肖肖 authored
619
        soldOutPools: formatSoldOutPools(_.get(ordCartData, 'sold_out_goods_pool'), goodsList, false, analysisData),
m  
刘传洋 authored
620 621 622

        promotionInfos: formatPromotionInfos(_.get(ordCartData, 'promotion_info'), goodsList),
        stat: formatShoppingCartData(_.get(ordCartData, 'shopping_cart_data')),
周少峰 authored
623 624 625
        ensureUrl: helpers.urlFormat('/cart/ensure'),

        // 免运费提示
yyq authored
626
        isShippingCostFree: _.get(ordCartData, 'shipping_cost_prompt.is_shipping_cost_free', '') === 'Y',
627 628 629 630
        tips: _.get(ordCartData, 'shipping_cost_prompt.shipping_cost_tips', ''),

        // 低档赠品
        matchGiftIds: _.get(ordCartData, 'match_gift_ids', []).join(',')
m  
刘传洋 authored
631 632 633 634 635 636 637 638 639 640 641 642 643 644
    };

    let advStat = result.advanceCart.stat;
    let ordStat = result.ordinaryCart.stat;

    // 为空
    if (!_.get(advStat, 'goodsCount', 0)) {
        result.advanceCart = false;
    }

    if (!_.get(ordStat, 'goodsCount', 0)) {
        result.ordinaryCart = false;
    }
m  
刘传洋 authored
645
    if (!result.advanceCart && !result.ordinaryCart) {
m  
刘传洋 authored
646
        result.isEmpty = true;
m  
刘传洋 authored
647 648 649 650 651
        return result;
    }

    if (_.get(result, 'ordinaryCart.promotionInfos')) {
        result.ordinaryCart.promotionInfos = _.filter(result.ordinaryCart.promotionInfos, pinfo => {
m  
刘传洋 authored
652
            return pinfo && pinfo.tag && Number(pinfo.promotionId) === 0;
m  
刘传洋 authored
653
        });
m  
刘传洋 authored
654 655
    }
m  
刘传洋 authored
656
    // promotionInfos,  gifts, priceGifts 放一起展示
周少峰 authored
657 658 659 660
    let hasGifts = _.get(result, 'ordinaryCart.giftsPromotionInfos') &&
        _.get(result, 'ordinaryCart.giftsPromotionInfos').length;
    let hasPrices = _.get(result, 'ordinaryCart.priceGiftsPromotionInfos') &&
        _.get(result, 'ordinaryCart.priceGiftsPromotionInfos').length;
m  
刘传洋 authored
661
    let hasPromo = _.get(result, 'ordinaryCart.promotionInfos') && _.get(result, 'ordinaryCart.promotionInfos').length;
OF1706 authored
662 663 664 665
    let orderAmount = (parseFloat(_.get(advStat, 'orderAmount', 0)) +
    parseFloat(_.get(ordStat, 'orderAmount', 0))).toFixed(2);
    let lastOrderAmount = (parseFloat(_.get(advStat, 'lastOrderAmount', 0)) +
    parseFloat(_.get(ordStat, 'lastOrderAmount', 0))).toFixed(2);
m  
刘传洋 authored
666 667 668 669 670

    if (result.ordinaryCart) {
        result.ordinaryCart.hasGlobalBlock = hasGifts || hasPrices || hasPromo;
    }
    result.stat = {
OF1706 authored
671
        orderAmount: orderAmount,
OF1706 authored
672
        lastOrderAmount: lastOrderAmount,
OF1706 authored
673
        discountAmount: (orderAmount - lastOrderAmount).toFixed(2),
m  
刘传洋 authored
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
        gainYohoCoin: parseFloat(_.get(advStat, 'gainYohoCoin', 0)) + parseFloat(_.get(ordStat, 'gainYohoCoin', 0)),
        goodsCount: _.get(advStat, 'goodsCount', 0) + _.get(ordStat, 'goodsCount', 0),
        selectedGoodsCount: _.get(advStat, 'selectedGoodsCount', 0) + _.get(ordStat, 'selectedGoodsCount', 0)
    };

    // 普通购物车和预售购物车都为空
    /* if (ordinaryCount === 0 && advanceCount === 0 && ordinarySoldOut && advanceSoldOut) {
     result.isEmpty = true;
     return result;
     }*/

    // 预售和普通都有商品
    if (result.advanceCart && _.get(result, 'advanceCart.stat.selectedGoodsCount') > 0 &&
        result.ordinaryCart && _.get(result, 'ordinaryCart.stat.selectedGoodsCount') > 0) {
        result.stat.mix = true;
    } else if (result.advanceCart && _.get(result, 'advanceCart.stat.selectedGoodsCount') > 0) {
        result.stat.ensureUrl = result.advanceCart.ensureUrl;
    } else if (result.ordinaryCart && _.get(result, 'ordinaryCart.stat.selectedGoodsCount') > 0) {
        result.stat.ensureUrl = result.ordinaryCart.ensureUrl;
    }

    Object.assign(result, {
        ids: _.isArray(analysisData.ids) ? analysisData.ids.join(',') : '',
        criteo: analysisData.criteo || ''
    });

    return result;
};
m  
刘传洋 authored
703
module.exports = {
m  
刘传洋 authored
704 705 706
    transPrice,
    getShoppingKeyByCookie,
    formatCartGoods,
m  
刘传洋 authored
707
m  
刘传洋 authored
708 709
    // formatGifts,
    formatPriceGiftOne,
m  
刘传洋 authored
710 711
    formatPriceGifts,
    formatShoppingCartData,
m  
刘传洋 authored
712
    formatPromotion,
m  
刘传洋 authored
713 714 715
    formatPromotionPools,
    formatPromotionInfos,
    formatOffShelves,
m  
刘传洋 authored
716
    formatSoldOuts,
m  
刘传洋 authored
717 718 719
    formatCart,

    getCartDelList
m  
刘传洋 authored
720
};