shop-service.js 23.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
/**
 * Created by TaoHuang on 2016/6/28.
 */

'use strict';
const Promise = require('bluebird');
const co = Promise.coroutine;
const _ = require('lodash');
const Api = require('./shop-api');
const SearchApi = require('./search-api');
const helpers = global.yoho.helpers;

const shopHandler = require('./shop-handler');
const searchHandler = require('./search-handler');
const listHandler = require('./list-handler');
const seoHandler = require('./seo-handler');
const headerModel = require('../../../doraemon/models/header');
const productProcess = require('../../../utils/product-process-simple');
const handleStaticUrl = require(`${global.utils}/parameter`).fullParamToMinPath;

const DEFAULT_IMG = '01091c21f2317a64f123f1649fbbccf7ba';

// 经典店铺list url
const shopListUrl = '/product/shoplist';

const needParams = ['query', 'msort', 'misort', 'category_id', 'gender', 'shelveTime'];

/**
 * channel=>gender
 */
const _getGender = (channel) => {
    let gender;

    switch (channel) {
        case 'boys':
            gender = '1,3';
            break;
        case 'girls':
            gender = '2,3';
            break;
        default:
            gender = '1,2,3';
            break;
    }

    return gender;
};


function _getShopData(channel, params, shopInfo) {
    params = params || {};

    let gender = _getGender(channel),
        shopId = params.shopId,
        domain = params.domain;
    let resData = {shopId: shopId};
    const baseUrl = `/shop/${domain}-${shopId}`;

    params.domain && delete params.domain;
    params.shopId && delete params.shopId;

    return co(function* () {
        let result = yield Promise.props({
            header: headerModel.requestHeaderData(channel), // 头部数据
            sort: this.searchApi.getSortList({shop_id: shopId}),
            decorator: this.searchApi.getShopDecorator(shopId), // 店铺装修数据
            product: this.searchApi.getProductList(Object.assign({
                shop_id: shopId,
                need_filter: 'no'
            }, params), 'shop'), // 搜索店铺商品
            brands: this.searchApi.getShopBrands(shopId), // 店铺品牌数据
            coupons: this.api.shopCouponListAsync(shopId), // 店铺优惠券数据
            shopInfo: shopInfo ? Promise.resolve(shopInfo) : this.api.getShopInfo(shopId)
        });

        if (!shopInfo) {
            shopInfo = _.get(result, 'shopInfo.data', {});
        }

        Object.assign(resData,
            result.header, // 头部数据
            searchHandler.handlePathNavData({brandName: shopInfo.shop_name}, params, 'shop', channel), // 面包屑导航
            seoHandler.getShopListSeo([], [], {shopName: shopInfo.shop_name}) // 店铺SEO
        );

        // _.set(resData, 'headerData.header', true);

        // 店铺装修
        if (result.decorator.code === 200) {
            _.set(result, 'decorator.data.domain', shopInfo.shop_domain);
            Object.assign(resData, shopHandler.getShopDecorator(result.decorator.data, params, shopId));

            _.set(resData, 'shopTopBanner.brandIntro', {
                shopId: shopId,
                brandName: shopInfo.shop_name || '',
                brandCont: shopInfo.shop_intro || ''
            });
        } else {
            return Promise.reject('No ShopDecorator data');
        }

        // 获取商品数据和顶部筛选条件
        if (result.product.code === 200) {
            let data = result.product.data;
            let allGoods = {
                name: '全部商品 ALL',
                sort: searchHandler.handleOptsData(params, _.get(data, 'total', 0)),
                list: productProcess.processProductList(_.get(data, 'product_list', []), {
                    newCoverSort: true,
                    showDiscount: false,
                    gender: gender
                }),
                href: `/product/shoplist?navBar=1&shopId=${shopId}`
            };

            _.set(allGoods, 'sort.newPage', true); // 启用新的分页导航

            resData.allGoods = allGoods;
        }

        // 店铺类目
        if (result.sort.code === 200) {
            let groupSort = _.get(result.sort, 'data', []);

            resData.leftContent = listHandler.handleSortData(groupSort, params, params, baseUrl);

            _.set(resData, 'brandShopAd', {baseUrl: baseUrl});

            if (resData.allGoods) {
                Object.assign(resData.allGoods, searchHandler.setShopSort(groupSort, Object.assign({},
                    params, {page: 1})), searchHandler.setGenderFilter(params));
            }
        }

        // 店铺优惠券
        if (result.coupons.data && !_.isEmpty(result.coupons.data)) {
            resData.coupon = searchHandler.handleBrandShopCoupons(result.coupons.data, {shopId: shopId});
        }

        let sknList = []; // 资源位配置商品skn
        let prodList = _.concat(_.get(resData, 'newArrivel.list', []),
            _.get(resData, 'hotSingle.list', []));

        _.forEach(prodList, value => {
            sknList.push(value.productSkn);
        });

        let apiMethod = [
            this.searchApi.getProductList({
                viewNum: sknList.length,
                query: _.join(_.uniq(sknList), ',')
            }, 'shop')
        ];

        // 店铺品牌
        if (result.brands.code === 200 && result.brands.data) {
            let brands = [];

            _.forEach(result.brands.data, value => {
                brands.push(value.brand_id);
            });

            resData.shopBrands = brands.join(',');
        }

        let subRes = yield Promise.all(apiMethod);

        // 设置资源位商品封面图
        if (subRes[0].code === 200) {
            let list = {};

            prodList = productProcess.processProductList(_.get(subRes[0], 'data.product_list', []), {
                newCoverSort: true,
                showDiscount: false,
                gender: gender
            });

            _.forEach(prodList, value => {
                list[value.skn] = {
                    img: value.default_images || value.thumb,
                    title: value.product_name,
                    price: ${value.sales_price}`
                };
            });

            if (_.has(resData, 'newArrivel.list')) {
                _.forEach(resData.newArrivel.list, value => {
                    if (list[value.productSkn]) {
                        Object.assign(value, list[value.productSkn]);
                    }
                });
            }

            if (_.has(resData, 'hotSingle.list')) {
                _.forEach(resData.hotSingle.list, value => {
                    if (list[value.productSkn]) {
                        Object.assign(value, list[value.productSkn]);
                    }
                });
            }
        }

        resData.trendInfo = true; // 展示店铺推荐文章

        return resData;
    }).bind(this)();
}


/**
 * 获取基础模板店铺数据
 */
function _getBaseShopData(channel, params, shopInfo) {
    params = params || {};

    let searchParams = searchHandler.getSearchParams(params);
    const shopId = params.shopId || params.shop_id;
    const domain = params.domain;
    const baseUrl = `/shop/${domain}-${shopId}`;

    params.shopId && delete params.shopId;
    params.domain && delete params.domain;

    return co(function* () {
        let result = yield Promise.props({
            header: headerModel.requestHeaderData(channel), // 头部数据
            sort: this.searchApi.getSortList({shop_id: shopId}),
            decorator: this.searchApi.getShopDecorator(shopId), // 店铺装修数据
            product: this.searchApi.getProductList(Object.assign(searchParams,
                {shop_id: shopId}), 'shop'), // 搜索店铺商品
            coupons: this.api.shopCouponListAsync(shopId), // 店铺优惠券数据
            shopInfo: shopInfo ? Promise.resolve(shopInfo) : this.api.getShopInfo(shopId)
        });

        if (!shopInfo) {
            shopInfo = _.get(result, 'shopInfo.data', {});
        }

        const shopName = shopInfo.shop_name;
        const shopAboutHref = `/shop${shopId}-about`;

        let pageIntro = _.replace(shopInfo.shop_intro || '', /<\/?[^>]*>|\s*|(\n)|(\t)|(\r)/g, ''),
            more = `... <a href="${shopAboutHref}" class="more-page-intro blue">了解更多>></a>`;

        let resData = {
            shopId: shopId,
            brand: {
                brandShopAd: true,
                pageIntro: {title: shopName, intro: _.truncate(pageIntro, {length: 300, omission: more})}
            }
        };

        Object.assign(resData, result.header);

        _.set(resData, 'brand.shopBanner', {
            shopId: shopId,
            shopName: shopName,
            shopHome: `/shop/${shopInfo.shop_domain}-${shopId}.html`,
            shopIntro: shopAboutHref
        });

        // 店铺装修
        if (result.decorator.code === 200) {
            let data = result.decorator.data || {},
                decorator = shopHandler.getShopDecorator(data, {}, shopId, true);

            Object.assign(resData.brand.shopBanner, decorator.shopTopBannerBase || {});

            // 设置店招高度
            _.set(resData, 'brand.shopBanner.bannerHeight', 150);

            if (decorator.signboard) {
                _.set(resData, 'brand.signboard', decorator.signboard);
            }
        }

        // 获取左侧类目数据
        if (result.sort.code === 200) {
            let dps = {shop_id: shopId};

            _.forEach(needParams, value => {
                if (params[value]) {
                    dps[value] = params[value];
                }
            });

            Object.assign(resData.brand, {
                leftContent: listHandler.handleSortData(result.sort.data, dps, params, baseUrl)
            });
        }

        // 获取商品数据和顶部筛选条件
        if (result.product.code === 200) {
            let data = result.product.data;
            let filters = Object.assign(listHandler.handleFilterData(data, params, baseUrl),
                _.get(resData, 'brand.leftContent.sort', {}));

            filters.checkedConditions.conditions = _.concat(filters.checkedConditions.conditions,
                _.get(resData, 'brand.leftContent.checked', []));

            Object.assign(resData.brand, {
                filters: filters,
                opts: listHandler.handleOptsData(params, data.total, data.filter, baseUrl),
                totalCount: data.total,
                footPager: listHandler.handlePagerData(data.total, params, false, baseUrl),
                goods: productProcess.processProductList(data.product_list,
                    Object.assign({showDiscount: false, from: {type: 'shop', params: params}}, params)),
                hasNextPage: listHandler.handleNextPage(params, data.total, baseUrl),

                // 最近浏览记录
                latestWalk: 7
            });

            // 店铺页不显示品牌筛选项
            _.unset(resData, 'brand.filters.brand');
        }

        // 店铺优惠券
        if (result.coupons && !_.isEmpty(result.coupons.data)) {
            _.set(resData, 'brand.coupon',
                searchHandler.handleBrandShopCoupons(result.coupons.data, {shopId: shopId}));
        }

        const sortList = _.get(resData, 'brand.leftContent.allSort.list', []);
        const checkedList = _.get(resData, 'brand.filters.checkedConditions.conditions');

        Object.assign(resData.brand, listHandler.handleListPathNavData(sortList, checkedList,
            params, channel, baseUrl));

        if (resData.brand.pathNav) {
            if (resData.brand.pathNav.length < 2) { // 无参数添加店铺名
                resData.brand.pathNav.push({name: shopName});
            } else { // 保留店铺介绍h1
                _.last(resData.brand.pathNav).useH1 = false;
            }
        }

        Object.assign(resData, seoHandler.getShopListSeo(sortList, checkedList, {shopName: shopName}));

        return resData;
    }).bind(this)();
}

function getShopInfoAsync(domain, channel, params) {
    let resData;
    let shopId = _.get(params, 'shopId');

    return co(function* () {
        let data, shopInfo;

        if (shopId) { // 带id访问
            let result = yield this.api.getShopInfo(shopId);

            data = result.data;

            // 根据店铺ID,未取到店铺信息,跳转至首页
            if (result.code !== 200 || _.isEmpty(data)) {
                return {redirect: helpers.urlFormat('')};
            }

            let lowerDomain = _.toLower(data.shop_domain);

            // 根据店铺ID取到的店铺domain与链接中domain不一致,跳转至店铺域名下(解决店铺域名与品牌域名混用的问题)
            if (lowerDomain !== domain) {
                _.unset(params, 'shopId');
                return {
                    redirect: helpers.urlFormat(`/shop/${lowerDomain}-${shopId}.html`,
                        _.isEmpty(params) ? null : params),
                    redirectType: 301
                };
            }

            shopInfo = data;
        } else { // 以店铺域名方式直接访问
            let result = yield this.searchApi.getBrandData({domain: domain});

            data = result.data;

            // 未取到domain信息,跳转至首页
            if (result.code !== 200) {
                return {redirect: helpers.urlFormat('')};
            }

            // domain类型不为店铺,跳转至搜索
            if (data.type * 1 !== 2) {
                let d = {query: domain};

                if (data.id) {
                    d.brand = data.id;
                }

                return {redirect: helpers.urlFormat('', d, 'search')};
            }

            // 没有店铺id的情况下跳转至domain-id.html
            return {
                redirect: helpers.urlFormat(`/shop/${domain}-${data.shop_id}.html`,
                        _.isEmpty(params) ? null : params),
                redirectType: 301
            };
        }

        if (+data.shop_template_type === 2) { // 经典店铺
            resData = yield this._getShopData(channel, params, shopInfo);
        } else {
            resData = yield this._getBaseShopData(channel, params, shopInfo);
        }

        return Object.assign(resData, {templateType: +data.shop_template_type});
    }).bind(this)();
}

function _getShopListData(channel, params, shopInfo) {
    let gender = _getGender(channel),
        shopId = params.shopId || params.shop_id,
        domain = params.domain,
        navBar = params.navBar || 1;
    let searchParams = searchHandler.getSearchParams(params);
    const baseUrl = `/shop/${domain}-${shopId}`;

    params.shopId && delete params.shopId;
    params.domain && delete params.domain;

    return co(function* () {
        let result = yield Promise.props({
            header: headerModel.requestHeaderData(channel), // 头部数据
            shopInfo: shopInfo ? shopInfo : this.api.getShopInfo(shopId), // 店铺介绍
            decorator: this.searchApi.getShopDecorator(shopId), // 店铺装修数据
            sort: this.searchApi.getSortList({shop_id: shopId}),
            product: this.searchApi.getProductList(Object.assign(searchParams,
                {shop_id: shopId}), 'shop'), // 搜索店铺商品

            // 如果有店内搜索,则并行查询店铺所有商品,搜索不到商品则显示所有商品
            allProduct: params.query ? this.searchApi.getProductList(Object.assign(searchParams,
                {shop_id: shopId, query: ''}), 'shop') : Promise.resolve({})
        });

        let resData = {headerData: Object.assign(result.header.headerData, {header: true})};
        let shopName = '';

        // 店铺装修
        if (result.decorator.code === 200) {
            _.set(result, 'decorator.data.domain', _.get(result, 'shopInfo.data.shop_domain'));
            Object.assign(resData, shopHandler.getShopDecorator(result.decorator.data, params, shopId));

            // 设置shop nav选中状态
            _.set(resData, `navigationBar[${navBar}].current`, true);

            if (result.shopInfo.code === 200) {
                let data = _.get(result, 'shopInfo.data', {});

                _.set(resData, 'shopTopBanner.brandIntro', {
                    shopId: shopId,
                    brandName: data.shop_name || '',
                    brandCont: data.shop_intro || ''
                });

                shopName = data.shop_name;
            }
        } else {
            return Promise.reject('No ShopDecorator data');
        }

        // 获取商品数据和顶部筛选条件
        if (result.product.code === 200) {
            let info = result.product;
            let goodsList = _.get(info, 'data.product_list', []);

            if (goodsList.length) {
                let totalPage = _.get(info, 'data.total', 1);

                Object.assign(resData, {
                    filters: listHandler.handleFilterData(info.data, params, baseUrl),
                    opts: listHandler.handleOptsData(params, totalPage, {}, baseUrl),
                    goods: productProcess.processProductList(goodsList, {
                        newCoverSort: true,
                        showDiscount: false,
                        gender: _getGender(channel),
                        query: params.query
                    }),
                    hasNextPage: listHandler.handleNextPage(params, totalPage, baseUrl),
                    footPager: listHandler.handlePagerData(totalPage, params, true, baseUrl)
                });

                if (_.has(resData, 'filters.checkedConditions')) {
                    _.set(resData, 'filters.checkedConditions.clearUrl',
                        handleStaticUrl(baseUrl, {navBar: params.navBar}));
                }
            } else {
                resData.searchEmpty = true;

                let data = _.get(result, 'allProduct.data.total', 0);
                let plist = _.get(data, 'product_list', []);

                if (params.query && plist.length) {
                    resData.allGoods = {
                        name: '全部商品 ALL',
                        sort: listHandler.handleOptsData(params, data.total || 0, {}, baseUrl),
                        list: productProcess.processProductList(plist, {
                            newCoverSort: true,
                            showDiscount: false,
                            gender: gender
                        })
                    };

                    _.set(resData.allGoods, 'sort.newPage', true); // 启用新的分页导航
                }
            }
        }

        if (result.sort.code === 200) {
            let groupSort = _.get(result.sort, 'data', []),
                noPageQs = Object.assign({}, params, {page: 1});

            resData.leftContent = listHandler.handleSortData(groupSort, noPageQs, params, baseUrl);

            _.set(resData, 'brandShopAd', {baseUrl: shopListUrl});

            if (resData.allGoods) {
                Object.assign(resData.allGoods, searchHandler.setShopSort(groupSort, noPageQs));
            }
        }


        const sortList = _.get(resData, 'leftContent.allSort.list', []);
        const checkedList = _.get(resData, 'filters.checkedConditions.conditions');

        Object.assign(resData, listHandler.handleListPathNavData(sortList, checkedList,
            params, channel, baseUrl));

        if (resData.pathNav && resData.pathNav.length < 2) { // 无参数添加店铺名
            resData.pathNav.push({
                name: shopName,
                useH1: true
            });
        }

        Object.assign(resData, seoHandler.getShopListSeo(sortList, checkedList, {shopName: shopName}));

        resData.criteo = {skn: searchHandler.getCriteo(_.get(resData, 'goods'))};

        return resData;
    }).bind(this)();
}

// 基础店铺&经典店铺共用列表
function getShopListAsync(channel, params) {
    let resData = {};

    return co(function* () {
        let result = yield this.api.getShopInfo(params.shopId);
        let shopInfo = result.data;

        // 根据店铺ID,未取到店铺信息,跳转至首页
        if (result.code !== 200 || _.isEmpty(shopInfo)) {
            return {redirect: helpers.urlFormat('')};
        }

        if (+shopInfo.shop_template_type === 2) { // 经典店铺
            resData = yield this._getShopListData(channel, params, result);
        } else {
            resData = yield this._getBaseShopData(channel, params, shopInfo);
        }

        return Object.assign(resData, {templateType: +shopInfo.shop_template_type});
    }).bind(this)();
}

function getShopGoodsData(shopId, channel, params) {
    let gender = _getGender(channel);
    let resData = {};

    _.unset(params, '_pjax');
    return Promise.all([
        this.searchApi.getProductList(Object.assign({shop_id: shopId}, params), 'shop'), // 搜索店铺商品
        this.searchApi.getSortList({shop_id: shopId}) // 根据店铺id获取分类
    ]).then(result => {
        // 获取商品数据和顶部筛选条件
        if (result[0].code === 200) {
            Object.assign(resData, {
                sort: searchHandler.handleOptsData(params, _.get(result[0], 'data.total', 0)),
                list: productProcess.processProductList(_.get(result[0], 'data.product_list', []), {
                    newCoverSort: true,
                    showDiscount: false,
                    gender: gender
                })
            });
            _.set(resData, 'sort.newPage', true); // 启用新的分页导航
        }

        if (result[1].code === 200) {
            let groupSort = _.get(result[1], 'data', []);

            Object.assign(resData, searchHandler.setShopSort(groupSort, Object.assign({}, params,
                {page: 1})), searchHandler.setGenderFilter(params));
        }

        return resData;
    });
}


module.exports = class extends global.yoho.BaseModel {
    constructor(ctx) {
        super(ctx);
        this.api = new Api(ctx);
        this.searchApi = new SearchApi(ctx);

        this._getShopData = _getShopData.bind(this);
        this._getBaseShopData = _getBaseShopData.bind(this);
        this._getShopListData = _getShopListData.bind(this);

        this.getShopInfoAsync = getShopInfoAsync.bind(this);
        this.getShopListAsync = getShopListAsync.bind(this); // 基础店铺&经典店铺共用列表
        this.getShopGoodsData = getShopGoodsData.bind(this);
    }

    getShopBannerAsync(shopId) {
        return this.api.shopBannerAsync(shopId).then((result) => {
            if (result.code === 200) {
                return _.includes(result.data.banner, DEFAULT_IMG) ? '' : result.data.banner;
            } else {
                return null;
            }
        });
    }

    queryShopByBrandIdAsync(sid, bid) {
        return co(function* () {
            let result = yield this.api.queryShopsByBrandId(sid, bid);

            if (_.get(result, 'code') !== 200) {
                return false;
            }

            return _.get(result, 'data[0]', {});
        }).bind(this)();
    }


    getShopArticleByBrandsAsync(brands) {
        let resData = {};

        brands = _.split(brands, ',');

        if (!brands.length) {
            return Promise.resolve(resData);
        }

        return Promise.all(brands.map(value => this.searchApi.getArticleByBrand(value))).then(result => {
            let articleList = [];

            for (let i = 0; i < result.length; i++) {
                articleList = _.concat(articleList, _.get(result[i], 'data', []));
            }

            if (articleList.length >= 3) {
                articleList.length = 3;

                resData.trendInfo = {
                    name: '潮流资讯 HOT ITEMS',
                    trendList: articleList.map(value => {
                        return {
                            href: helpers.urlFormat(`/guang/${value.id}.html`, null),
                            src: helpers.getForceSourceUrl(value.src) +
                            '?imageView2/1/w/{width}/h/{height}',
                            mainTitle: value.title,
                            Subtitle: value.intro
                        };
                    })
                };
            }

            return resData;
        });
    }
};