erp2goods-service.js 1.42 KB
/**
 * Created by TaoHuang on 2016/11/14.
 */

'use strict';

const Erp2GoodsApi = require('./erp2goods-api');

const _ = require('lodash');
const helpers = global.yoho.helpers;

module.exports = class extends global.yoho.BaseModel {
    constructor(ctx) {
        super(ctx);

        this.erp2GoodsApi = new Erp2GoodsApi(ctx);
    }

    find(q) {
        if (q.sku) {
            return this._findBySku(q.sku);
        } else if (q.skn) {
            return this._findBySkn(q.skn);
        } else {
            return Promise.reject();
        }
    }

    _findBySku(sku) {
        return this.erp2GoodsApi.getProductBySkuAsync(`[${sku}]`).then((result) => {
            if (result && result.code && result.code === 200 && !_.isEmpty(result.data)) {
                let product = _.head(result.data) || {};
                let skn = product.erpProductId || '';

                if (skn) {
                    return this._findBySkn(skn);
                }

                return {};
            } else {
                return {};
            }
        });
    }

    _findBySkn(skn) {
        return this.erp2GoodsApi.getProductBySknAsync(skn).then((result) => {
            if (result && result.code && result.code === 200 && result.data.product_url) {
                return {
                    url: helpers.getUrlBySkc(result.data.product_skn)
                };
            } else {
                return {};
            }
        });
    }
};