|
@@ -3,6 +3,8 @@ const { CrudService } = require('naf-framework-mongoose-free/lib/service');
|
|
|
const { BusinessError, ErrorCode } = require('naf-core').Error;
|
|
|
const _ = require('lodash');
|
|
|
const assert = require('assert');
|
|
|
+const moment = require('moment');
|
|
|
+const Transaction = require('mongoose-transactions');
|
|
|
//
|
|
|
class ZrOrderService extends CrudService {
|
|
|
constructor(ctx) {
|
|
@@ -15,11 +17,50 @@ class ZrOrderService extends CrudService {
|
|
|
this.pointModel = this.ctx.model.Base.Point;
|
|
|
this.shopModel = this.ctx.model.Base.Shop;
|
|
|
this.addressModel = this.ctx.model.Base.Address;
|
|
|
+ this.tran = new Transaction();
|
|
|
}
|
|
|
// 进入订单页前,通过函数判断,存储是否可以购买 指定商品 的 指定数量
|
|
|
// 下单,走同样的函数判断.
|
|
|
// 直接生成订单,扣除积分
|
|
|
|
|
|
+ async create(data) {
|
|
|
+ const { shop, goods, buy_num, address, remarks } = data;
|
|
|
+ const res = await this.checkCanBuy({ shop, goods, num: buy_num }, false);
|
|
|
+ if (!res.result) throw new BusinessError(ErrorCode.DATA_INVALID, res.msg);
|
|
|
+ // 可以购买
|
|
|
+ const customer = _.get(this.ctx.user, '_id');
|
|
|
+ const goodsInfo = await this.goodsModel.findById(goods);
|
|
|
+ const buy_time = moment().format('YYYY-MM-DD HH:mm:ss');
|
|
|
+ const no = `${buy_time}-${this.createNonceStr()}`;
|
|
|
+ try {
|
|
|
+ const orderData = {
|
|
|
+ customer,
|
|
|
+ shop,
|
|
|
+ goods: goodsInfo,
|
|
|
+ buy_num,
|
|
|
+ buy_time,
|
|
|
+ no,
|
|
|
+ address,
|
|
|
+ status: '1',
|
|
|
+ remarks,
|
|
|
+ };
|
|
|
+ const order_id = this.tran.insert('ZrOrder', orderData);
|
|
|
+ // #region 积分处理
|
|
|
+ const costTotal = this.ctx.multiply(_.get(goodsInfo, 'cost'), buy_num);
|
|
|
+ const pointData = { customer, point: costTotal, time: buy_time, source: '-2', source_id: order_id };
|
|
|
+ this.tran.insert('Point', pointData);
|
|
|
+ // #endregion
|
|
|
+ await this.tran.run();
|
|
|
+ return 'ok';
|
|
|
+ } catch (error) {
|
|
|
+ await this.tran.rollback();
|
|
|
+ console.error(error);
|
|
|
+ } finally {
|
|
|
+ this.tran.clean();
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
async toMakeOrder({ key }) {
|
|
|
key = `${this.redisKey.orderKeyPrefix}${key}`;
|
|
|
let data = await this.redis.get(key);
|