Blame view

utils/cart-process.js 16.2 KB
陈峰 authored
1 2 3 4 5 6 7 8
/**
 * 购物车处理类
 */

'use strict';

const helpers = global.yoho.helpers;
const _ = require('lodash');
9
const productProcess = require('./product-process');
陈峰 authored
10
lijing authored
11
// const regPromoTitle = /^【[^】]+】(.*)/;
陈峰 authored
12
陈峰 authored
13
const transPrice = (price, isSepcialZero) => {
陈峰 authored
14
    return (price > 0 || isSepcialZero) ? parseFloat(price).toFixed(2) : 0;
陈峰 authored
15
};
陈峰 authored
16
lijing authored
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
// const formatPromotionTitle = (promo) => {
//     let title;

//     if (promo.status === 0) {
//         if (promo.condition_unit === 1) {
//             title = `再购${Math.abs(promo.condition_value)}件`;
//         } else if (promo.condition_unit === 2) {
//             title = `再购¥${transPrice(Math.abs(promo.condition_value))}`;
//         }
//     } else {
//         title = '已满足';
//     }
//     let match = regPromoTitle.exec(promo.promotion_title);
//     let promotionTitle = match !== null && match.length > 1 ? match[1] : promo.promotion_title;

//     promotionTitle = promotionTitle.replace(/¥/g, '¥');
//     return `${title}【${promotionTitle}】`;
// };
陈峰 authored
35
const formatPromotionOpt = (promo) => {
陈峰 authored
36 37 38 39 40 41 42 43 44 45
    if (promo.status === 0) {
        return '去凑单';
    }
    if (promo.status === 10) {
        if (promo.promotion_type === 'Needpaygift') {
            return '去换购';
        }
        if (promo.promotion_type === 'Gift') {
            return '领赠品';
        }
陈峰 authored
46
        return '';
陈峰 authored
47 48 49 50 51 52 53
    }
    if (promo.status === 20) {
        return '已抢光';
    }
    if (promo.status === 30) {
        return '更换';
    }
陈峰 authored
54 55
};
陈峰 authored
56 57 58 59 60 61 62
/**
 * 格式化加价购和赠品商品
 *
 * @param array $advanceGoods 加价购商品列表
 * @param int $count 计商品件数
 * @return array $arr 处理之后的加价购商品数据
 */
陈峰 authored
63 64 65 66 67 68 69 70 71 72 73
const formatAdvanceGoods = (gifts, isGift) => {
    return _.map(gifts, gift => {
        return {
            promotionId: gift.promotion_id,
            promotionTitle: gift.promotion_title,
            isGift: isGift,
            goods: _.map(gift.goods_list, good => {
                return {
                    id: good.product_skn,
                    name: good.product_name,
                    thumb: good.goods_images ? helpers.image(good.goods_images, 120, 160) : '',
74 75
                    price: isGift ? '0.00' : transPrice(good.last_price),
                    salesPrice: good.last_price !== good.sales_price ? transPrice(good.sales_price) : false,
陈峰 authored
76 77 78 79 80
                    count: good.storage_number
                };
            })
        };
    });
陈峰 authored
81 82 83 84 85 86 87
};

/**
 * 格式化购物车商品
 *
 * @param array $cartGoods 购物车商品列表
 * @param bool $isAdvanceCart 是否是预售购物车(和上市期有关)
陈峰 authored
88 89
 * @param boolean $isValid 是否是可用商品(非失效商品),默认是
 * @param boolean $inValidLow 是否失效类型的库存不足,默认否
陈峰 authored
90 91
 * @return array 处理之后的购物车商品数据
 */
陈峰 authored
92
const formatCartGoods = (goodData, isAdvanceCart, isValid, inValidLow) => {
陈峰 authored
93
    if (typeof isValid === 'undefined') {
陈峰 authored
94 95
        isValid = true;
    }
陈峰 authored
96
    if (typeof inValidLow === 'undefined') {
陈峰 authored
97 98
        inValidLow = false;
    }
zhangxiaoru authored
99
陈峰 authored
100 101 102 103 104
    let result = {
        id: goodData.product_sku,
        skn: goodData.product_skn,
        name: goodData.product_name,
        thumb: goodData.goods_images ? helpers.image(goodData.goods_images, 120, 160) : '',
陈峰 authored
105
        color: goodData.factory_goods_name || goodData.color_name,
陈峰 authored
106 107 108
        size: goodData.size_name,
        checked: goodData.selected === 'Y',
        price: transPrice(goodData.last_vip_price),
109
        salesPrice: goodData.sales_price !== goodData.last_vip_price ? transPrice(goodData.sales_price) : false,
陈峰 authored
110 111 112 113 114
        isVipPrice: goodData.sales_price !== goodData.last_vip_price && goodData.discount_tag === 'V',
        isStudents: goodData.sales_price !== goodData.last_vip_price && goodData.discount_tag === 'S',
        count: goodData.buy_number,
        promotion_id: _.toNumber(goodData.promotion_id) === 0 ? '' : goodData.promotion_id
    };
115
116 117 118
    goodData.storage_number = _.parseInt(goodData.storage_number);
    goodData.min_buy_number = _.parseInt(goodData.min_buy_number);
    goodData.buy_number = _.parseInt(goodData.buy_number);
陈峰 authored
119
120 121
    if (goodData.min_buy_number && goodData.min_buy_number > 0) {
        result.minNumber = goodData.min_buy_number;
陈峰 authored
122
    }
123 124 125
    result.maxNumber = goodData.storage_number;
    result.minSelectNum = goodData.buy_number <= goodData.min_buy_number || goodData.buy_number === 1;
    result.maxSelectNum = goodData.buy_number >= goodData.storage_number && goodData.goods_type === 'ordinary';
陈峰 authored
126
陈峰 authored
127 128
    if (isValid) {
        // 库存不足
129
        result.lowStocks = goodData.buy_number > goodData.storage_number;
陈峰 authored
130 131
    } else { // 失效商品
        result.inValid = true;
陈峰 authored
132
        result.inValidLow = inValidLow;
陈峰 authored
133 134
    }
郭成尧 authored
135 136 137 138
    if (inValidLow && goodData.storage_number > 0) {
        result.reAddToCart = true;
    }
陈峰 authored
139 140 141
    // gift=>是否赠品,advanceBuy=>是否加价购,soldOut=>失效商品;
    if (!goodData.goods_type) {
        result.inValid = true;
陈峰 authored
142
    } else if (goodData.goods_type === 'gift' && !goodData.isAdvanceBuy) {
陈峰 authored
143 144 145
        result.isGift = true;
        result.salesPrice = transPrice(goodData.sales_price);
        result.price = transPrice(goodData.last_price);
陈峰 authored
146 147
        result.maxNumber = 1;
    } else if (goodData.goods_type === 'price_gift') {
陈峰 authored
148 149 150 151
        result.showCheckbox = true;
        result.isAdvanceBuy = true;
        result.salesPrice = transPrice(goodData.sales_price);
        result.price = transPrice(goodData.last_price);
陈峰 authored
152 153
        result.maxNumber = 1;
    } else {
陈峰 authored
154 155 156 157 158 159 160 161 162
        result.showCheckbox = true;
    }

    // 上市期
    if (isAdvanceCart && goodData.expect_arrival_time) {
        result.appearDate = goodData.expect_arrival_time;
    }

    // 商品链接
163
    result.link = helpers.urlFormat(`/product/${goodData.product_skn}.html`); // 商品url改版
陈峰 authored
164 165
    return result;
};
郭成尧 authored
166 167 168 169 170 171 172 173 174

/**
 * 失效商品池数据处理
 * @param {*} pool
 */
const formatValidPool = (pool) => {
    let poolTemp = {
        poolBuyNumber: pool.pool_buy_number,
        poolId: pool.pool_id,
郭成尧 authored
175
        poolBatchNo: pool.pool_batch_no, // 套餐批次
郭成尧 authored
176 177 178 179 180 181 182 183 184 185 186 187 188 189
        poolStorageNumber: pool.pool_storage_number,
        poolTitle: pool.pool_title,
        selected: pool.selected,
        showCheckbox: false,
        isBundle: true
    };

    poolTemp.goods = _.get(pool, 'goods_list', []).map(good => {
        return formatCartGoods(good, false, false, true);
    });

    return poolTemp;
};
陈峰 authored
190
const procPriceGiftData = (data, promotionType) => {
陈峰 authored
191
    let result = {};
陈峰 authored
192
    let arrays = _.get(data, 'arrays', []);
陈峰 authored
193
陈峰 authored
194 195 196 197
    // 赠品和加价购
    result.gifts = formatAdvanceGoods(arrays, promotionType === 'Gift');
    if (result.gifts.length === 1) {
        result.promotionTitle = result.gifts[0].promotionTitle;
陈峰 authored
198 199
    }
    return result;
陈峰 authored
200
};
陈峰 authored
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

const getPromotionFlag = (promo) => {
    switch (promo.promotion_type) {
        case 'Cashreduce': // 满减
        case 'SpecifiedAmount': // X件X元
        case 'Cheapestfree':// 满X免1
            return '满减';
        case 'Degressdiscount':// 分件折扣
        case 'Discount':// 打折
            return '折扣';
        case 'Gift':// 赠品
            return '赠品';
        case 'Needpaygift':// 加价购
            return '加价购';
        default:
            return '';
    }
};
const formatPromotion = (promo) => {
    return {
        status: promo.status,
        conditionUnit: promo.condition_unit,
        conditionValue: promo.condition_value,
        giftPrice: promo.gift_price,
lijing authored
225
        promotionId: _.get(promo, 'ts_promotion_ids', 0),
陈峰 authored
226
        promotionOriginTitle: promo.promotion_title,
lijing authored
227
        promotionTitle: _.get(promo, 'promotion_desc', ''),
陈峰 authored
228 229 230
        promotionType: promo.promotion_type,
        alreadyMatch: promo.alreadyMatch,
        optTitle: formatPromotionOpt(promo),
231 232
        promotionFlag: getPromotionFlag(promo),
        noStorage: promo.status === 20
陈峰 authored
233 234 235
    };
};
陈峰 authored
236 237 238
/**
 * 处理购物车商品、加价购商品、赠品详情数据
 *
陈峰 authored
239 240 241 242
 * @param array $productData 要处理的商品数据
 * @param int $num 购买数目
 * @return array $data 处理之后的数据
 * @internal param null $mnum 量贩最小购买数量
陈峰 authored
243
 */
陈峰 authored
244
const procGoodsDetail = (productData, num) => {
陈峰 authored
245
    let data = {};
陈峰 authored
246
    let sizeInfo = productProcess.processSkusInfo(productData);
陈峰 authored
247
248
    Object.assign(data, sizeInfo);
陈峰 authored
249
    data.productSkn = productData.product_skn;
陈峰 authored
250 251 252
    if (_.has(productData, 'special_price')) { // 加价购或者赠品的销售价字段
        data.price = productData.format_market_price;
        data.salePrice = productData.format_sales_price;
陈峰 authored
253
    } else { // 购物车商品的销售价字段
陈峰 authored
254 255 256 257 258 259 260 261 262 263
        data.price = productData.market_price > productData.sales_price ? productData.format_market_price : false;
        data.salePrice = '¥' + transPrice(productData.sales_price);
    }


    if (_.has(productData, 'storage_sum')) {
        data.storage = productData.storage_sum;
    }
    data.num = 1;
    if (num) {
264
        data.num = _.parseInt(num);
陈峰 authored
265
    }
266 267
    data.colorName = '颜色';
    data.sizeName = '尺码';
陈峰 authored
268
    return data;
陈峰 authored
269 270
};
陈峰 authored
271
const procCartData = (data, isAdvanceCart) => {
陈峰 authored
272
    if (typeof isAdvanceCart === 'undefined') {
陈峰 authored
273 274
        isAdvanceCart = true;
    }
陈峰 authored
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    let result = {};

    // 购买的可用商品列表
    result.goods = _.get(data, 'goods_list', []).map(good => {
        let gr = formatCartGoods(good, isAdvanceCart);

        if (gr.isGift) {
            gr.noEdit = true;
        }
        return gr;
    });
    result.goodPools = _.get(data, 'goods_pool_list', []).map(pool => {
        return {
            isBrand: pool.pool_type <= 1,
            isPromotion: pool.pool_type === 2,
郭成尧 authored
290
            isBundle: pool.pool_type === 3,
陈峰 authored
291
            poolTitle: pool.pool_title,
郭成尧 authored
292
            poolBuyNumber: pool.pool_buy_number,
郭成尧 authored
293 294 295
            poolId: pool.pool_id, // 套餐 activity_id
            poolBatchNo: pool.pool_batch_no, // 套餐批次
            selected: pool.selected === 'Y', // 套餐是否选中
郭成尧 authored
296
            poolStorageNumber: pool.pool_storage_number, // 库存数量
陈峰 authored
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
            goods: _.get(pool, 'goods_list', []).map(good => {
                return formatCartGoods(good, isAdvanceCart);
            }),
            promotions: _.get(pool, 'promotion_list', []).map(promo => {
                return formatPromotion(promo);
            }),
            promotionMore: _.get(pool, 'promotion_list', []).length > 1,
            sub_pool: _.get(pool, 'sub_pool', []).map(subPool => {
                return {
                    isBrand: subPool.pool_type <= 1,
                    isPromotion: subPool.pool_type === 2,
                    goods: _.get(subPool, 'goods_list', []).map(good => {
                        return formatCartGoods(good, isAdvanceCart);
                    }),
                    promotions: _.get(subPool, 'promotion_list', []).map(promo => {
                        return formatPromotion(promo);
                    }),
                    promotionMore: _.get(subPool, 'promotion_list', []).length > 1
                };
            })
        };
    });

    // 失效商品列表,库存为0
    result.notValidGoods = _.get(data, 'sold_out_goods_list', []).map(good => {
        return formatCartGoods(good, isAdvanceCart, false, true);
    });
郭成尧 authored
325 326 327 328 329
    // 失效的商品池
    result.notValidPool = _.get(data, 'sold_out_goods_pool', []).map(pool => {
        return formatValidPool(pool);
    });
陈峰 authored
330 331 332 333 334 335
    // 下架的商品列表
    result.offShelveGoods = _.get(data, 'off_shelves_goods_list', []).map(good => {
        return formatCartGoods(good, isAdvanceCart, false);
    });

    // 赠品和加价购商品
陈峰 authored
336
    if (_.get(data, 'g_gift_list', []).length || _.get(data, 'g_price_gift_list', []).length) {
陈峰 authored
337 338 339
        result.freebieOrAdvanceBuy = true;

        // 赠品
陈峰 authored
340
        result.freebie = data.g_gift_list.filter(freebie => freebie.status !== 30 && freebie.status !== 0);
陈峰 authored
341
        result.selectFreebie = result.freebie.filter(freebie => freebie.status === 10);
陈峰 authored
342
        result.giftHasStorage = _.some(result.freebie, freebie => freebie.status === 10);
陈峰 authored
343 344

        // 加价购
345
        result.advanceBuy = data.g_price_gift_list.filter(advanceBuy => advanceBuy.status !== 30 && advanceBuy.status !== 0);// eslint-disable-line
陈峰 authored
346
        result.selectAdvanceBuy = result.advanceBuy.filter(advanceBuy => advanceBuy.status === 10);
陈峰 authored
347
        result.advanceHasStorage = _.some(result.advanceBuy, advanceBuy => advanceBuy.status === 10);
陈峰 authored
348
    }
陈峰 authored
349
    result.matchGifts = _.get(data, 'match_gift_ids', []);
陈峰 authored
350 351 352 353 354 355 356

    // 已参加的活动
    if (data.promotion_info && data.promotion_info.length > 0) {
        result.promotionInfo = data.promotion_info.map(promotion => {
            return {id: promotion.promotion_id, name: promotion.promotion_title};
        });
    }
陈峰 authored
357 358
    result.shipCost = {
        isFree: _.get(data, 'shipping_cost_prompt.is_shipping_cost_free', 'N'),
李靖 authored
359
        shippingTip: _.get(data, 'shipping_cost_prompt.shipping_cost_tips', '').replace(/¥/g, '¥'),
N  
李靖 authored
360
        freeShipping: _.get(data, 'shipping_cost_prompt.is_shipping_cost_free', 'N') === 'N'
陈峰 authored
361
    };
陈峰 authored
362 363 364 365 366

    // 计算正常商品且有库存的总数
    let goodCount = _.sum(result.goods
        .filter(good => good.lowStocks === false)
        .map(good => {
367
            return _.parseInt(good.count, 10);
毕凯 authored
368
        })) + // 普通商品
陈峰 authored
369 370 371 372

        _.sum(result.goodPools
            .map(goodPool => {
                return _.sum(_.get(goodPool, 'sub_pool', [])
毕凯 authored
373 374 375 376 377 378 379 380
                    .map(subPool => {
                        return _.sum(_.get(subPool, 'goods', [])// 子促销池中的商品
                            .filter(good => good.lowStocks === false)
                            .map(good => {
                                return _.parseInt(good.count, 10);
                            }));
                    })) +
                        _.sum(_.get(goodPool, 'goods', []) // 大促销池中的商品
陈峰 authored
381 382
                            .filter(good => good.lowStocks === false)
                            .map(good => {
383
                                return _.parseInt(good.count, 10);
陈峰 authored
384 385 386 387 388 389 390
                            }));
            }));

    // 结算数据

    result.formulaPrice = data.shopping_cart_data.promotion_formula;
    result.count = data.shopping_cart_data.selected_goods_count;
391
    result.isAllSelected = (goodCount <= data.shopping_cart_data.selected_goods_count) && (data.shopping_cart_data.selected_goods_count > 0);// eslint-disable-line
陈峰 authored
392
    result.sumPrice = transPrice(data.shopping_cart_data.last_order_amount);
郭成尧 authored
393 394 395
    result.hasNoSaleGoods = result.notValidGoods.length ||
        result.offShelveGoods.length ||
        result.notValidPool.length;
陈峰 authored
396 397 398

    return result;
};
陈峰 authored
399
const processData = (data, cartType) => {
陈峰 authored
400
    if (typeof cartType === 'undefined') {
陈峰 authored
401 402
        cartType = 'all';
    }
陈峰 authored
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    let cart = data.data;
    let result = {};
    let ordinaryCount = _.get(cart, 'ordinary_cart_data.shopping_cart_data.goods_count', 0);
    let advanceCount = _.get(cart, 'advance_cart_data.shopping_cart_data.goods_count', 0);
    let ordinarySoldOut = _.get(cart, 'ordinary_cart_data.sold_out_goods_list', []);
    let advanceSoldOut = _.get(cart, 'advance_cart_data.sold_out_goods_list', []);

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

    /* 普通购物车 */
    result.commonGoodsCount = ordinaryCount;
    result.ordinarySoldOut = ordinarySoldOut.length;
陈峰 authored
419
    result.commonCart = procCartData(cart.ordinary_cart_data, false);
陈峰 authored
420 421 422 423

    /* 预售购物车 */
    result.presellGoodsCount = advanceCount;
    result.advanceSoldOut = advanceSoldOut.length;
陈峰 authored
424
    result.preSellCart = procCartData(cart.advance_cart_data);
陈峰 authored
425 426 427
    return result;
};
陈峰 authored
428
陈峰 authored
429 430 431 432 433 434 435 436 437
/**
 * 获取处理量贩数据
 * @param $productSkn
 * @return array
 */
const handleBundleInfo = (apiResult) => {
    let result = {};

    if (apiResult && apiResult.code === 200 && apiResult.data) {
陈峰 authored
438 439 440 441 442 443
        let discountBuy = _.find(apiResult.data, bund => _.get(bund, 'bundleInfo.discountType') === 2);

        if (discountBuy) {
            result.num = discountBuy.bundleInfo.bundleCount;
            result.discount = _.has(discountBuy.bundleInfo, 'discount') ? discountBuy.bundleInfo.discount : false;
            result.promotionPhrase = discountBuy.bundleInfo.promotionPhrase;
陈峰 authored
444 445 446 447
        }
    }

    return result;
陈峰 authored
448
};
陈峰 authored
449
陈峰 authored
450 451
module.exports = {
    processData,
陈峰 authored
452 453 454
    procGoodsDetail,
    handleBundleInfo,
    procPriceGiftData
陈峰 authored
455
};