index.js 20.9 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 673 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 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
/**
 * 逛 model
 * @author: lcy<chuanyang.liu@yoho.cn>
 * @date: 2016/08/31
 */
'use strict';

const _ = require('lodash');
const moment = require('moment');
const ghelper = require('./guang-helper');


const helpers = global.yoho.helpers;
const serviceApi = global.yoho.ServiceAPI;
const yohoApi = global.yoho.API;

// const KEY_WEB_GUANG_BANNER_DATA = 'key_web_guang_banner_data';// 逛的首页banner
// const KEY_WEB_GUANG_ADS_DATA = 'key_web_guang_ads_data';// 逛的首页ads
const URL_OPERATIONS_RESOURCE_GET = 'operations/api/v5/resource/get';

// guang banner code
const BANNER_CODE = {
    boys: '15a288635c2ed9f6c807417be90f5d2d',
    girls: 'e14e12e35af8626650979f7af8a0de2b',
    lifestyle: '1d398e899f759c6d88971be680521a6f',
    kids: 'ad14ee01ad048ce308aa3ca416133d2a'
};

// 逛 ads code
const ADS_CODE = {
    boys: '41777aa7ac86347692c5aa0d394b2f59',
    girls: '722253573823ebb994e313e71b0a4fb9',
    lifestyle: '02568b6042510e4be739cc688dc7d6ae',
    kids: '1ffdd6ea22c58af52ee6408cd353c2d5'
};

/**
 * 获取首页频道nav
 */
const getHomeChannelNav = (channel) => {
    let home;

    switch (channel) {
        case 'girls':
            home = helpers.urlFormat('/woman', '', 'new');
            break;
        case 'lifestyle':
            home = helpers.urlFormat('/lifestyle', '', 'new');
            break;
        case 'kids':
            home = helpers.urlFormat('/kids', '', 'new');
            break;
        default:
            home = helpers.urlFormat('', '', 'default');

    }

    return {
        href: home,
        name: `${channel.toUpperCase()}首页`,
        pathTitle: 'YOHO!有货'
    };
};

const getPathNav = (channelType, query) => {

    let path = _.concat(
        getHomeChannelNav(channelType),
        [{
            name: '逛',
            pathTitle: '逛',
            href: helpers.urlFormat('', '', 'guang')
        }]
    );

    return query ? _.concat(path, [{ name: query, pathTitle: query}]) : path;
};

const _formatTag = (tagData) => {
    let name = tagData.name;

    return {
        tag: name,
        name: name,
        url: helpers.urlFormat('/tags/index', {query: name}, 'guang')
    };
};

/**
 * 格式化资讯文章
 *
 * @param array $articleData 需要格式化的资讯数据
 * @param bool $showTag 是否显示左上角标签
 * @param bool $showAuthor 控制是否显示作者信息
 * @return array | false
 */
const _formatArticle = (articleData, showTag, showAuthor) => {

    // 资讯ID不存在,则不显示
    if (!articleData || !articleData.id) {
        return false;
    }

    let width = 360,
        height = 360,
        isSquareImage = true;


    if (articleData.conver_image_type === 2) {
        width = 360;
        height = 240;
        isSquareImage = false;
    }

    let result = {
        id: articleData.id,
        classification: articleData.category_name,
        isReco: articleData.is_recommended ? true : false,
        url: ghelper.getArticleUrl(articleData.url, articleData.id),
        img: helpers.image(articleData.src, width, height, 1),
        isSquareImg: isSquareImage,
        title: articleData.title,
        pTime: articleData.publish_time,
        pView: articleData.views_num,
        content: articleData.intro,
        showTags: showTag,
        comment: articleData.comment_num
    };

    if (!articleData.author) {
        articleData.author = {
            name: '',
            avatar: ''
        };
    }

    result.author = articleData.author.name;

    let authorId = articleData.author.author_id;

    if (authorId) {
        result.editorUrl = helpers.urlFormat('/Index/editor', {author_id: authorId}, 'guang');
    }

    let tags = [];

    if (articleData.tags) {
        let aTags = articleData.tags;

        for (let i = 0; i < aTags.length; i++) {
            tags.push(_formatTag(aTags[i]));
        }
    }

    result.tags = tags;

    _.assign(result, {
        tags: tags,
        like: articleData.praise_num,
        liked: articleData.isPraise === 'Y'
    });

    // 判断是否显示作者信息
    if (showAuthor && articleData.author) {
        result.author = _.cloneDeep(articleData.author);
    }

    // 模板中需要的标签标识
    if (showTag && articleData.category_id) {
        let categoryId = '' + articleData.category_id;

        switch (categoryId) {
            case '1': // 话题
                result.isTopic = true;
                break;
            case '2': // 搭配
                result.isCollocation = true;
                break;
            case '3': // 潮人
                result.isFashionMan = true;
                break;
            case '4': // 潮品
                result.isFashionGood = true;
                break;
            case '5': // 小贴士
                result.isTip = true;
                break;
        }
    }
    return result;
};

const _formatAd = (adData) => {

    return {
        img: helpers.image(adData.src, 640, 640),
        url: helpers.urlFormat('/info/index', {id: adData.id}, 'guang'),
        title: adData.title,
        bgColor: adData.bgColor
    };
};

/**
 * 获取页文章数据
 * @param  {String} channelType 传入频道页类型,值可以是: boys, girls, kids, lifestyle
 * @return {Object}
 */
const getArticleList = (gender, sortId, uid, udid, page, tag, authorId, limit, useCache) => {

    uid = uid || 0;
    udid = udid || '';
    page = page || 1;
    useCache = useCache || false;

    let param = {
        gender: gender,
        page: page,
        uid: uid,
        udid: udid,
        client_type: 'web'
    };

    if (sortId) {
        param.sort_id = sortId;
    }

    if (tag) {
        param.tag = tag;
    }

    if (_.isNumber(authorId)) {
        param.author_id = authorId;
    }

    if (limit) {
        param.limit = limit;
    }

    return serviceApi.get('guang/api/v2/article/getList', param, {
        cache: useCache ? 300 : false
    }).then(res => {

        if (res && res.data) {

            let artList,
                adsList,
                total = 0;

            if (res.data.total) {
                total = _.parseInt(res.data.total);
            }

            if (res.data.list) {
                let list = res.data.list;

                if (list.artList) {
                    artList = _.map(list.artList, it => _formatArticle(it, true, false));
                }

                if (list.adlist) {
                    adsList = _.map(list.artList, it => _formatAd(it));
                }
            }

            return {
                msgs: artList,
                ads: adsList,
                total: total
            };
        }
    });
};

/**
 * 获取热门标签数据
 * @param  {String} type 传入频道页类型,值可以是: boys, girls, kids, lifestyle
 * @return {Object}
 */
const getHotTags = (page, limit) => {

    let data = {
        client_type: 'web',
        page: page || 1,
        limit: limit || 10
    };

    return serviceApi.get('guang/api/v2/article/getTagTop', data, {
        cache: false
    }).then(res => {
        return _.map((res && res.data) || [], it => {
            return {
                tagName: it.tag_name,
                url: helpers.urlFormat('/tags/index', { query: it.tag_name}, 'guang')
            };
        });
    });
};

/**
 * 获取广告数据
 * @param  {String} channelType 传入频道页类型,值可以是: boys, girls, kids, lifestyle
 * @return {Object}
 */
const getAds = channelType => {

    let contentCode = ADS_CODE[channelType] || ADS_CODE.boys;

    return serviceApi.get(URL_OPERATIONS_RESOURCE_GET, {
        content_code: contentCode
    }, {cache: true}).then(res => {
        let list = [];

        if (res && res.code === 200 && res.data && res.data[0] && res.data[0].data) {
            list = _.map(res.data[0].data, (it) => {
                return {
                    img: helpers.image(it.src, 640, 640, 1),
                    url: it.url
                };
            });
        }

        return list.length > 5 ? list.slice(0, 4) : list;
    });
};

/**
 * 获取热门标签数据
 * @param  {String} type 传入频道页类型,值可以是: boys, girls, kids, lifestyle
 * @return {Object}
 */
const getBanner = channelType => {

    let contentCode = BANNER_CODE[channelType] || BANNER_CODE.boys;

    return serviceApi.get(URL_OPERATIONS_RESOURCE_GET, {
        content_code: contentCode
    }, {cache: true}).then(res => {

        let list = [];

        if (res && res.code === 200 && res.data && res.data[0] && res.data[0].data) {

            list = _.map(res.data[0].data, it => {
                return {
                    img: helpers.image(it.src, 830, 327, 1),
                    url: it.url
                };
            });
        }
        return list;
    });
};

const getCategory = currentSortId => {

    currentSortId = currentSortId || 0;
    return serviceApi.get('guang/api/v1/category/get', {}).then(res => {
        let list = [];

        if (res && res.code === 200 && res.data) {
            for (let cat of res.data) {
                list.push({
                    typeId: cat.id,
                    type: cat.name,
                    isActive: cat.id === currentSortId,
                    navUrl: helpers.urlFormat('/index/index', {type: cat.id}, 'guang')
                });
            }
        }

        return list;
    });
};

/**
 * 推荐文章
 */
const getRecoArticles = (gender, page, limit) => {

    return serviceApi.get('guang/api/v2/article/getArticleByViewsNum', {
        gender: gender,
        page: page,
        limit: limit
    }, {cache: true}).then(res => {

        let list = [];

        if (res && res.data) {
            for (let i = 0; i < res.data.length; i++) {
                let it = res.data[i];

                let reco = {
                    url: ghelper.getArticleUrl(it.url, it.id),
                    title: it.title
                };

                if (it.src) {
                    reco.img = helpers.image(it.src, 90, 60, 1);
                }

                list.push(reco);
            }
        }

        return list;
    });
};

/**
 * 获取作者信息
 */
const getAuthor = authorId => {

    return serviceApi.get('guang/service/v1/author/getAuthor', {
        author_id: authorId
    }, {
        cache: 3600
    }).then(res => {
        if (res && res.data) {
            let d = res.data;

            return {
                authorId: authorId,
                avatar: d.avatar,
                name: d.name,
                intro: d.author_desc,
                authorUrl: d.name ? helpers.urlFormat('/Index/editor', {author_id: authorId }, 'guang') : ''
            };
        }
    });
};

/**
 * 获取文章基本信息,文章标题(不含内容)
 */
const getArticleInfo = aid => {
    return serviceApi.get('guang/service/v2/article/getArticle', {
        article_id: aid
    }, {cache: true}).then(res => {
        if (res && res.code === 200 && res.data) {
            let d = res.data;
            let tags = [];

            if (d.tags) {
                for (let i = 0; i < d.tags.length; i++) {
                    tags.push(_formatTag(d.tags[i]));
                }
            }

            return {
                title: d.article_title,
                time: moment(d.publish_time * 1000).format('YYYY年MM月DD HH:mm'),
                click: d.pageViews,
                shareImg: helpers.image(d.cover_image, 600, 600),
                desc: d.article_summary,
                authorId: d.author_id,
                weixinUrl: d.url,
                tag: d.tag,    // tags 的字符串
                tags: tags
            };
        }
    });
};

const _formatProduct = (products, arr) => {
    let result = [];

    _.forEach(products, val => {

        let goods = {
            thumb: helpers.image(val.default_images, 235, 314),
            name: val.product_name,
            salesPrice: val.sales_price,
            url: helpers.getUrlBySkc(val.product_id, val.goods_list[0].goods_id, val.cn_alphabet)
        };

        if (val.market_price !== val.sales_price) {
            goods.marketPrice = val.market_price;
        }

        _.forEach(arr, (v, k) => {
            if (k === val.product_skn) {
                goods.thumb = helpers.image(v, 235, 314);
            }
        });

        result.push(goods);
    });

    return result;
};

/**
 * 按照skn string 来查询 query=skn1,skn2,skn3
 */
const getProductList = (params, arr) => {

    return yohoApi.get('', _.assign({
        method: 'web.search.search',
        order: 's_n_desc',
        limit: 60
    }, params)).then(ret => {
        if (ret && ret.code === 200 && ret.data && ret.data.product_list) {
            return _formatProduct(ret.data.product_list, arr);
        }
    });
};

const _articleContentFormat = {
    goods: goods => {

        let productSkn = [],
            arr = {};

        _.forEach(goods, val => {
            productSkn.push(val.id);
            arr[val.id] = val.src;
        });

        if (productSkn.length > 0) {

            return getProductList({
                query: productSkn.join(',')
            }, arr);

        }

        return null;
    },
    goodsGroup: goodsGroup => {

        let result = [];

        _.forEach(goodsGroup, val => {
            if (val && val.list) {

                let productSkn = [];
                let arr = {};

                for (let it of val.list) {
                    productSkn.push(it.id);
                    arr[it.id] = it.src;
                }

                if (productSkn.length) {
                    // 包含多个对象,每对象里list都取数据,最终每个list只取前4个
                    result.push(getProductList({
                        query: productSkn.join(',')
                    }, arr).then(products => {

                        let pl = [];

                        if (products && _.isArray(products)) {
                            pl = products.slice(0, 4);
                        }

                        return pl;
                    }));
                }
            }
        });

        return result;
    },
    text: data => {
        return data;
    },
    singleImage: data => {
        if (data && data[0] && data[0].src) {
            return {
                pic: helpers.image(data[0].src, 640, 640)
            };
        }
        return null;
    },
    smallPic: data => {
        let result = {
            smallPic: []
        };

        _.forEach(data, (it, key) => {
            if (key < 2) {
                result.smallPic.push(helpers.image(it.src, 600, 600));
            }
        });
        return result;
    },
    link: () => ({})
};

/**
 * 获取文章内容详情
 */
const getArticleContent = aid => {

    let content = [],
        index = 0;

    return serviceApi.get('guang/service/v2/article/getArticleContent', {
        article_id: aid
    }, {cache: true}).then(res => {    // 内容内推荐的商品

        let gpromises = [], ggpromises = [];

        if (res && res.code === 200 && res.data) {
            _.forEach(res.data, (it) => {

                _.forEach(it, (val, key) => {
                    if (key === 'goods') {
                        gpromises.push(_articleContentFormat.goods(val.data));
                    } else if (key === 'goodsGroup') {
                        // 可能包含多个list,则有多个promise
                        ggpromises = ggpromises.concat(_articleContentFormat.goodsGroup(val.data));
                    } else {
                        let other = _.isFunction(_articleContentFormat[key]) ?
                                    _articleContentFormat[key](val.data) : '';

                        content.push(other);
                    }
                });
            });
        }

        index = gpromises.length;
        return Promise.all(gpromises.concat(ggpromises));

    }).then(res => {

        let goods = _.filter(_.flatten(res.slice(0, index)), function(it) {
            return it;
        });

        let goodsGroup = _.filter(_.flatten(res.slice(index)), function(it) {
            return it;
        });

        if (goods.length > 0) {
            content.push({
                relatedReco: {
                    recos: goods
                }
            });
        }

        if (goodsGroup.length > 0) {
            content.push({
                relatedReco: {
                    recos: goodsGroup
                }
            });
        }

        return content;
    });
};

/**
 * 判断用户是否收藏文章地址,应该是文章与用户关联的信息
 * @param $articleId
 * @param $uid
 * @param $udid
 * @param bool $onlyUrl
 * @return mixed
 */
const getArticleBaseInfo = (aid, uid, udid) => {
    return serviceApi.get('guang/api/v1/article/getArticleBaseInfo', {
        id: aid,
        uid: uid,
        udid: udid
    }).then(res => ({
        isLike: res && res.isPraise === 'Y',
        likeNum: res.praise_num || 0,
        isCollected: res && res.isFavor === 'Y'
    }));
};

/**
 * 文章相关品牌
 * @param $articleId
 * @param bool $onlyUrl
 * @return mixed
 */
const getArticleRelateBrand = aid => {
    return serviceApi.get('guang/service/v2/article/getBrand', {
        article_id: aid
    }, {cache: true}).then(res => {

        if (res && res.code === 200 && res.data) {
            return _.map(res.data, it => {
                it.thumb = it.thumb;
                it.url = it.url;
                return it;
            });
        }

    });
};

/**
 * 相关文章列表
 * @param $articleId
 * @param $tag
 * @param int $limit
 * @param bool $onlyUrl
 * @return mixed
 */
const getRelateArticleList = (aid, tag, size) => {
    size = size || 3;

    return serviceApi.get('guang/service/v2/article/getOtherArticle', {
        article_id: aid,
        tags: tag,
        limit: size
    }, {cache: true}).then(res => {
        if (res && res.code === 200 && res.data) {
            return _.map(res.data, it => {
                it.thumb = helpers.image(it.thumb, 264, 173, 1);
                it.url = ghelper.getArticleUrl(it.url, it.id);
                return it;
            });
        }
    });
};

/**
 * 获取文章评论数据
 */
const getArticleComments = (aid, page, pageSize) => {
    page = page || 1;
    pageSize = pageSize || 20;

    return serviceApi.get('guang/api/v1/comments/getList', {
        article_id: aid,
        page: page,
        pageSize: pageSize
    }).then(res => {

        let num = (res.data && res.data.total) || 0;
        let list = [];

        if (num > 0 && res.data.list) {
            let iList = res.data.list;

            for (let i = 0; i < iList.length; i++) {
                let it = iList[i];

                list.push({
                    avatar: helpers.image(it.avator, 100, 100),
                    name: it.username,
                    content: it.content,
                    time: it.create_time
                });
            }
        }

        return {
            commentNum: num,
            list: list
        };
    });
};

/**
 * 文章评论提交
 * @param $id
 * @param $uid
 * @return mixed
 */
const addComment = (aid, uid, content) => serviceApi.get('guang/api/v1/comments/add', {
    article_id: aid,
    uid: uid,
    content: content
}).then(res => {
    if (res && res.code === 200) {
        return res.data;
    } else {
        return Promise.reject('评论失败');
    }
});

/**
 * 文章点赞
 * @param $id
 * @param $uid
 * @return mixed
 */
const praise = (aid, udid) => serviceApi.get('guang/api/v2/praise/setPraise', {
    article_id: aid,
    udid: udid
});

/**
 * 文章点赞
 * @param $id
 * @param $uid
 * @return mixed
 */
const cancelPraise = (aid, udid) => serviceApi.get('guang/api/v2/praise/cancel', {
    article_id: aid,
    udid: udid
});

/**
 * 收藏文章
 * @param $id
 * @param $uid
 * @return mixed
 */
const collect = (aid, uid) => serviceApi.get('guang/api/v1/favorite/setFavorite', {
    article_id: aid,
    uid: uid
});

/**
 * 取消收藏文章
 * @param $id
 * @param $uid
 * @return mixed
 */
const cancelCollect = (aid, uid) => serviceApi.get('guang/api/v1/favorite/cancelFavorite', {
    article_id: aid,
    uid: uid
});

/**
 * 获取制指定文章的动态信息
 * @param ids
 * @returns {Promise.<T>|*}
 */
const getDynamicDataById = id => {
    return serviceApi.get('', {
        id: id
    }).then(res => {

        if (res && res.code === 200 && res.data) {
            return res.data;
        }

        return Promise.reject('获取失败');
    });
};

/**
 * 获取制指定文章的动态信息
 * @param ids
 * @returns {Promise.<T>|*}
 */
const getDynamicDataByIds = ids => {
    return serviceApi.get('', {
        ids: ids
    }).then(res => {

        if (res && res.code === 200 && res.data) {
            return res.data;
        }

        return Promise.reject('获取失败');
    });
};

module.exports = {
    getArticleList,
    getHotTags,
    getAds,
    getBanner,
    getCategory,
    getRecoArticles,
    getPathNav,
    getAuthor,

    getArticleInfo,
    getArticleContent,
    getArticleBaseInfo,
    getArticleRelateBrand,
    getRelateArticleList,
    getArticleComments,

    addComment,
    praise,
    cancelPraise,
    collect,
    cancelCollect,

    getDynamicDataById,
    getDynamicDataByIds
};