Skip to content

Commit

Permalink
feat 添加订单物流
Browse files Browse the repository at this point in the history
  • Loading branch information
tumobi committed Feb 9, 2018
1 parent 1c86330 commit 500282b
Show file tree
Hide file tree
Showing 6 changed files with 324 additions and 59 deletions.
155 changes: 106 additions & 49 deletions nideshop.sql

Large diffs are not rendered by default.

36 changes: 26 additions & 10 deletions src/api/controller/order.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ module.exports = class extends Base {
* @return {Promise} []
*/
async listAction() {
const orderList = await this.model('order').where({user_id: think.userId}).page(1, 10).countSelect();
const orderList = await this.model('order').where({ user_id: think.userId }).page(1, 10).countSelect();
const newOrderList = [];
for (const item of orderList.data) {
// 订单的商品
item.goodsList = await this.model('order_goods').where({order_id: item.id}).select();
item.goodsList = await this.model('order_goods').where({ order_id: item.id }).select();
item.goodsCount = 0;
item.goodsList.forEach(v => {
item.goodsCount += v.number;
Expand All @@ -32,18 +32,21 @@ module.exports = class extends Base {

async detailAction() {
const orderId = this.get('orderId');
const orderInfo = await this.model('order').where({user_id: think.userId, id: orderId}).find();
const orderInfo = await this.model('order').where({ user_id: 1, id: orderId }).find();

if (think.isEmpty(orderInfo)) {
return this.fail('订单不存在');
}

orderInfo.province_name = await this.model('region').where({id: orderInfo.province}).getField('name', true);
orderInfo.city_name = await this.model('region').where({id: orderInfo.city}).getField('name', true);
orderInfo.district_name = await this.model('region').where({id: orderInfo.district}).getField('name', true);
orderInfo.province_name = await this.model('region').where({ id: orderInfo.province }).getField('name', true);
orderInfo.city_name = await this.model('region').where({ id: orderInfo.city }).getField('name', true);
orderInfo.district_name = await this.model('region').where({ id: orderInfo.district }).getField('name', true);
orderInfo.full_region = orderInfo.province_name + orderInfo.city_name + orderInfo.district_name;

const orderGoods = await this.model('order_goods').where({order_id: orderId}).select();
const latestExpressInfo = await this.model('order_express').getLatestOrderExpress(orderId);
orderInfo.express = latestExpressInfo;

const orderGoods = await this.model('order_goods').where({ order_id: orderId }).select();

// 订单状态的处理
orderInfo.order_status_text = await this.model('order').getOrderStatusText(orderId);
Expand Down Expand Up @@ -75,14 +78,14 @@ module.exports = class extends Base {
async submitAction() {
// 获取收货地址信息和计算运费
const addressId = this.post('addressId');
const checkedAddress = await this.model('address').where({id: addressId}).find();
const checkedAddress = await this.model('address').where({ id: addressId }).find();
if (think.isEmpty(checkedAddress)) {
return this.fail('请选择收货地址');
}
const freightPrice = 0.00;

// 获取要购买的商品
const checkedGoodsList = await this.model('cart').where({user_id: think.userId, session_id: 1, checked: 1}).select();
const checkedGoodsList = await this.model('cart').where({ user_id: think.userId, session_id: 1, checked: 1 }).select();
if (think.isEmpty(checkedGoodsList)) {
return this.fail('请选择商品');
}
Expand Down Expand Up @@ -159,6 +162,19 @@ module.exports = class extends Base {
await this.model('order_goods').addMany(orderGoodsData);
await this.model('cart').clearBuyGoods();

return this.success({orderInfo: orderInfo});
return this.success({ orderInfo: orderInfo });
}

/**
* 查询物流信息
* @returns {Promise.<void>}
*/
async expressAction() {
const orderId = this.get('orderId');
if (think.isEmpty(orderId)) {
return this.fail('订单不存在');
}
const latestExpressInfo = await this.model('order_express').getLatestOrderExpress(orderId);
return this.success(latestExpressInfo);
}
};
60 changes: 60 additions & 0 deletions src/api/model/order_express.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
module.exports = class extends think.Model {
get tableName() {
return this.tablePrefix + 'order_express';
}

/**
* 获取最新的订单物流信息
* @param orderId
* @returns {Promise.<*>}
*/
async getLatestOrderExpress(orderId) {
const returnExpressInfo = {
shipper_code: '',
shipper_name: '',
logistic_code: '',
is_finish: 0,
request_time: 0,
traces: []
};
const orderExpress = await this.where({ order_id: orderId }).find();
if (think.isEmpty(orderExpress)) {
return returnExpressInfo;
}
if (think.isEmpty(orderExpress.shipper_code) || think.isEmpty(orderExpress.logistic_code)) {
return returnExpressInfo;
}

returnExpressInfo.shipper_code = orderExpress.shipper_code;
returnExpressInfo.shipper_name = orderExpress.shipper_name;
returnExpressInfo.logistic_code = orderExpress.logistic_code;
returnExpressInfo.is_finish = orderExpress.is_finish;
returnExpressInfo.request_time = think.datetime(orderExpress.request_time * 1000);
returnExpressInfo.traces = think.isEmpty(orderExpress.traces) ? [] : JSON.parse(orderExpress.traces);

// 如果物流配送已完成,直接返回
if (orderExpress.is_finish) {
return returnExpressInfo;
}

// 查询最新物流信息
const ExpressSerivce = think.service('express', 'api');
const latestExpressInfo = await ExpressSerivce.queryExpress(orderExpress.shipper_code, orderExpress.logistic_code);
const nowTime = Number.parseInt(Date.now() / 1000);
const updateData = {
request_time: nowTime,
update_time: nowTime,
request_count: ['EXP', 'request_count+1']
};
if (latestExpressInfo.success) {
returnExpressInfo.traces = latestExpressInfo.traces;
returnExpressInfo.is_finish = latestExpressInfo.isFinish;
// 查询成功则更新订单物流信息
updateData.traces = JSON.stringify(latestExpressInfo.traces);
returnExpressInfo.request_time = think.datetime(nowTime * 1000);
updateData.is_finish = latestExpressInfo.isFinish;
}
await this.where({ id: orderExpress.id }).update(updateData);
return returnExpressInfo;
}
};
19 changes: 19 additions & 0 deletions src/api/model/shipper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module.exports = class extends think.Model {
/**
* 根据快递公司编码获取名称
* @param shipperCode
* @returns {Promise.<*>}
*/
async getShipperNameByCode(shipperCode) {
return this.where({ code: shipperCode }).getField('name', true);
}

/**
* 根据 id 获取快递公司信息
* @param shipperId
* @returns {Promise.<*>}
*/
async getShipperById(shipperId) {
return this.where({ id: shipperId }).find();
}
};
107 changes: 107 additions & 0 deletions src/api/service/express.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
const rp = require('request-promise');
const _ = require('lodash');

module.exports = class extends think.Service {
async queryExpress(shipperCode, logisticCode, orderCode = '') {
let expressInfo = {
success: false,
shipperCode: shipperCode,
shipperName: '',
logisticCode: logisticCode,
isFinish: 0,
traces: []
};
const fromData = this.generateFromData(shipperCode, logisticCode, orderCode);
if (think.isEmpty(fromData)) {
return expressInfo;
}

const sendOptions = {
method: 'POST',
url: think.config('express.request_url'),
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
form: fromData
};

try {
const requestResult = await rp(sendOptions);
if (think.isEmpty(requestResult)) {
return expressInfo;
}
expressInfo = this.parseExpressResult(requestResult);
expressInfo.shipperCode = shipperCode;
expressInfo.logisticCode = logisticCode;
return expressInfo;
} catch (err) {
return expressInfo;
}
}

parseExpressResult(requestResult) {
const expressInfo = {
success: false,
shipperCode: '',
shipperName: '',
logisticCode: '',
isFinish: 0,
traces: []
};

if (think.isEmpty(requestResult)) {
return expressInfo;
}

try {
if (_.isString(requestResult)) {
requestResult = JSON.parse(requestResult);
}
} catch (err) {
return expressInfo;
}

if (think.isEmpty(requestResult.Success)) {
return expressInfo;
}

// 判断是否已签收
if (Number.parseInt(requestResult.State) === 3) {
expressInfo.isFinish = 1;
}
expressInfo.success = true;
if (!think.isEmpty(requestResult.Traces) && Array.isArray(requestResult.Traces)) {
expressInfo.traces = _.map(requestResult.Traces, item => {
return { datetime: item.AcceptTime, content: item.AcceptStation };
});
_.reverse(expressInfo.traces);
}
return expressInfo;
}

generateFromData(shipperCode, logisticCode, orderCode) {
const requestData = this.generateRequestData(shipperCode, logisticCode, orderCode);
const fromData = {
RequestData: encodeURI(requestData),
EBusinessID: think.config('express.appid'),
RequestType: '1002',
DataSign: this.generateDataSign(requestData),
DataType: '2'
};
return fromData;
}

generateRequestData(shipperCode, logisticCode, orderCode = '') {
// 参数验证
const requestData = {
OrderCode: orderCode,
ShipperCode: shipperCode,
LogisticCode: logisticCode
};
return JSON.stringify(requestData);
}

generateDataSign(requestData) {
return encodeURI(Buffer.from(think.md5(requestData + think.config('express.appkey'))).toString('base64'));
}
};
6 changes: 6 additions & 0 deletions src/common/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,11 @@ module.exports = {
mch_id: '', // 商户帐号ID
partner_key: '', // 微信支付密钥
notify_url: '' // 微信异步通知,例:https://www.nideshop.com/api/pay/notify
},
express: {
// 快递物流信息查询使用的是快递鸟接口,申请地址:http://www.kdniao.com/
appid: '', // 对应快递鸟用户后台 用户ID
appkey: '', // 对应快递鸟用户后台 API key
request_url: 'http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx'
}
};

0 comments on commit 500282b

Please sign in to comment.