group-service.js 15.2 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
const GroupApi = require('./group-api');
const _ = require('lodash');
const utils = '../../../utils';
const filterProcess = require(`${utils}/group-filter-process`);
const isProd = process.env.NODE_ENV === 'production';
const contentCodes = {
    test: {
        home: 'ae00dffeb10f417887c433057b0af8bb',
        ready: '89141506b9926010f28915a82b3db61d',
        result: '3c3a94fd6c6e19508b6921acd7f6cbad',
        detail: 'cea0efae77f4e04c935beb1e87181247'
    },
    production: {
        home: '4b24541678c9fe0ca12c8fd205a6d427',
        ready: '89141506b9926010f28915a82b3db61d',
        result: '3c3a94fd6c6e19508b6921acd7f6cbad',
        detail: 'cea0efae77f4e04c935beb1e87181247'
    }
} [isProd ? 'production' : 'test'];

const newContentCodes = {
    test: {
        homeTab: 'cbdd29c609017c2803d46d99bd17a33a',
        home: '7744d415ea1a9da42398b27a1376a879',
        ready: '89141506b9926010f28915a82b3db61d',
        result: '3c3a94fd6c6e19508b6921acd7f6cbad',
        detail: 'cea0efae77f4e04c935beb1e87181247'
    },
    production: {
        homeTab: 'cbdd29c609017c2803d46d99bd17a33a',
        home: '7744d415ea1a9da42398b27a1376a879',
        ready: '89141506b9926010f28915a82b3db61d',
        result: '3c3a94fd6c6e19508b6921acd7f6cbad',
        detail: 'cea0efae77f4e04c935beb1e87181247'
    }
} [isProd ? 'production' : 'test'];

class GroupService extends global.yoho.BaseModel {
    constructor(ctx) {
        super(ctx);
        this.api = new GroupApi(ctx);
    }

    async newIndex(content_code) {
        try {
            const result = await this.api._getResourceCode({
                contentCode: content_code || newContentCodes.homeTab
            });

            return result;
        } catch (e) {
            return {
                error: e
            };
        }
    }

    async index() {
        try {
            const result = await this.api._getResourceCode({
                contentCode: contentCodes.home
            });

            return result;
        } catch (e) {
            return {
                error: e
            };
        }
    }
    async readyListResource() {
        try {
            const result = await this.api._getResourceCode({
                contentCode: contentCodes.ready
            });

            return result;
        } catch (e) {
            return {
                error: e
            };
        }
    }

    async groupResult({
        groupNo,
        activityId,
        uid
    } = {}) {
        try {
            let unionType = '';
            let [unionTypeResult, detail, recommend, banner] = await Promise.all([
                this.getUnionType(uid),
                this.api.groupDetail({
                    uid,
                    groupNo
                }),
                this.api.activityRecommend({
                    uid,
                    activityId
                }),
                this.api._getResourceCode({
                    contentCode: contentCodes.result
                })
            ]);

            // pageGo状态值:
            // 1. 开团成功--准备邀请好友参团
            // 2. 尚未加入团--应好友邀请
            // 3. 已经加入团--应好友邀请
            // 4. 团已达成--你已加入一起购买成功
            // 5. 团已达成--你来晚了没能加入
            // 6. 拼团失败--过期未达成[非自己所开团]
            // 7. 拼团失败--过期未达成[自己所开团]
            let yourJoinItem = detail.yourJoinItem;
            let lackNum = detail.lackNum;
            let membershipItems = detail.membershipItems;

            if (!yourJoinItem) {
                detail.yourJoinItem = membershipItems[0];
            }

            for (let i = 0; i < +lackNum; i++) {
                detail.membershipItems.push({
                    empty: true
                });
            }

            if (unionTypeResult.unionType) {
                unionType = unionTypeResult.unionType;
            }

            return {
                ...detail,
                recommend,
                bannerResource: banner,
                unionType
            };

        } catch (e) {
            return {
                error: e
            };
        }
    }


    async productData(params = {}) {
        let options = {
            data: {
                method: 'app.product.data',
                product_skn: params.productSkn
            }
        };

        return this.get(options).then(result => {
            return result;
        });
    }

    async groupResultRec({
        activityId,
        uid,
        page,
        limit
    } = {}) {
        try {
            const recommend = await this.api.activityRecommend({
                uid,
                activityId,
                limit,
                page
            });

            return {
                ...recommend
            };

        } catch (e) {
            return {
                error: e
            };
        }
    }
    async groupIndex() {
        let result = {};

        result.index = await this.index();
        result.tabData = await this.tabData();
        result.shareInfo = await this.getShareInfo({
            share_id: 6737
        });
        result.filterGroupList = await this.filterGroupList({
            joinLimit: result.tabData.joinLimit || 1
        });
        return result;
    }

    async newGroupIndex(tabIndex) {
        let result = {};
        let tabCurrentIndex = tabIndex || 0;

        result.index = await this.newIndex() || [];
        result.shareInfo = await this.getShareInfo({
            share_id: 6737
        });
        let filters = [];

        result.index.forEach(item => {
            if (item.template_name === 'guessLike') {
                filters = item.data;
            }
        });

        filters.forEach(item => {
            item.queryString = JSON.stringify(item.query);
        });

        let indexFilter = filters[tabCurrentIndex] || { query: [] };
        let query = {};

        indexFilter.query.forEach(item => {
            query = Object.assign(query, item);
        });
        let code = indexFilter.resources_code;

        result.floors = code && await this.newIndex(code);
        result.filterGroupList = await this.filterGroupList({
            ...query
        });

        return result;
    }

    async goodsTab(query, result = {}) {
        result.filterGroupList = await this.filterGroupList({
            ...query,
        });
        return result;
    }

    async groupListIndex(params, uid) {
        let result = {};

        // 兼容小程序的type配置 type为4则显示即将开始列表
        if (!params.showType) {
            params.showType = params.type === '4' ? '2' : '1';
        }
        result.showType = params.showType; // 1、只展示已开始的 2、只展示即将开始的 3、展示全部
        result.groupList = await this.groupList(params);
        result.readyListResource = result.showType === '2' && await this.readyListResource();

        // 登录后获取分享信息
        if (uid !== 0) {
            // let share_id = await this.getShareId(uid);
            let unionType = await this.getUnionType(uid);

            result.unionType = unionType;
            let share_id = isProd ? 5409 : 1124; // 线上:5409 ;测试:1124;

            result.shareInfo = await this.getShareInfo({
                share_id
            });
        } else {
            result.shareInfo = '';
            result.unionType = '';
        }
        return result;
    }

    async getUnionType(uid) {
        try {
            const result = await this.api._getShareId({
                uid
            });

            return result.unionType || '';
        } catch (e) {
            return {
                error: e
            };
        }
    }

    async getShareId(uid) {
        try {
            const result = await this.api._getShareId({
                uid
            });

            return result.shareId;
        } catch (e) {
            return {
                error: e
            };
        }
    }

    async tabData() {
        const result = await this.api._getPromoteCount();
        let tabsData = {};
        let {
            newGroup = 0, normalGroup = 0
        } = result;

        if (+newGroup && +normalGroup) {
            tabsData.showTab = true;
        } else if (+newGroup) {
            tabsData.joinLimit = 1;
        } else if (+normalGroup) {
            tabsData.joinLimit = 2;
        }
        return tabsData;
    }
    async filterData(params) {
        let result = await this.api._getFilterData(params);

        return filterProcess.processFilter(result.filter || []);
    }

    async filterGroupList(params) {
        const initParams = {
            page: 1,
            limit: 20,
            order: ''
        };
        let newParams = {
            ...initParams,
            ...params
        };


        const result = await this.api._getPromoteList(newParams);
        let finalResult = {};

        if (_.get(result, 'list')) {
            finalResult = result.list;

            _.forEach(finalResult, (val) => {
                val.sales_price = val.sales_price ? val.sales_price.toFixed(2) : '';
                val.market_price = val.market_price ? val.market_price.toFixed(2) : '';
                val.collagePrice = val.collagePrice ? val.collagePrice.toFixed(2) : '';
                val.joinLimitStr = val.join_limit === 1 ? '邀新团' : '普通团';
                // eslint-disable-next-line max-len
                val.joinPeopleNum = val.joinPeopleNum > 10000 ? (val.joinPeopleNum / 10000).toFixed(1) + '万' : val.joinPeopleNum;
            });
        }
        return finalResult;
    }

    async groupList(params) {
        const initParams = {
            page: 1,
            limit: 20,
            activityId: '',
            showType: 1 // 默认显示已开始的
        };
        let newParams = {
            ...initParams,
            ...params
        };

        try {
            const result = await this.api._getGroupList(newParams);
            let finalResult = {};

            if (result.banner && result.banner.length > 0) {
                let imagePath = result.banner;
                let imageUrl = result.jumpUrl;

                finalResult.banner = {
                    imageUrl,
                    imagePath
                };
            }
            if (_.get(result, 'collageProductVoList')) {
                finalResult.activityList = result.collageProductVoList;

                _.forEach(finalResult.activityList, (val) => {
                    val.salesPrice = val.salesPrice ? val.salesPrice.toFixed(2) : '';
                    val.marketPrice = val.marketPrice ? val.marketPrice.toFixed(2) : '';
                    val.collagePrice = val.collagePrice ? val.collagePrice.toFixed(2) : '';
                    val.beginTimeText = this.formatTimeByDefined(val.beginTime, 'M月D日');
                });
            }
            return finalResult;
        } catch (e) {
            return {
                error: e
            };
        }
    }
    async getShareInfo(params) {
        try {
            return await this.api._getShareInfo(params);
        } catch (e) {
            return {
                error: e
            };
        }
    }
    async goodsDetail(params, uid) {
        let result = await this.api.getProductData(params);

        if (uid !== 0) {
            let unionType = await this.getUnionType(uid);

            result.unionType = unionType;
        }
        if (result.shop_id) {
            result.storeUrl = `/shop/${_.get(result, 'brand_info.brand_domain')}-${_.get(result, 'shop_id')}.html`;
        }
        result.shopInfo = await this.api.getShopInfo({
            brand_id: result.brand_id,
            shop_id: result.shop_id
        });
        result.activityIdDetail = await this.api.getCollageProductInfo(params);

        if (!result.activityIdDetail.peopleNum) {
            result.activityIdDetail.peopleNum = 0;
        }
        result.activityGroupDetailList = await this.api.fetchActivityGroups(params);
        result.support = await this.api.getSupport(params);
        result.floor = await this.api._getResourceCode({
            contentCode: contentCodes.detail
        });
        for (let item of result.activityGroupDetailList) {
            item.formatLeftTime = this.formatDate(item.leftTime);
        }
        result.introUrl = '/product/detail/intro/' + params.productSkn;
        return result;
    }

    async order({
        type,
        page,
        limit,
        uid
    }) {
        try {
            const result = await this.api.getOrderList({
                limit,
                page,
                type,
                uid
            });

            const reasons = await this.api.getRefundApplyReasons({
                uid
            });

            result.order_list = result.order_list.map((item) => {
                reasons.forEach(reason => {
                    if (item.refund_status === reason.id) {
                        item.refund_status_str = reason.reason;
                    }
                });
                return item;
            });

            result.reasons = reasons;
            return result;
        } catch (error) {
            return {
                error: error
            };
        }
    }

    async delOrder({
        orderCode,
        uid
    }) {
        try {
            const result = await this.api.delOrder({
                orderCode,
                uid
            });

            return result;
        } catch (error) {
            return {
                error: error
            };
        }
    }

    async cancelOrder({
        orderCode,
        uid
    }) {
        try {
            const result = await this.api.cancelOrder({
                orderCode,
                uid
            });

            return result;
        } catch (error) {
            return {
                error
            };
        }
    }

    add0(m) {
        return m < 10 ? '0' + m : m;
    }

    formatDate(shijianchuo) {
        // 秒数
        let second = Math.floor(shijianchuo);

        // 小时位
        let hr = Math.floor(second / 3600);

        // 分钟位
        let min = Math.floor((second - hr * 3600) / 60);

        // 秒位
        let sec = (second - hr * 3600 - min * 60);

        return this.add0(hr) + ':' + this.add0(min) + ':' + this.add0(sec);
    }

    /**
     * 时间戳转化为年 月 日 时 分 秒
     * time: 传入时间戳
     * format:返回格式,支持自定义,但参数必须与formateArr里保持一致
     * formatTimeByDefined(1488481383,'Y/M/D h:m:s') => 2017/03/03 03:03:03
     */
    formatTimeByDefined(time, format) {

        var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
        var returnArr = [];

        var date = new Date(time * 1000);
        var i = 0;

        returnArr.push(date.getFullYear());
        returnArr.push(this.add0(date.getMonth() + 1));
        returnArr.push(this.add0(date.getDate()));

        returnArr.push(this.add0(date.getHours()));
        returnArr.push(this.add0(date.getMinutes()));
        returnArr.push(this.add0(date.getSeconds()));

        for (i; i < returnArr.length; i++) {
            format = format.replace(formateArr[i], returnArr[i]);
        }
        return format;
    }
}

module.exports = {
    GroupService
};