cart-helper.js 12.1 KB
/**
 * Created by yoho on 2016-12-21.
 */
'use strict';

const _ = require('lodash');
const helpers = global.yoho.helpers;
const md5 = require('md5');

const PROMOTION_TYPE_TAG_MAP = {
    Cashreduce: '满减',         // 满减
    Degressdiscount: '折扣',    // 分件折扣
    Cheapestfree: '满减',       // 满X免1
    Discount: '折扣',           // 打折
    Gift: '赠品',
    Needpaygift: '加价购',
    SpecifiedAmount: '满减'     // X件X元
};

/**
 * 从用户加入购物车的COOKIE取出购物车凭证
 */
const getShoppingKeyByCookie = (req) => {

    return req.cookies._SPK || '';
};

/**
 * 转换价格
 *
 * @param float|string $price 价格
 * @return float|string 转换之后的价格
 */
const transPrice = (price) => {
    return price ? (price * 1).toFixed(2) : '0.00';
};

/**
 * 生成公开的TOKEN凭证
 *
 * @param string $string 字符串
 * @return string
 */
const makeToken = (str) => {
    return md5(md5(str + '#@!@#'));
};

/**
 * 购物车商品
 * @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,
            isChecked: it.selected === 'Y',
            productTitle: it.product_name,
            imgCover: it.goods_images ? helpers.image(it.goods_images, 60, 60) : '',
            productColor: it.factory_goods_name,
            productSize: it.size_name,
            productPrice: transPrice(it.last_vip_price), // self::transPrice($value['real_price']);
            productNum: it.buy_number,
            isVipPrice: it.sales_price !== it.last_vip_price && it.discount_tag === 'V',
            isStuPrice: it.sales_price !== it.last_vip_price && it.discount_tag === 'S',
            yohoIcon: it.get_yoho_coin || 0,
            productSubtotal: transPrice(it.last_vip_price * it.buy_number),
            promotionId: it.promotion_id || 0,
            isLimitSkn: it.is_limit_skn === 'Y'  // is_limit_skn=Y 不支持7天无理由退货
        };


        // 已下架
        if (isOffShelves) {
            goods.isTipNoStore = true;
            goods.tipMessage = '库存不足';
        } else if (!inValid) {  // 有效
            if (it.buy_number > it.storage_number) {
                goods.isTipNoStore = true; // 是否在结算时候显示库存不足
                goods.tipMessage = '库存不足';
            } else if (it.storage_number <= 2) {
                goods.tipMessage = '余量有限';
            }
        } else { // 失效商品
            goods.inValid = true;
        }

        // advanceBuy=>是否加价购,soldOut=>失效商品;
        if (!it.goods_type) {
            goods.inValid = true;
        } else if (it.goods_type === 'gift' && it.isAdvanceBuy) {  // gift=>是否赠品
            goods.isGift = true;
            goods.productPrice = transPrice(it.last_price);
            goods.productSubtotal = it.subtotal ? transPrice(it.subtotal) : goods.productPrice;
        } else if (it.goods_type === 'price_gift') { // price_gift=>是否加价购
            goods.isPriceGift = true;
            goods.productPrice = transPrice(it.last_price);
            goods.productSubtotal = it.subtotal ? transPrice(it.subtotal) : goods.productPrice;
        } else if (it.real_price === 0) {    // 免单
            goods.productPrice = transPrice(it.sales_price);
            goods.xForOne = true;

            // 分析用: 商品ID列表
            if (_.isArray(_.get(analysis, 'ids'))) {
                analysis.ids.push(it.product_id);
            }

            // 分析用: CRITEO
            if (_.isArray(_.get(analysis, 'criteo'))) {
                analysis.criteo.push({
                    id: it.product_skn,
                    quantity: Number(it.buy_number),
                    price: it.last_vip_price
                });
            }
        } else {
            // 分析用: 商品ID列表
            if (_.isArray(_.get(analysis, 'ids'))) {
                analysis.ids.push(it.product_id);
            }

            // 分析用: CRITEO
            if (_.isArray(_.get(analysis, 'criteo'))) {
                analysis.criteo.push({
                    id: it.product_skn,
                    quantity: Number(it.buy_number),
                    price: it.last_vip_price
                });
            }
        }

        // 商品类型:预售或普通
        goods.goodsType = isAdvanceCart ? 'advance' : 'ordinary';

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

        // 商品链接
        let cnAlphaBet = it.cn_alphabet ? it.cn_alphabet : md5(it.product_name);

        goods.link = helpers.urlFormat(`/product/pro_${it.product_id}_${it.goods_id}/${cnAlphaBet}.html`, null, 'item');

        return goods;
    });
};

/**
 * 购物车统计
 */
const formatShoppingCartData = (sc) => {

    return {
        discountAmount: sc.discount_amount,     // 活动价
        fastShoppingCost: sc.fast_shopping_cost,
        gainYohoCoin: sc.gain_yoho_coin,        // 获赠有货币个数
        goodsCount: sc.goods_count,
        isMultiPackage: sc.is_multi_package,
        lastOrderAmount: sc.last_order_amount,      // 商品金额总计
        orderAmount: sc.order_amount,   // 商品总价
        //  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,
            promotionTitle: it.promotion_title,
            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);
};

/**
 * 可选加价购
 * isGift 是否是赠品:true-赠品
 */
const formatPriceGifts = (giftList, isGift) => {

    return _.map(giftList, (it) => {

        let gift = {
            isShowGift: isGift, // 控制是否显示赠品
            isFold: true, // 控制是否[展开]
            promotionId: it.promotion_id,
            promotionTitle: it.promotion_title.replace('¥', '¥') + '(注:您看到的以下商品可能因为下单时间差已售完)',  // subjoinType
            maxSelectNumber: it.max_select_number,
            promotionType: it.promotion_type
        };

        gift.goodsList = _.map(it.goods_list, (g) => {

            let goods = {
                id: g.product_id,
                skn: g.product_skn,
                subjoinTitle: g.product_name,
                imgCover: it.goods_images ? helpers.image(it.goods_images, 60, 60) : '',
                subjoinPrice: transPrice(g.last_price),
                marketPrice: isGift ? '' : transPrice(g.market_price),
                yohoIcon: 0
            };

            // 商品链接
            if (g.goods_id) {
                let cnAlphaBet = g.cn_alphabet ? g.cn_alphabet : md5(g.product_name);

                goods.subjoinLink = helpers.urlFormat(`/product/pro_${g.product_id}_${g.goods_id}/${cnAlphaBet}.html`,
                                                null, 'item');
            } else {
                let uri = `/product/show_${g.product_id}_${g.product_skn}/${makeToken(g.product_skn)}.html`;

                goods.subjoinLink = helpers.urlFormat(uri, null, 'item');
            }

            // 赠品
            if (isGift) {
                goods.isGift = true;
            } else {  // 加价购
                goods.isPriceGift = true;
            }

            return goods;
        });
    });
};

/**
 * 购物车赠品
 */
const formatGifts = (giftList) => {
    return formatPriceGifts(giftList, true);
};

/**
 * 优惠池头部优惠信息列表
 */
const formatPoolPromotionInfos = (infoList) => {

    return _.map(infoList, it => {

        let status = Number(it.status);
        let info = {
            status: status,

            // "status": 0, // 状态 0 未满足 10 已满足 [20 售光 30 更换 ]
            conditionUnit: it.condition_unit,   // 0满足,1 件,2金额
            conditionValue: it.condition_value,
            giftPrice: it.gift_price,   // 赠品或加价购商品价格
            giftGoodsList: formatCartGoods(it.gift_goods_List),  // 可供选择的赠品或加价购商品列表
            promotionId: it.promotion_id, // 促销id
            promotionTitle: it.promotion_title, // "已满足[满30减10-dev30]",
            promotionType: it.promotion_type,  // 促销类型
            tag: PROMOTION_TYPE_TAG_MAP[it.promotion_type],

            isGift: it.promotion_type === 'Gift',
            isPriceGift: it.promotion_type === 'Needpaygift',
            isNotReach: status === 0,   // 未满足
            isReach: status === 10,     // 满足条件
            isEmpty: status === 20,     // 已售完
            isSelected: status === 30   // 已选择,可更换
        };

        if (status === 0) {
            let tipTxt = `差${ -1 * info.conditionValue}`;

            if (info.conditionUnit === 1) {
                tipTxt += '件';
            } else if (info.conditionUnit === 2) {
                tipTxt += '元';
            }

            info.promotionTitle = tipTxt + info.promotionTitle;
        } else if (status === 10) {
            info.promotionTitle = '已满足' + info.promotionTitle;
        }
        return info;
    });
};

/**
 * 格式化子优惠池信息,返回商品列表,子优惠列表放在每个商品中
 */
const formatSubPromotionPools = (pools) => {

    let goodsListPool = _.map(pools, p => {
        let pool = {
            goodsList: formatCartGoods(p.goods_list),
            promotionInfos: formatPoolPromotionInfos(p.promotion_list)
        };

        let goodsList = pool.goodsList;

        if (goodsList && goodsList.length) {
            return _.map(goodsList, g => {
                g.promotionInfos = pool.promotionInfos;
                return g;
            });
        }

        return [];
    });

    // [ [goods, goods], [goods, ..], [] ] => [goods, goods ]
    return _.flatten(goodsListPool);
};

/**
 * 优惠池
 */
const formatPromotionPools = (pools) => {
    return _.map(pools, p => {

        let pool = {
            poolTitle: p.pool_title,
            poolType: p.pool_type,
            goodsList: formatCartGoods(p.goods_list),
            promotionInfos: formatPoolPromotionInfos(p.promotion_list)
        };

        if (p.sub_pool) {
            let goodsWithPromotion = formatSubPromotionPools(p.sub_pool);

            if (_.isArray(goodsWithPromotion) && goodsWithPromotion.length) {
                pool.goodsList = goodsWithPromotion.concat(pool.goodsList);
            }
        }

        return pool;
    });
};

module.exports = {
    transPrice,
    getShoppingKeyByCookie,
    formatCartGoods,
    formatGifts,
    formatPriceGifts,
    formatShoppingCartData,
    formatPromotionPools,
    formatPromotionInfos,
    formatOffShelves,
    formatSoldOuts
};