point.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. */
  29. async addPoints(orderDetail_id) {
  30. const orderDetail = await this.orderDetailModel.findById(orderDetail_id);
  31. assert(orderDetail, '缺少订单信息');
  32. const realPay = this.ctx.service.util.orderDetail.computedRealPay(orderDetail);
  33. // 支付金额/设定金额 为积分;
  34. const config = await this.ctx.service.system.config.query();
  35. const setting = _.get(config, 'config.buyPoint', 10);
  36. const point = this.ctx.divide(realPay, setting);
  37. const { customer, _id: source_id } = orderDetail;
  38. const obj = { customer, source_id, source: '0' };
  39. const r = await this.checkHasAdd(obj);
  40. if (r) return;
  41. obj.point = point;
  42. obj.time = moment().format('YYYY-MM-DD HH:mm:ss');
  43. await this.model.create(obj);
  44. }
  45. // 检查是否已经添加过该来源的积分
  46. async checkHasAdd(query) {
  47. const { customer, source_id, source } = query;
  48. const num = await this.model.count({ customer, source_id, source });
  49. return num > 0;
  50. }
  51. }
  52. module.exports = PointService;