cashBack.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. const res = await this.model.find({ inviter: customer });
  17. const total = res.reduce((p, n) => {
  18. let money = n.money;
  19. if (!(n.source === '0' || n.source === '1')) money = -money;
  20. return this.ctx.plus(p, money);
  21. }, 0);
  22. return total;
  23. }
  24. /**
  25. * 添加检查返现
  26. * @param {String} orderDetail_id 订单详情id
  27. * @param {Transaction} tran 数据库事务
  28. */
  29. async create(orderDetail_id, tran) {
  30. const { populate } = this.ctx.service.trade.orderDetail.getRefMods();
  31. const orderDetail = await this.orderDetailModel.findById(orderDetail_id).populate(populate);
  32. if (!orderDetail) return;
  33. // 找到商品的返现类型
  34. let rmoney = 0;
  35. const { goods: goodsSpec, type } = orderDetail;
  36. // 根据订单类型判断应该取哪个价钱,为下面的百分比计算取值用
  37. let priceKey;
  38. if (type === '1') priceKey = 'ggrp';
  39. else priceKey = 'grp';
  40. const moneyDetail = this.ctx.service.util.orderDetail.moneyDetail(orderDetail);
  41. for (const gs of goodsSpec) {
  42. const goods = _.get(gs, 'goods');
  43. if (!goods) continue;
  44. const { is_cashBack, cb_config } = goods;
  45. // 0:返现(使用)
  46. if (is_cashBack !== '0') continue;
  47. const type = _.get(cb_config, 'back_type');
  48. if (!type) continue;
  49. const money = _.get(cb_config, 'money');
  50. if (type === 'fixed') rmoney = this.ctx.plus(rmoney, money);
  51. else if (type === 'percent') {
  52. const specId = _.get(gs, '_id');
  53. const realPay = _.get(moneyDetail, `${specId}.${priceKey}`);
  54. const grm = this.ctx.multiply(realPay, this.ctx.divide(money, 10));
  55. rmoney = this.ctx.plus(rmoney, grm);
  56. }
  57. }
  58. const { inviter, _id: order_detail } = orderDetail;
  59. if (!inviter) return;
  60. const obj = { inviter: _.get(inviter, '_id'), source_id: order_detail, source: '0', money: rmoney, time: moment().format('YYYY-MM-DD HH:mm:ss') };
  61. // 检查是否已经返利
  62. const num = await this.model.count({ inviter: _.get(inviter, '_id'), source_id: order_detail, source: '0' });
  63. if (num > 0) return;
  64. tran.insert('CashBack', obj);
  65. }
  66. }
  67. module.exports = CashBackService;