returns.js 20.5 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
/**
 *  个人中心 退换货
 *  @author chenxuan <xuan.chen@yoho.cn>
 */

'use strict';

const _ = require('lodash');

// const path = require('path');
const Promise = require('bluebird');
const returnAPI = require('./returns-api');
const ordersAPI = require('./orders-api');

const pager = require(`${global.utils}/pager`).setPager;

// 使用 product中的分页逻辑
// const pagerPath = path.join(global.appRoot, '/apps/product/models/public-handler.js');
// const pager = require(pagerPath).handlePagerData;

const co = Promise.coroutine;
const api = global.yoho.API;
const helpers = global.yoho.helpers;

// 常量
const REFUND = 1; // 退货
const EXCHANGE = 2; // 换货
const TRUE = 'Y';
const RETURNS_EMPTY = '您没有退/换货订单';
const CANCEL_REFUND_URI = '/home/returns/cancelRefund';
const CANCEL_EXCHANGE_URI = '/home/returns/cancelChange';
const REFUND_URI = '/home/returns/refundDetail';
const EXCHANGE_URI = '/home/returns/exchangeDetail';

// 处理退换货商品链接
const getProductUrlBySkc = (skn, gid, cnAlphabet) => {
    cnAlphabet = cnAlphabet || 'cnalphabet';

    return helpers.getUrlBySkc(skn, gid, cnAlphabet);
};

const setDetailGoods = (list) => {
    let resData = [];

    _.forEach(list, value => {
        resData.push({
            name: value.product_name || '',
            reason: value.reason_name
        });
    });

    return resData;
};

// 处理订单商品的数据
function getGoodsData(goods) {
    let arr = [];

    goods.forEach(good => {
        let cnAlphabet = good.cn_alphabet || '';

        arr.push({
            href: getProductUrlBySkc(good.product_skn, good.goods_id, cnAlphabet),
            thumb: helpers.image(good.goods_image, 60, 60),
            name: good.product_name,
            color: good.color_name,
            size: good.size_name
        });
    });

    return arr;
}

/**
 * 获得快递列表
 * @return array
 */
const getExpressCompany = (expressList) => {
    let data = [];

    _.forEach(expressList, function(value) {
        data.push(value);
    });
    data = _.flatten(data);

    return data;
};

/**
 * 退换货列表页数据
 * @param  {string} uid   用户 uid
 * @param  {Number} page  当前页数
 * @param  {Number} limit 每页最大条数
 * @return {Object}             Promise
 */
const getReturnsList = co(function*(uid, page, limit) {
    page = Number.parseInt(page, 10) || 1;
    limit = Number.parseInt(limit, 10) || 10;

    let obj = {
        orders: [],
        pager: {}
    };
    let response = yield api.post('', {
        method: 'app.refund.getList',
        uid: uid,
        page: page,
        limit: limit
    });
    let repData = response.data;

    // 处理数据
    if (response.code === 200 && repData && repData.list.length) {
        obj.pager = Object.assign({
            count: repData.total,
            curPage: page,
            totalPages: repData.total_page || 1
        }, pager(repData.total_page, {page: page}));

        repData.list.forEach(item => {
            let t = {
                returnId: item.id,
                orderNum: item.order_code,
                orderTime: item.order_create_time,
                returnTime: item.create_time,
                returnStatus: item.status_name
            };

            let canCancel = item.canCancel === TRUE;
            let isChange, uri = '', cancelUri = '';

            switch (item.refund_type) {
                case REFUND:
                    isChange = false;
                    uri = REFUND_URI;
                    cancelUri = CANCEL_REFUND_URI;
                    break;
                case EXCHANGE:
                    isChange = true;
                    uri = EXCHANGE_URI;
                    cancelUri = CANCEL_EXCHANGE_URI;
                    break;
                default:
                    break;
            }

            Object.assign(t, {
                isChange: isChange,
                canCancel: canCancel,
                canCancelUrl: cancelUri,
                moreHref: helpers.urlFormat(uri, { id: item.id }),
                goods: getGoodsData(item.goods)
            });

            obj.orders.push(t);
        });
    } else {
        obj.empty = RETURNS_EMPTY;
    }

    return obj;
});

/**
 * 退货申请页数据
 * @param $orderCode
 * @param $uid
 * @return array|mixed
 */
const getOrderRefund = (orderCode, uid) => {
    let process = function*() {
        let resData = {};
        let result = yield returnAPI.getRefundGoodsAsync(orderCode, uid);

        if (result.data) {
            let goods = [];
            let returnReason = result.data.return_reason,
                remarks = _.split(_.get(result, 'data.special_notice.remark', ''), '   ', 2), // 使用3个空格拆分
                amount = 0;


            _.forEach(_.get(result, 'data.goods_list', []), value => {
                let cnAlphabet = value.cn_alphabet || 'cnalphabet';
                let item = {
                    href: getProductUrlBySkc(value.product_skn, value.goods_id, cnAlphabet),
                    thumb: helpers.image(value.goods_image, 60, 60),
                    name: value.product_name,
                    color: value.factory_color_name,
                    size: value.size_name,
                    price: value.last_price,
                    skn: value.product_skn,
                    skc: value.product_skc,
                    sku: value.product_sku,
                    goods_type_id: value.goods_type_id,
                    goods_type: value.goods_type,
                    reason: returnReason
                };

                amount += parseInt(value.last_price, 10);

                // tar note 为每个特殊商品都添加标识
                if (value.is_limit_skn === 'Y') {
                    item.specialNoticeBo = {
                        title: _.get(result, 'data.special_notice.title', ''),
                        remark1: remarks[0] || '',
                        remark2: remarks[1] || ''
                    };

                    // tar note 对数组做处理,为不显示的添加 inactive
                    if (_.get(result, 'data.special_return_reason')) {
                        let spReason = _.get(result, 'data.special_return_reason');

                        _.forEach(item.reason, (subVal, subKey) => { // eslint-disable-line
                            if (_.indexOf(spReason, subKey)) {
                                _.set(item, `reason[${subKey}].inactive`, true);
                            }
                        });
                    }
                }

                goods.push(item);

                // 商品中有鞋类,传给前端标识
                if (value.hasShoes) {
                    _.set(resData, 'tips.footwear', true);
                }
            });

            Object.assign(resData, {
                goods: goods,
                orderCode: orderCode,

                // 计算相关支付细节
                amount: amount - _.get(result, 'data.yoho_coin_num', 0) -
                    _.get(result, 'data.coupon_amount', 0),
                yohoCoin: result.data.yoho_coin_num,
                coupon: result.data.coupon_amount,
                cash: amount
            });

            _.forEach(result.data.return_amount_mode, (val, key) => {
                if (val.is_default === 'Y') {
                    _.set(result, `data.return_amount_mode[${key}].default`, true);
                }
            });

            resData.returnBankMode = _.get(result, 'data.return_bank_mode', '');
            resData.returnAmountMode = result.data.return_amount_mode;
        }

        return {refund: resData};
    };

    return co(process)();
};

/**
 * 提交退货申请
 * @param $orderCode
 * @param $uid
 * @param array $goods
 * @param array $payment
 * @return array|mixed
 */
const saveRefund = (req, uid) => {
    let process = function*() {
        let orderCode = req.body.orderCode,
            goods = req.body.goods,
            payment = req.body.payment;


        if (_.isEmpty(orderCode) || orderCode < 1 ||
            _.isEmpty(goods) || _.isEmpty(payment)) {
            return {
                code: 203,
                message: '非法提交'
            };
        }

        // 调用模型提交退货申请
        let order = yield ordersAPI.viewOrderData(orderCode, uid);

        if (_.isEmpty(order)) {
            return {
                code: 403,
                message: '没有找到该订单'
            };
        }

        // 组装站内信内容
        let title = '您有一笔订单提交退货申请:';
        let content = '您的订单' + orderCode + '申请退货,给您带来不便敬请谅解!请至订单中心查看详情!';

        // 调用接口保存退货申请
        let result = yield returnAPI.refundSubmit(orderCode, uid, goods, payment);

        if (_.get(result, 'code') === 200) {
            // 退货成功发送站内信
            returnAPI.sendMessage(uid, title, content);

            result.data.refer = helpers.urlFormat('/home/returns/refundSuccess', {orderCode: orderCode});
        }

        return result;
    };

    return co(process)();
};

/**
 * 获取退货详情页数据
 * @param $uid
 * @param $id
 * @return array|mixed
 */
const getRefundDetail = (applyId, uid) => {
    let process = function*() {
        let resData = {};
        let result = yield Promise.all([
            returnAPI.getRefundDetailAsync(applyId, uid),
            returnAPI.getExpressCompanyAsync()
        ]);

        if (result[0].data) {
            let data = result[0].data;
            let detail = {
                isChange: false,
                returnId: applyId,
                orderNum: data.source_order_code,
                nowStatus: data.status_name,
                applyTime: data.create_time,
                payMode: data.source_payment_type_desc || '',
                backMode: data.return_amount_mode_name || '',
                goods: setDetailGoods(data.goods_list)
            };

            if (+data.status !== 0) {
                detail.express = {
                    id: _.get(data, 'notice.express_id', ''),
                    company: _.get(data, 'notice.express_company', ''),
                    number: _.get(data, 'notice.express_number', '')
                };
            }

            detail.statusList = [];
            _.forEach(data.statusList, value => {
                detail.statusList.push({
                    name: value.name,
                    act: value.act === 'Y'
                });
            });

            if (data.canCancel === 'Y') {
                detail.canCancelUrl = '/home/refund/cancel';
            }

            resData.detail = detail;

        }

        if (result[1].data && resData.detail) {
            _.set(resData, 'detail.express.expressList', getExpressCompany(result[1].data));
        }

        return resData;
    };

    return co(process)();
};

/**
 * 获取换货详情页数据
 * @param $uid
 * @param $id
 * @return array|mixed
 */
const getChangeDetail = (applyId, uid) => {
    let process = function*() {
        let resData = {};
        let result = yield Promise.all([
            returnAPI.getChangeDetailAsync(applyId, uid),
            returnAPI.getExpressCompanyAsync()
        ]);

        if (result[0].data) {
            let data = result[0].data;
            let detail = {
                isChange: true,
                returnId: applyId,
                orderNum: data.source_order_code,
                nowStatus: data.status_name,
                applyTime: data.create_time,
                goods: setDetailGoods(data.goods_list)
            };

            if (+data.status !== 0 && +data.delivery_tpye !== 20) {
                detail.express = {
                    id: _.get(data, 'notice.express_id', ''),
                    company: _.get(data, 'notice.express_company', ''),
                    number: _.get(data, 'notice.express_number', ''),
                    expressDeadLine: _.get(data, 'notice.date', '')
                };
            }

            detail.statusList = [];
            _.forEach(data.statusList, value => {
                detail.statusList.push({
                    name: value.name,
                    act: value.act === 'Y'
                });
            });

            if (data.canCancel === 'Y') {
                detail.canCancelUrl = helpers.urlFormat('/home/returns/cancelChange');
            }

            resData.detail = detail;

        }

        if (result[1].data && resData.detail) {
            _.set(resData, 'detail.express.expressList', getExpressCompany(result[1].data));
        }

        return resData;
    };

    return co(process)();
};

/**
 * 提交换货申请
 * @param $orderCode
 * @param $uid
 * @param $goods
 * @param $consigneeName
 * @param $areaCode
 * @param $address
 * @param $mobile
 * @param $zipCode
 * @param $deliveryType
 * @return array|mixed
 */
const saveExchange = (req, uid) => {
    let process = function*() {

        let orderCode = req.body.orderCode,
            goods = req.body.goods,
            consigneeName = req.body.consigneeName,
            areaCode = req.body.areaCode,
            address = req.body.address,
            mobile = req.body.mobile,
            zipCode = req.body.zipCode,
            deliveryType = req.body.deliveryType;

        if (_.isEmpty(orderCode) || orderCode < 1 || _.isEmpty(goods) ||
            _.isEmpty(deliveryType) || _.isEmpty(consigneeName) || _.isEmpty(areaCode) ||
            _.isEmpty(address) || _.isEmpty(mobile)) {
            return {
                code: 203,
                message: '非法提交'
            };
        }

        // 调用接口查询订单详情
        let order = yield ordersAPI.viewOrderData(orderCode, uid);

        if (_.isEmpty(order)) {
            return {
                code: 403,
                message: '没有找到该订单'
            };
        }

        // 订单15天后不能换货
        // if (_.get(order, 'code') === 200) {
        //     if ((new Date() - order.data.create_time) > 15*86400) {
        //         return {
        //             code: 400,
        //             message: '您的订单已经超过了换货有效期'
        //         }
        //     }
        // }

        // 保存换货申请
        let result = yield returnAPI.exchangeSubmit(orderCode, goods, consigneeName, areaCode,
            address, mobile, zipCode, deliveryType, uid);

        // 组装站内信内容
        let title = '您有一笔订单提交换货申请:';
        let content = '您的订单' + orderCode + '申请换货,给您带来不便敬请谅解!请至订单中心查看详情!';

        // 换货成功,返回前端相应格式,并返回换货成功页跳转链接
        if (_.get(result, 'code') === 200) {
            // 换货成功发送站内信
            returnAPI.sendMessage(uid, title, content);
            result.data.refer = helpers.urlFormat('/home/returns/exchangeSuccess', {orderCode: orderCode});
        }

        return result;
    };

    return co(process)();
};

/**
 * 换货申请页数据
 * @param $orderCode
 * @param $uid
 * @return array|mixed
 */
const getOrderExchange = (orderCode, uid) => {
    let process = function*() {
        let resData = {};
        let result = yield returnAPI.getExchangeGoodsAsync(orderCode, uid);

        if (result.data) {
            let goods = [];
            let sknPromise = [];
            let returnReason = result.data.exchange_reason,
                remarks = _.split(_.get(result, 'data.special_notice.remark', ''), '   ', 2); // 使用3个空格拆分

            _.forEach(_.get(result, 'data.goods_list', []), value => {
                let cnAlphabet = value.cn_alphabet || 'cnalphabet';
                let item = {
                    href: getProductUrlBySkc(value.product_skn, value.goods_id, cnAlphabet),
                    thumb: helpers.image(value.goods_image, 60, 60),
                    name: value.product_name,
                    color: value.color_name,
                    size: value.size_name,
                    price: value.last_price,
                    skn: value.product_skn,
                    skc: value.product_skc,
                    sku: value.product_sku,
                    goods_type_id: value.goods_type_id,
                    reason: _.cloneDeep(returnReason)
                };

                // tar note 为每个特殊商品都添加标识
                if (value.is_limit_skn === 'Y') {
                    item.specialNoticeBo = {
                        title: _.get(result, 'data.specialNoticeBo.title', ''),
                        remark1: remarks[0] || '',
                        remark2: remarks[1] || ''
                    };

                    let spReason = _.get(result, 'data.special_exchange_reason', []);

                    // tar note 对数组做处理,为不显示的添加 inactive
                    if (spReason && spReason.length) {
                        _.forEach(item.reason, subVal => { // eslint-disable-line
                            if (!_.filter(spReason, ['id', subVal.id]).length) {
                                subVal.inactive = true;
                            }
                        });
                    }
                }

                goods.push(item);

                // 商品中有鞋类,传给前端标识
                if (value.hasShoes) {
                    _.set(resData, 'tips.footwear', true);
                }

                sknPromise.push(returnAPI.getProductDataAsync(value.product_skn));
            });

            Object.assign(resData, {
                orderCode: orderCode,

                // 换货地址相关数据(邮编为可空参数)
                name: _.get(result, 'data.address.consignee', ''),
                area: _.get(result, 'data.address.area', ''),
                area_code: _.get(result, 'data.address.area_code', ''),
                address: _.get(result, 'data.address.address', ''),
                phone: _.get(result, 'data.address.mobile', ''),
                postcode: _.get(result, 'data.address.zip_code', '')
            });

            let productList = yield Promise.all(sknPromise);

            _.forEach(productList, (product, key) => { // 遍历得到每件商品

                let colorSize = [],
                    value = product.data;

                _.forEach(value.goods_list, val => { // 遍历商品得到每个颜色

                    let size = [];

                    _.forEach(val.size_list, v => { // 遍历颜色得到每个尺码
                        if (+v.storage_number > 0) { // 当某个尺码下有库存时,将该颜色及其对应的尺码加入该商品选项下
                            size.push(v);
                        }
                    });

                    if (size.length) {
                        colorSize.push({
                            color: val.factory_goods_name,
                            colorId: val.color_id,
                            goodsId: val.goods_id,
                            skc: val.product_skc,
                            sizeList: size
                        });
                    }
                });

                if (colorSize.length) {
                    goods[key].colorSize = colorSize;
                } else {
                    goods[key].banMsg = '库存不足不能换货';
                }

            });

            resData.goods = goods;
        }

        return {exchange: resData};
    };

    return co(process)();
};

const getDelivery = (areaCode, uid, gender, channel) => {
    return returnAPI.getDeliveryAsync(areaCode, uid, gender, channel).then((result) => {
        return result;
    });
};

const getCancelRefund = (id, uid) => {
    return returnAPI.cancelRefundAsync(id, uid).then((result) => {
        return result;
    });
};

const getCancelChange = (id, uid) => {
    return returnAPI.cancelChangeAsync(id, uid).then((result) => {
        return result;
    });
};

const setExpressNumber = (id, expressId, expressNumber, uid, expressCompany, isChange) => {
    return returnAPI.setExpressNumberAsync(id, expressId, expressNumber, uid, expressCompany, isChange).then((result) => { // eslint-disable-line
        return result;
    });
};

module.exports = {
    getReturnsList,         // 我的订单,退换货列表
    getOrderRefund,         // 我的订单,申请退货
    saveRefund,             // 退货提交
    getRefundDetail,        // 退货详情
    saveExchange,           // 换货提交
    getChangeDetail,        // 换货详情
    getOrderExchange,       // 我的订单,申请换货
    getDelivery,            // 获取换货方式
    getCancelRefund,        // 取消退货申请
    getCancelChange,        // 取消换货申请
    setExpressNumber        // 设置快递
};