product-process.js 19.7 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 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
'use strict';
require('../app');
const _ = require('lodash');
const helpers = global.yoho.helpers;
const GENDER = {
    1: '男',
    2: '女',
    3: '男|女'
};

/**
 * 根据性别来决定  默认图片获取字段   如果是 2、3
 *
 * 则优先从cover_2 --》 cover_1 -- 》 images_url
 * 否则优先从cover_1 --》 cover_2 -- 》 images_url
 *
 */
// const _procProductImg = (product, gender, yhChannel) => {
//     if (gender === '2,3' || gender === '2' || gender === '3' && yhChannel === '2') {
//         return product.cover_2 || product.images_url || product.cover_1 || '';
//     }
//
//     return product.cover_1 || product.images_url || product.cover_2 || '';
// };

const productNameProcess = require('./product-name-process');


const toArray = (obj) => {
    if (_.isArray(obj)) {
        return obj;
    }
    let arr = [];

    _.forEach(obj, (v, k) => {
        if (_.isObject(v)) {
            v._key = k;
        } else {
            v = {
                _key: k,
                _value: v
            };
        }
        arr.push(v);
    });

    return arr;
};

/**
 * 按照数组中指定字段排序二维数组
 *
 * @param  array list 需要排序的数组
 * @param  string key 字段名称
 * @param  boolean 有 desc 时候降序排列,默认为false
 */
const _sortListByField = (list, key, desc) => {
    let array = toArray(list);

    return array.sort(function(a, b) {
        a = a._key.split(',')[0] * 1;
        b = b._key.split(',')[0] * 1;
        return desc ? a < b : a > b;
    });

/*
    array = array.sort((a, b) => {
        let matchNumber = /([\d]+)/g;

        // 有键,使用键的值排序
        if (a[key] && b[key]) {
            let numA = +(_.toArray(a[key].match(matchNumber))[0] || 0); // 取第一个出现的数字排序,如果不存在,取0
            let numB = +(_.toArray(b[key].match(matchNumber))[0] || 0);

            return (desc ? numA > numB : numA < numB) ? -1 : 1;
        }

        // 无键, 使用本身
        let numA = +(_.toArray(a._value.match(matchNumber))[0] || 0);
        let numB = +(_.toArray(b._value.match(matchNumber))[0] || 0);

        return numA < numB ? -1 : 1;
    });

    return array;*/
};

/**
 * 商品搜索商品数据处理
 */
exports.processProductList = (list, options) => {
    const pruductList = [];

    options = Object.assign({
        showTags: true,
        showNew: true,
        showSale: true,
        width: 290,
        height: 388,
        isApp: false,
        showPoint: true,
        gender: '2,3'
    }, options);

    _.forEach(list, (product) => {
        if (!product) {
            return;
        }

        // H5 暂时不支持全球购商品,先过滤掉 2017.04.09
        // if (product.is_global === 'Y') {
        //     return;
        // }

        // 商品信息有问题,则不显示
        if (!(
            (product.product_skn && _.get(product, 'goods_list.length', 0)) || product.recommend_type
        )) {
            return;
        }

        if (product.recommend_type) {
            // recommend_type 对应 附加属性
            let flagMap = {
                fashionArticle: '_isFashionArticle',
                seasonSort: '_isSeasonSort',
                hotShop: '_isHotShop',
                hotSearchTerm: '_isHotSearchTerm',
            };

            let extraAttr = flagMap[product.recommend_type];

            if (extraAttr) {
                product[extraAttr] = true;

                if (extraAttr === '_isHotShop' && parseInt(product.data.show_type, 10) === 1) {
                    product.reShop = true;
                    product.data.shopUrl = '//m.yohobuy.com/product/shop?domain=' + product.data.shop_domain;
                }

                pruductList.push(product);
            }

            return;
        }

        // 如果库存为0,显示已抢完
        // if (product.storage_num === 0) {
        //     product.noStorage = true;
        // }

        // 市场价和售价一样,则不显示市场价
        if (!product.market_price || product.market_price === product.sales_price) {
            product.market_price = false;
        }

        // 判别默认的商品是否将默认的图片URL赋值到skn
        // let flag = false;

        // 如果设置了默认图片,就取默认的图片
        // _.forEach(product.goods_list, (goods) => {
        //     if (flag) {
        //         return;
        //     }
        //     if (goods.is_default === 'Y') {
        //         // product.default_images = procProductImg(goods);
        //         // product.default_images = product.default_images;
        //         flag = true;
        //     }
        // });

        // 如果还未赋值,则取第一个skc产品的默认图片
        // if (!flag) {
        //     product.default_images = _procProductImg(product.goods_list[0], product.gender, options.yh_channel);
        // }

        product.is_soon_sold_out = product.is_soon_sold_out === 'Y';

        if (product.cn_alphabet) {
            product.cn_alphabet = productNameProcess(product.cn_alphabet);
        }

        product.url = product.is_global === 'Y' ? helpers.urlFormat(`/product/global/${product.product_skn}.html`) :
            helpers.urlFormat(`/product/${product.product_skn}.html`); // 商品url改版 // eslint-disable-line

        /**
         * 全球购商品标记
         */
        if (product.is_global === 'Y') {
            product.isGlobal = true;
        }

        /**
         * 限定商品标记
         */
        if (product.is_limitbuy === 'Y') {
            product.isLimitbuy = true;
        }

        // APP访问需要加附加的参数
        // 备注:如果以后APP的接口太多,可以把这边参数提取出来,变成一个公共的方法来生成,便于以后管理维护
        if (options.isApp) {
            if (product.is_global === 'Y') {
                product.url = `http:${product.url}?openby:yohobuy={"action":"go.globalpurchase","params":{"skn":"${product.product_skn}"}}`;  // eslint-disable-line
            } else {
                product.url = `http:${product.url}?openby:yohobuy={"action":"go.productDetail","params":{"product_skn":"${product.product_skn}"}}`;  // eslint-disable-line
            }
        }

        if (options.showTags) {
            let tags = {};

            _.forEach(product.tags, tag => {
                tags[tag] = true;
            });

            product.tags = tags;

            if (tags.is_solded === true) {
                product.is_solded = true;
            }

            if (product.is_global === 'Y' && product.tbl_country_name && product.tbl_country_name !== '') {
                tags.is_global = true;
            }

            product.is_soon_sold_out = tags.is_soon_sold_out;

        }

        // 显示相似商品按钮
        if (options.showSimilar) {
            product.similar = true;
        }

        product.imgAlt = _.compact([product.brand_name, (product.gender ? GENDER[product.gender] : false), product.small_sort_name, product.product_name]).join('|'); // eslint-disable-line

        pruductList.push(product);
    });

    return pruductList;
};

/**
 * 分词数据处理
 * @param list
 * @param  string | options
 * @return array 处理之后的筛选数据
 */
exports.termsSuggestion = (list, options) => {
    let termsSuggestion = [];
    let query = options.query && decodeURIComponent(options.query.replace(/\%/g, escape('%'))) || '';

    _.each(list, (terms, index) => {
        termsSuggestion.push({
            name: terms,
            link: helpers.urlFormat('/', {needSuggestion: 'Y', query: terms, from: 'search'}, 'search'),
            select: (options.isChangedQuery && index === 0) ||
                (options.needSuggestion === 'Y' && terms === query)
        });
    });

    return termsSuggestion;
};

/**
 * 处理筛选数据
 * @param list
 * @param  string | options
 * @return array 处理之后的筛选数据
 */
exports.processFilter = (list, options) => {

    const filters = {
        classify: []
    };

    const filtersType = {
        brand: {
            name: '所有品牌',
            title: '品牌',
            dataId: 'id',
            subsName: 'brand_name',
            firstSub: 0,
            dataType: 'brand',
            sortNum: '1'
        },
        color: {
            name: '所有颜色',
            title: '颜色',
            dataId: 'color_id',
            subsName: 'color_name',
            firstSub: 0,
            dataType: 'color',
            sortNum: '4'
        },
        discount: {
            name: '所有商品',
            title: '折扣',
            dataId: 'key',
            subsName: 'name',
            firstSub: '0,1',
            dataType: 'p_d',
            sortNum: '7'
        },
        gender: {
            name: '所有性别',
            title: '性别',
            dataId: 'key',
            subsName: 'flag',
            firstSub: '1,2,3',
            dataType: 'gender',
            sortNum: '0'
        },
        group_sort: {
            name: '所有品类',
            title: '品类',
            dataId: 'relation_parameter',
            subsName: 'category_name',
            firstSub: 0,
            dataType: 'sort',
            sortNum: '3'
        },
        priceRange: {
            name: '所有价格',
            title: '价格',
            dataId: 'key',
            subsName: 'flag',
            firstSub: 0,
            dataType: 'price',
            sortNum: '6'
        },
        size: {
            name: '所有尺码',
            title: '尺码',
            dataId: 'size_id',
            subsName: 'size_name',
            firstSub: 0,
            dataType: 'size',
            sortNum: '5'
        },
        ageLevel: {
            name: '所有人群',
            title: '人群',
            dataId: 'id',
            subsName: 'name',
            firstSub: 0,
            dataType: 'ageLevel',
            sortNum: '2'
        }
    };

    options = Object.assign({
        gender: '1,2,3', // 默认选择的性别,默认1,2,3表示所有
        exclude: null // 需要排除的字段
    }, options);

    _.forEach(list, (item, key) => {
        let classify = {
            subs: []
        };

        if (!filtersType[key]) {
            return;
        }

        if ((options.hideSize && key === 'size') || (options.hideSort && key === 'group_sort')) {
            return;
        }

        classify.dataType = filtersType[key].dataType;
        classify.name = filtersType[key].name;
        classify.title = filtersType[key].title;

        classify.subs.push({
            chosed: true,
            dataId: filtersType[key].firstSub,
            name: filtersType[key].name
        });

        // 折扣,价格区间,需要排序
        if (key === 'discount' || key === 'priceRange') {
            item = _sortListByField(item, 'name');
        }

        _.forEach(item, (sub, index) => {
            let subs = {};

            if (key === 'discount') {
                subs.dataId = sub._key;
            } else if (key === 'priceRange') {
                subs.dataId = sub._key;
            } else if (filtersType[key].dataId === 'key') {
                subs.dataId = index;
            } else if (filtersType[key].dataId === 'relation_parameter') {
                subs.dataId = sub.relation_parameter['sort']; // eslint-disable-line
            } else {
                subs.dataId = sub[filtersType[key].dataId];
            }

            if (key === 'priceRange') {
                subs.name = sub._value.replace('¥', '¥');
            } else if (filtersType[key].subsName === 'flag') {
                subs.name = sub;
            } else {
                subs.name = sub[filtersType[key].subsName];

                if (key === 'discount') {
                    subs.name = subs.name + '折商品';
                }
            }
            classify.subs.push(subs);
        });

        filters.classify[filtersType[key].sortNum] = classify;
    });

    return filters;
};

/**
 * 解析skn数据,支持多属性
 */
exports.processSkusInfo = (origin) => {
    let tickets = origin.attribute === 3;
    let dest = {
        productId: origin.product_id,
        name: origin.product_name || '',
        totalNum: origin.storage_sum,
        skus: [],
        props: [{
            name: tickets ? '日期' : '颜色',
            type: 'color',
            values: []
        }, {
            name: tickets ? '区域' : '尺码',
            type: 'size',
            values: []
        }]
    };
    let colorChosed = false;

    // 只有一个颜色,默认选中
    if (_.get(origin, 'goods_list.length') === 1) {
        colorChosed = true;
    }

    // 解析接口数据构造为带属性列表的sku列表
    _.each(origin.goods_list, color => {
        let sizeChosed = false;

        // 只有一个尺码,默认选中
        if (_.get(color, 'size_list.length') === 1 && _.get(origin, 'goods_list.length') === 1) {
            sizeChosed = true;
        }

        _.each(color.size_list, size => {
            let colorProp = dest.props.find(prop => prop.type === 'color'),
                sizeProp = dest.props.find(prop => prop.type === 'size');

            if (!_.some(colorProp.values, prop => prop.id === color.product_skc)) {
                colorProp.values.push({
                    id: color.product_skc,
                    name: color.factory_goods_name || color.color_name,
                    chosed: colorChosed
                });
            }
            if (!_.some(sizeProp.values, prop => prop.id === size.size_id)) {
                sizeProp.values.push({
                    id: size.size_id,
                    name: size.size_name,
                    chosed: sizeChosed
                });
            }

            dest.skus.push({
                skuId: size.product_sku,
                sizeInfo: size.size_info,
                sizeRec: size.size_rec,
                storage: size.storage_number,
                thumb: helpers.image(color.color_image, 300, 395),
                prop: {
                    color: {
                        valId: color.product_skc,
                        goodsId: color.goods_id,
                        valName: color.factory_goods_name || color.color_name
                    },
                    size: {
                        valId: size.size_id,
                        valName: size.size_name
                    }
                },
                limitNum: size.limit_buy_num
            });
        });
    });

    dest.defaultThumb = helpers.image(_.get(dest, 'skus[0].thumb', ''), 300, 395);

    return dest;
};

/**
 * 解析尺码弹出框数据
 */
exports.processSizeInfo = (origin) => {
    let cartInfo = {},
        thumbImageList = [],
        colorGroup = {},
        sizeGroup = [],
        totalStorageNum = 0;

    if (origin.goods_list.length) {
        let goodsGroup = [],
            sizeName = '',
            colorList = [],
            sizeList = {},
            allSizeList = {},
            colorStorageGroup = {},
            colorStorageNum = 0;

        _.forEach(origin.goods_list, function(value) {
            // 未上架也显示
            // if (value.status === 0) {
            //     return;
            // }

            colorStorageNum = 0;

            // 商品分组
            if (value.images_list) {
                _.forEach(value.images_list, function(good) {
                    goodsGroup.push({
                        goodsId: value.goods_id,
                        img: good.image_url
                    });
                });
            }

            // 商品的尺码列表
            colorStorageGroup[value.product_skc] = {};
            if (value.size_list) {
                sizeList[value.product_skc] = [];
                _.forEach(value.size_list, function(size) {
                    sizeList[value.product_skc].push({
                        id: size.size_id,
                        skuId: size.product_sku,
                        goodsId: value.goods_id,
                        colorId: value.color_id,
                        name: size.size_name,
                        sizeNum: size.storage_number,
                        sizeInfo: size.size_info ? size.size_info : ''
                    });

                    sizeName = size.size_name;

                    // 所有尺码列表,赋值用于前端展示默认尺码的时候
                    // 判断出没有库存则显示灰色
                    let build = {
                        id: size.size_id,
                        storage: size.storage_number,
                        sizeInfo: size.size_info ? size.size_info : ''
                    };

                    allSizeList[sizeName] = (allSizeList[sizeName] === null ||
                    typeof allSizeList[sizeName] === 'undefined') ? build : allSizeList[sizeName];
                    colorStorageNum += parseInt(size.storage_number, 10);
                    colorStorageGroup[value.product_skc][sizeName] = parseInt(size.storage_number, 10);
                });


                // 颜色分组
                colorList.push({
                    id: value.color_id,
                    skcId: value.product_skc,
                    name: value.factory_goods_name || value.color_name,
                    colorNum: colorStorageNum
                });
            }

            // 缩略图
            thumbImageList.push({
                img: helpers.image(value.color_image, 300, 395)
            });

            // 商品库存总数
            totalStorageNum += _.toNumber(colorStorageNum);
        });

        // 遍历所有尺码,构建颜色显示数据
        let i = 1;

        sizeGroup[0] = {
            size: []
        };
        _.forEach(allSizeList, (value, key) => {

            // 默认尺码
            sizeGroup[0].size.push({
                name: key,
                sizeNum: _.toNumber(value.storage) > 0 ? true : false,
                id: value.id,
                sizeInfo: value.sizeInfo
            });

            colorGroup[i] = {
                color: []
            };

            // 各个颜色的尺码, 每行显示一个尺码对应的颜色
            _.forEach(colorList, (colorArr) => {
                let tempColorArr = _.cloneDeep(colorArr);

                if (colorStorageGroup[tempColorArr.skcId] &&
                    colorStorageGroup[tempColorArr.skcId][key]) {
                    tempColorArr.colorNum = colorStorageGroup[tempColorArr.skcId][key];
                } else {
                    tempColorArr.colorNum = 0;
                }
                colorGroup[i].color.push(Object.assign({}, tempColorArr));
            });
            colorGroup[i].id = value.id;

            ++i;
        });

        colorGroup[0] = {
            color: []
        };

        // 遍历所有颜色, 构建尺码显示数据
        i = 1;
        _.forEach(colorList, function(value) {

            // 各个尺码的颜色, 每行显示一个颜色的对应尺码
            sizeGroup[i] = {
                size: sizeList[value.skcId],
                colorId: value.skcId
            };

            // 默认颜色
            colorGroup[0].color.push(value);
            ++i;
        });
        _.orderBy(colorGroup);
        Object.assign(cartInfo, {
            productId: origin.product_id,
            thumbs: thumbImageList,
            name: origin.product_name || '',
            totalNum: totalStorageNum,
            colors: _.toArray(colorGroup),
            sizes: sizeGroup
        });
    }
    return cartInfo;
};

/**
 * 处理有货币的促销信息
 */
exports.procPromYohoCoin = (promotionYohoCoinData, vipLevel) => {
    let showText = '';

    _.forEach(promotionYohoCoinData, levelInfo => {
        if (_.get(levelInfo, 'vip_level', -1) === vipLevel) {
            showText = levelInfo.title;
            return;
        }
    });

    return showText;
};