list.js 20.6 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
/**
 * 品类|品牌|店铺 controller
 * @author: wsl<shuiling.wang@yoho.cn>
 * @date: 2016/7/21
 */

'use strict';
const utils = '../../../utils';
const mRoot = '../models';
const headerModel = require('../../../doraemon/models/header');
const listModel = require(`${mRoot}/list`);
const _ = require('lodash');
const md5 = require('yoho-md5');
const co = Promise.coroutine;
const helpers = global.yoho.helpers;
const productProcess = require(`${utils}/product-process`);
const searchModel = require(`${mRoot}/search`);
const shopModel = require(`${mRoot}/shop`);
const searchProcess = require(`${utils}/search-process`);
const stringProcess = require(`${utils}/string-process`);
const listParamsProcess = require(`${utils}/list-params-process`);
const redis = require(`${utils}/redis`);
const logger = global.yoho.logger;

/**
 * 封面图
 * @type {{boys: string, gilrs: string}}
 */
const _coverChannel = {
    boys: '1,3',
    gilrs: '2,3'
};

/**
 * 从 useragent 获取 uid
 * @returns {*}
 * @private
 */
const _getUidFromUserAgent = (req) => {
    let userAgent = _.split(req.headers['user-agent'], ';');
    let uidString = '';

    _.forEach(userAgent, value => {
        if (_.startsWith(value, 'uid')) {
            uidString = value;
            return;
        }
    });

    return _.split(uidString, '=')[1];
};

/**
 * 店铺 - 基础模板
 */
const _baseShop = (req, res, shopInfo, shopId) => {

    req.ctx(listModel).getBaseShopData(Object.assign(req.query, {
        channel: req.yoho.channel
    }), shopInfo).then(result => {
        if (result && result.baseShopHome && result.baseShopHome.banner) {
            if (result.baseShopHome.banner.indexOf('?') < 0) {
                result.baseShopHome.banner += '?imageMogr2/auto-orient/strip/thumbnail/x150/crop/640x150';
            }
        }

        res.render('search/goods-list', Object.assign({
            module: 'product',
            page: 'search-list',
            pageHeader: headerModel.setNav({
                navTitle: result.shopName
            }),
            goodList: result,
            showDownloadApp: true,
            pageFooter: true,
            shopId: shopId,
            shopPage: true
        }, result.seoResult));
    });

};

/**
 *
 * 基础模板收藏
 */
const baseShopFav = (req, res) => {
    let allowOrigin = _.get(req, 'headers.origin', null) ?
        req.headers.origin : req.protocol + '://' + req.headers.host;

    res.setHeader('Access-Control-Allow-Origin', allowOrigin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');

    let uid = req.user.uid || req.query.uid || _getUidFromUserAgent(req);
    let shopId = req.query.shopId;

    req.ctx(listModel).getBrandFavStatus({
        uid: uid,
        id: shopId,
        type: 'shop'
    }).then(result => {
        res.json({
            code: 200,
            collect: result && result.data,
        });
    });
};


/**
 * 店铺首页
 * @return int
 */
const _shop = (req, res, shopId) => {
    let isApp = req.query.app_version || req.query.appVersion || false;
    let pageHeader = {};
    let uid = req.user.uid || req.query.uid;

    // pagecache前端判断
    if (!isApp) {
        pageHeader = {
            pageHeader: _.assign({
                shopPage: {
                    text: '分类',
                    url: helpers.urlFormat('/product/index/category', {
                        shop_id: shopId
                    })
                }
            }, headerModel.setNav({
                navTitle: false
            }))
        };
    }

    req.ctx(listModel).getShopData(req, shopId, uid, isApp).then(result => {
        if (result.goBrand) {

            /* 若店铺使用基础模板跳转基础模板 */
            _baseShop(req, res, result.goBrand, shopId);
        } else {
            req.ctx(searchModel).searchProductBySkn(result.hotListproductSkn).then(hotList => {
                result = _.assign(result, pageHeader, {
                    hotList: productProcess.processProductList(hotList, {isApp: isApp})
                });

                _.forEach(result.hotList, (value, key) => {
                    result.hotList[key].tags = {};
                    result.hotList[key].is_soon_sold_out = false;
                    result.hotList[key].tags.is_hot = true;
                });

                // 有领券功能,不缓存
                res.set('Cache-Control', 'no-cache');

                res.render('shop/index', Object.assign({
                    module: 'product',
                    page: 'shop',
                    shopIndex: result,
                    shopHeadHide: true,
                    gender: req.query.gender,
                    channel: req.query.channel,
                    shopId: shopId,
                    shopPage: true
                }, result.seoResult));

            });
        }
    });
};

/**
 * app设置cookie
 */
const shopAppCookie = (req, res) => {
    let allowOrigin = _.get(req, 'headers.origin', null) ?
        req.headers.origin : req.protocol + '://' + req.headers.host;

    res.setHeader('Access-Control-Allow-Origin', allowOrigin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');

    res.json({
        code: 200,
        msg: 'app cookie set',
    });
};

/**
 *
 * 前端请求判断shop是否收藏
 */
const shopFav = (req, res) => {
    let allowOrigin = _.get(req, 'headers.origin', null) ?
        req.headers.origin : req.protocol + '://' + req.headers.host;

    res.setHeader('Access-Control-Allow-Origin', allowOrigin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');

    let uid = req.user.uid || req.query.uid || req.cookies.appUid || _getUidFromUserAgent(req);
    let shopId = req.query.shopId;

    if (!uid || !shopId) {
        return res.json({
            code: 200,
            collect: false
        });
    }

    req.ctx(listModel).getBrandFavStatus({
        uid: uid,
        id: shopId,
        type: 'shop',
    }).then(result => {
        res.json({
            code: 200,
            collect: result && result.data
        });
    });
};

// 品类落地页
const category = (req, res, next) => {
    if (req.query) {
        _.forEach(req.query, (perParam, index) => {
            req.query[index] = stringProcess.paramsFilter(perParam);
        });
    }

    let params = Object.assign({}, req.query);
    let seoTitle;

    if (req.query.title || req.query.sort_name) {
        seoTitle = stringProcess.decodeURIComponent(req.query.title || req.query.sort_name);
    }

    /* 勿修改,唤起 APP 使用 */
    let appParams = Object.assign({}, req.query, {
        title: req.query.title || req.query.sort_name || '',
        productPool: req.query.filter_poolId,
        actiontype: req.query.actiontype || '1'
    });

    delete appParams.filter_poolId;

    let appPath = 'yohobuy://yohobuy.com/goapp?openby:yohobuy={"action":"go.list","params":' +
        JSON.stringify(appParams) +
        '}';

    let uid = req.user.uid || 0;

    // 获取第一页数据做服务端渲染
    let initialData = _.assign({
        gender: params.gender,
        sort: parseInt(params.sort, 10) || '',
        type: 'default',
        order: '0',
        page: 1,
        limit: 24,
        isApp: params.app_version
    }, params);

    if (uid) {
        initialData.uid = uid;
    }

    req.ctx(searchModel).getSearchData(initialData).then((firstPageGoods) => {
        res.render('search/goods-list', Object.assign({
            _noLazy: true, // 首屏不使用lazyload
            module: 'product',
            page: 'search-list',

            // canonical: {
            //     currentHref: 'https://www.yohobuy.com/list?' // TODO
            // },
            pageHeader: headerModel.setNav({
                navTitle: seoTitle || '商品列表'
            }),
            goodList: params,
            firstPageGoods: firstPageGoods || [],
            suggestion: firstPageGoods.suggestion || [],
            showDownloadApp: true,
            pageFooter: true,
            category: true,
            localCss: true,
            appPath: appPath,
            introText: req.query.intro_text
        }, searchProcess.getListSeoData({
            gender: req.query.gender,
            sort_name: seoTitle
        })));
    }).catch(next);
};

/**
 * 品类落地页 SEO 友好的新路由
 */
const listNew = (req, res, next) => {
    let queryParams = req.query;

    // 1. 取 path 的参数
    req.query = listParamsProcess.getParams(req.path);

    // 2. 取查询字符串参数
    _.assign(req.query, queryParams);

    if (req.query) {
        _.forEach(req.query, (perParam, index) => {
            req.query[index] = stringProcess.paramsFilter(perParam);
        });
    }

    let params = _.assign({}, req.query);

    /* 勿修改,唤起 APP 使用 */
    let appParams = _.assign({}, req.query, {
        title: req.query.title || req.query.sort_name || '',
        productPool: req.query.filter_poolId,
        actiontype: req.query.actiontype || '1'
    });

    delete appParams.filter_poolId;

    let appPath = 'yohobuy://yohobuy.com/goapp?openby:yohobuy={"action":"go.list","params":' +
        JSON.stringify(appParams) +
        '}';

    let uid = req.user.uid;

    // 获取第一页数据做服务端渲染
    let initialData = _.assign({
        gender: params.gender,
        type: 'default',
        order: '0',
        page: 1,
        limit: 24,
        isApp: params.app_version
    }, params);

    if (uid) {
        initialData.uid = uid;
    }

    co(function* () {
        let result = yield req.ctx(searchModel).getCategoryGoods(initialData);
        let categoryIntroRedis = [];

        let responseResult = {
            list: productProcess.processProductList(_.get(result, 'data.product_list', []), {
                isApp: params.isApp || (params.appVersion && params.appVersion !== 'false'),
                gender: _coverChannel[params.coverChannel],
                showSimilar: params.shop_id || params.material === 'true' ? false : true
            })
        };
        let seoParams = searchProcess.getFilterValueForSeo(initialData, _.get(result, 'data', {}));
        let seoRenderData = searchProcess.getListSeoData(seoParams);
        let seoTitle = _.get(seoParams, 'sort');
        let paramsTitle = params.title || params.sort_name; // 可能会配置的标题,优先级最高

        if (paramsTitle) {
            seoTitle = stringProcess.decodeURIComponent(paramsTitle);
        }

        try {
            categoryIntroRedis =
                yield redis.hmgetAsync(`category:description:${md5(seoTitle)}`, 'category', 'description').timeout(200);
        } catch (e) {
            logger.error('redis.hmgetAsync.category.description:' + e);
        }

        let categoryIntro = categoryIntroRedis[1] ? {
            title: categoryIntroRedis[0],
            desc: categoryIntroRedis[1]
        } : null;

        res.render('search/list-new', Object.assign({
            _noLazy: true, // 首屏不使用lazyload
            module: 'product',
            page: 'search-list-new',
            canonical: {
                currentHref: `https://www.yohobuy.com${req.url}`
            },
            pageHeader: headerModel.setNav({
                navTitle: seoTitle || '商品列表'
            }),
            goodList: params,
            firstPageGoods: responseResult || [],
            pageFooter: true,
            localCss: true,
            appPath: appPath,
            categoryIntro: categoryIntro
        }, seoRenderData));
    })().catch(next);
};

/**
 * SEO 友好的品类落地页异步获取商品数据
 */
const getCategoryGoods = (req, res, next) => {
    let allowOrigin = _.get(req, 'headers.origin', null) ?
        req.headers.origin : req.protocol + '://' + req.headers.host;

    res.setHeader('Access-Control-Allow-Origin', allowOrigin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');

    let currentUrlParams = listParamsProcess.getParams(req.query.currentUrl);

    delete req.query.currentUrl;

    let params = _.assign({}, currentUrlParams, req.query);
    let uid = req.user.uid || 0;

    if (uid) {
        params.uid = uid;
    }

    params.isApp = req.yoho.isApp;
    params.limit = 24;

    req.ctx(searchModel).getCategoryGoods(params).then((result) => {
        let productList = _.get(result, 'data.product_list', []);

        if (productList.length > 0) {
            let product_list = productProcess.processProductList(productList, {
                isApp: params.isApp || (params.appVersion && params.appVersion !== 'false'),
                gender: _coverChannel[params.coverChannel],
                showSimilar: params.shop_id || params.material === 'true' ? false : true
            });

            res.render('search/page', {
                layout: false,
                new: product_list,
                total: _.get(result, 'data.total', 0)
            });
        } else {
            res.json({});
        }
    }).catch(next);
};

/**
 * 品牌店铺的入口
 * @param req
 * @param res
 * @param next
 */
const brand = (req, res, next) => {
    let params = Object.assign({}, req.query);
    let domain = req.query.domain;
    let uid = req.user.uid;
    let brandId = 0;
    let brandLogo = {};
    let title = '';

    /* tar add 160909 如果有 shop_id 直接跳转 */
    if (req.query.shop_id) {
        _shop(req, res, req.query.shop_id);
        return;
    }

    if (!domain) {
        res.redirect('/?go=1');
        return;
    }

    req.ctx(shopModel).getBrandLogoByDomain(domain).then(result => {
        if (!result) {
            return next();
        }

        brandLogo = result;

        title = brandLogo.name;

        if (brandLogo && brandLogo.id) {
            brandId = brandLogo.id;
        }

        params = _.assign({
            brand: brandId
        }, params);

        // 无店铺:0--->品牌页 无单品店有多品店:1--->搜索页 有单品店:2--->店铺页面
        if (req.query.from !== 'search' && brandLogo.type === '2' && brandLogo.shopId) {
            _shop(req, res, brandLogo.shopId);
        } else { // 获取品牌店铺信息
            req.ctx(listModel).getBrandShops(brandId, req).then(brandShop => {
                if (brandId === 0) {
                    params.query = domain;
                }

                params.seoResult = brandShop.seoResult;

                // 从搜索页过来的,显示搜索框, 和进入品牌引导信息 或者品牌关联多店铺
                if (req.query.from === 'search' || brandShop.length > 0) {
                    params = _.assign({
                        brandWay: _.isEmpty(brandShop) ? brandLogo : brandShop,
                        search: {
                            default: req.query.query,
                            url: helpers.urlFormat('', null, 'search')
                        }
                    }, params);
                } else if (brandId && brandId !== 0 &&
                    brandId !== '' && brandId !== 'undefined') { // 品牌一览过来的展示品牌介绍和LOGO
                    return Promise.all([req.ctx(shopModel).getBrandIntro(brandId, uid), req.ctx(shopModel).getBrandBanner(brandId)]).then((resData) => { //eslint-disable-line
                        title = resData[0].title;
                        delete resData[0].title;

                        return _.assign({
                            banner: resData[1]
                        }, resData[0]);
                    });
                }
            }).then(brandHome => {
                params.brandHome = brandHome;

                if (!brandHome || !brandHome.id) {
                    res.set('Cache-Control', 'no-cache');
                }

                res.render('search/goods-list', Object.assign({
                    module: 'product',
                    page: 'search-list',
                    pageHeader: headerModel.setNav({
                        navTitle: title !== '' ? title : domain
                    }),
                    goodList: params,
                    showDownloadApp: true,
                    pageFooter: true,
                    domain: req.query.domain,
                    shopPage: true
                }, params.seoResult));
            });
        }
    }).catch(next);
};

/**
 *
 * @param req
 * @param res
 */
const brandFav = (req, res) => {
    let domain = req.query.domain;
    let uid = req.user.uid;
    let brandId = 0;

    req.ctx(shopModel).getBrandLogoByDomain(domain).then((result) => {
        brandId = result.id;
        req.ctx(listModel).getBrandFavStatus({
            uid: uid,
            id: brandId,
            type: 'brand',
        }).then(result2 => {
            res.json(result2);
        });
    });
};

/**
 * 店铺简介
 * @param req
 * @param res
 * @param next
 */
const shopIntro = (req, res, next) => {
    let shopId = req.query.shop_id;
    let appVersion = req.body.appVersion || false;
    let params = {};

    if (parseInt(shopId, 10)) {
        req.ctx(listModel).getShopIntro(shopId).then(result => {
            if (appVersion) {
                params = {
                    title: '店铺简介'
                };
            } else {
                params = {
                    pageHeader: headerModel.setNav({
                        navTitle: '店铺简介'
                    })
                };
            }

            res.render('shop/intro', _.assign(params, result, {
                module: 'product',
                page: 'intro'
            }));
        }).catch(next);
    } else {
        res.redirect('/?go=1');
    }
};

/**
 * 品牌[店铺]收藏/取消收藏
 * id 品牌ID
 * opt 操作标识("ok":表示收藏,"cancel":表示取消收藏)
 */
const favoriteBrand = (req, res, next) => {
    let allowOrigin = _.get(req, 'headers.origin', null) ?
        req.headers.origin : req.protocol + '://' + req.headers.host;

    res.setHeader('Access-Control-Allow-Origin', allowOrigin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');

    let id = req.query.id;
    let uid = req.user.uid || req.query.uid;
    let opt = req.query.opt || 'ok';
    let type = req.query.type || 'product';
    let appVersion = req.query.appVersion || false;
    let refer = encodeURIComponent(req.get('referer'));

    let url = helpers.urlFormat('/signin.html') + '?refer=' + refer;


    if (appVersion && appVersion !== 'false') {
        if (!uid || uid === 'undefined') {
            uid = _getUidFromUserAgent(req);
        }

        url = `${refer}&openby:yohobuy={"action":"go.weblogin","params":{"jumpurl":{"url":"${refer}","param":{}},"requesturl":{"param":{"method":"app.favorite.add","id":"${id}","fav_id":"${id}","type":"shop"},"url":"${_.get(global, 'yoho.API.ApiUrl', '')}"},"priority":"Y"}}`; // eslint-disable-line

    }

    if (!id) {
        return res.json({
            code: 401,
            message: '参数不正确',
            data: false
        });
    }

    if (!uid) {
        return res.json({
            code: 400,
            message: '未登录',
            data: url
        });
    }

    if (opt !== 'ok') { // 取消收藏
        req.ctx(listModel).setFavoriteCancel(id, uid, type).then(result => {
            res.json(result);
        }).catch(next);
    } else {
        req.ctx(listModel).setFavorite(id, uid, type).then(result => {
            res.json(result);
        }).catch(next);
    }
};

/**
 * 店铺品类页面
 * @param req
 * @param res
 * @param next
 */
const shopCategory = (req, res, next) => {

    req.ctx(listModel).getShopCategory({
        shopId: req.query.shop_id,
        channel: req.yoho.channel,
        gender: req.query.gender || '1,3'
    }).then(result => {
        res.render('shop/category', {
            content: result,
            allProduct: result.allProduct,
            module: 'product',
            page: 'category',
            pageHeader: headerModel.setNav({
                navTitle: '品类'
            }),
        });
    }).catch(next);
};

/**
 * 获取品牌优惠券列表
 * @param req
 * @param res
 * @param next
 */
const getBrandCouponsList = (req, res, next) => {
    let allowOrigin = _.get(req, 'headers.origin', null) ?
        req.headers.origin : req.protocol + '://' + req.headers.host;

    res.setHeader('Access-Control-Allow-Origin', allowOrigin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');

    let uid = req.user.uid;
    let brandId = parseInt(req.query.brandId, 10);
    let param = {};

    if (brandId) {
        if (uid) {
            param.uid = uid;
        }

        param.brand_id = brandId;

        req.ctx(listModel).brandCouponsList(param).then(result => {
            res.json(result);
        }).catch(next);
    } else {
        res.json([]);
    }
};

module.exports = {
    category,
    brand,
    favoriteBrand,
    shopIntro,
    brandFav,
    shopAppCookie,
    shopFav,
    baseShopFav,
    shopCategory,
    getBrandCouponsList,
    listNew,
    getCategoryGoods
};