point.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. const moment = require('moment');
  7. //
  8. class PointService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'point');
  11. this.model = this.ctx.model.User.Point;
  12. this.orderDetailModel = this.ctx.model.Trade.OrderDetail;
  13. this.userModel = this.ctx.model.User.User;
  14. }
  15. async computedTotal({ customer }) {
  16. assert(customer, '缺少用户信息');
  17. const res = await this.model.find({ customer });
  18. const total = res.reduce((p, n) => {
  19. let point = n.point;
  20. if (!(n.source === '0' || n.source === '1')) point = -point;
  21. return this.ctx.plus(p, point);
  22. }, 0);
  23. return total;
  24. }
  25. /**
  26. * 添加积分;将处理添加至事务之中
  27. * @param {String} orderDetail_id 订单详情id
  28. * @param {Transaction} tran 数据库事务
  29. */
  30. async addPoints(orderDetail_id, tran) {
  31. const orderDetail = await this.orderDetailModel.findById(orderDetail_id);
  32. assert(orderDetail, '缺少订单信息');
  33. const realPay = this.ctx.service.util.orderDetail.computedRealPay(orderDetail);
  34. // 支付金额/设定金额 为积分;
  35. const config = await this.ctx.service.system.config.query();
  36. const setting = _.get(config, 'config.buyPoint', 10);
  37. const point = this.ctx.divide(realPay, setting);
  38. const { customer, _id: source_id } = orderDetail;
  39. const obj = { customer, source_id, source: '0' };
  40. const r = await this.checkHasAdd(obj);
  41. if (r) return;
  42. obj.point = point;
  43. obj.time = moment().format('YYYY-MM-DD HH:mm:ss');
  44. // await this.model.create(obj);
  45. tran.insert('Point', obj);
  46. }
  47. // 检查是否已经添加过该来源的积分
  48. async checkHasAdd(query) {
  49. const { customer, source_id, source } = query;
  50. const num = await this.model.count({ customer, source_id, source });
  51. return num > 0;
  52. }
  53. /**
  54. * 订单退货,退积分
  55. * @param {String} source_id 拆分后的订单id
  56. * @param {Transaction} tran 数据库事务
  57. */
  58. async refundOrderPoint(source_id, tran) {
  59. const record = await this.model.findOne({ source_id, source: '0' });
  60. // 没有该订单收货后的积分记录,直接返回
  61. if (!record) return;
  62. // 查找该订单是否已经退积分
  63. const num = await this.model.count({ source_id, source: '-1' });
  64. // 有记录,返回
  65. if (num > 0) return;
  66. const { customer, point } = record;
  67. const data = { customer, point, time: moment().format('YYYY-MM-DD HH:mm:ss'), source: '-1', source_id };
  68. tran.insert('Point', data);
  69. }
  70. }
  71. module.exports = PointService;