cashBack.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 CashBackService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'cashback');
  11. this.model = this.ctx.model.User.CashBack;
  12. this.orderDetailModel = this.ctx.model.Trade.OrderDetail;
  13. }
  14. async computedTotal({ customer }) {
  15. assert(customer, '缺少用户信息');
  16. // status(状态) 和 source(来源) 均表示钱是入账还是出账,判断一个就行,主要还是依靠来源吧
  17. const res = await this.model.find({ inviter: customer }).lean();
  18. let total = 0;
  19. for (const i of res) {
  20. const { source, money } = i;
  21. const sn = parseInt(source);
  22. if (sn >= 0) total = this.ctx.plus(total, money);
  23. else total = this.ctx.minus(total, money);
  24. }
  25. return total;
  26. }
  27. /**
  28. * 添加检查返现
  29. * @param {String} orderDetail_id 订单详情id
  30. * @param {Transaction} tran 数据库事务
  31. */
  32. async create(orderDetail_id, tran) {
  33. const { populate } = this.ctx.service.trade.orderDetail.getRefMods();
  34. const orderDetail = await this.orderDetailModel.findById(orderDetail_id).populate(populate);
  35. if (!orderDetail) return;
  36. // 找到商品的返现类型
  37. let rmoney = 0;
  38. const { goods: goodsSpec, type } = orderDetail;
  39. // 根据订单类型判断应该取哪个价钱,为下面的百分比计算取值用
  40. let priceKey;
  41. if (type === '1') priceKey = 'ggrp';
  42. else priceKey = 'grp';
  43. const moneyDetail = this.ctx.service.util.orderDetail.moneyDetail(orderDetail);
  44. for (const gs of goodsSpec) {
  45. const goods = _.get(gs, 'goods');
  46. if (!goods) continue;
  47. const { is_cashBack, cb_config } = goods;
  48. // 0:返现(使用)
  49. if (is_cashBack !== '0') continue;
  50. const type = _.get(cb_config, 'back_type');
  51. if (!type) continue;
  52. const money = _.get(cb_config, 'money');
  53. if (type === 'fixed') rmoney = this.ctx.plus(rmoney, money);
  54. else if (type === 'percent') {
  55. const specId = _.get(gs, '_id');
  56. const realPay = _.get(moneyDetail, `${specId}.${priceKey}`);
  57. const grm = this.ctx.multiply(realPay, this.ctx.divide(money, 10));
  58. rmoney = this.ctx.plus(rmoney, grm);
  59. }
  60. }
  61. const { inviter, _id: order_detail } = orderDetail;
  62. if (!inviter) return;
  63. const obj = { inviter: _.get(inviter, '_id'), source_id: order_detail, source: '0', money: rmoney, time: moment().format('YYYY-MM-DD HH:mm:ss') };
  64. // 检查是否已经返利
  65. const num = await this.model.count({ inviter: _.get(inviter, '_id'), source_id: order_detail, source: '0' });
  66. if (num > 0) return;
  67. tran.insert('CashBack', obj);
  68. }
  69. }
  70. module.exports = CashBackService;