point.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. /**
  16. * 添加积分;将处理添加至事务之中
  17. * @param {String} orderDetail_id 订单详情id
  18. */
  19. async addPoints(orderDetail_id) {
  20. const orderDetail = await this.orderDetailModel.findById(orderDetail_id);
  21. assert(orderDetail, '缺少订单信息');
  22. const realPay = this.ctx.service.util.orderDetail.computedRealPay(orderDetail);
  23. // 支付金额/设定金额 为积分;
  24. const config = await this.ctx.service.system.config.query();
  25. const setting = _.get(config, 'config.buyPoint', 10);
  26. const point = this.ctx.divide(realPay, setting);
  27. const { customer, _id: source_id } = orderDetail;
  28. const obj = { customer, source_id, source: 'OrderDetail' };
  29. const r = await this.checkHasAdd(obj);
  30. if (r) return;
  31. obj.point = point;
  32. obj.time = moment().format('YYYY-MM-DD HH:mm:ss');
  33. await this.model.create(obj);
  34. }
  35. // 检查是否已经添加过该来源的积分
  36. async checkHasAdd(query) {
  37. const { customer, source_id, source } = query;
  38. const num = await this.model.count({ customer, source_id, source });
  39. return num > 0;
  40. }
  41. }
  42. module.exports = PointService;