cashBack.js 2.7 KB

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