orderDetail.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. //
  7. class OrderDetailService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'orderdetail');
  10. this.model = this.ctx.model.Trade.OrderDetail;
  11. this.orderModel = this.ctx.model.Trade.Order;
  12. }
  13. /**
  14. * 创建:用户支付完成后的订单
  15. * @param {Object} body 请求参数体
  16. * @param body.order_id 下单的id
  17. * @param {Transaction} tran 数据库事务实例
  18. */
  19. async create({ order_id }, tran) {
  20. assert(order_id, '缺少支付订单信息');
  21. // if (!tran) throw new BusinessError(ErrorCode.DATA_INVALID, '支付成功添加积分:缺少事务参数');
  22. const order = await this.orderModel.findById(order_id);
  23. if (!order) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到支付订单的数据');
  24. const { customer, address, goods, no, status, buy_time, pay } = order;
  25. if (status === '0') throw new BusinessError(ErrorCode.DATA_INVALID, '订单未支付');
  26. const orderDetailData = { customer, address, order: order_id, buy_time, pay_time: _.get(pay, 'pay_time'), status };
  27. // 补全 shop, goods, total_detail TODO: 补全 discount;
  28. // const arr = [];
  29. let noTimes = 1;
  30. for (const s of goods) {
  31. const shop = _.get(s, 'shop');
  32. const goodsList = _.get(s, 'goods', []);
  33. const detailNo = `${no}-${noTimes}`;
  34. const total_detail = this.getTotalDetail(goodsList);
  35. noTimes++;
  36. const obj = { ...orderDetailData, shop, goods: goodsList, no: detailNo, total_detail };
  37. tran.insert('OrderDetail', obj);
  38. // arr.push(obj);
  39. }
  40. // await this.model.insertMany(arr);
  41. }
  42. /**
  43. * 计算某店铺的金额总计
  44. * TODO: 缺少优惠计算部分
  45. * @param {Array} goodsList 商品规格列表
  46. */
  47. getTotalDetail(goodsList) {
  48. const goods_total = _.floor(
  49. goodsList.reduce((p, n) => p + (parseFloat(n.sell_money) || 0), 0),
  50. 2
  51. );
  52. const freight_total = _.floor(
  53. goodsList.reduce((p, n) => p + (parseFloat(n.freight) || 0), 0),
  54. 2
  55. );
  56. return { goods_total, freight_total };
  57. }
  58. }
  59. module.exports = OrderDetailService;