cashBack.js 2.1 KB

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