123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- 'use strict';
- const { CrudService } = require('naf-framework-mongoose-free/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const _ = require('lodash');
- const assert = require('assert');
- const moment = require('moment');
- //
- class CashBackService extends CrudService {
- constructor(ctx) {
- super(ctx, 'cashback');
- this.model = this.ctx.model.User.CashBack;
- this.orderDetailModel = this.ctx.model.Trade.OrderDetail;
- }
- async computedTotal({ customer }) {
- assert(customer, '缺少用户信息');
- const res = await this.model.find({ inviter: customer });
- const total = res.reduce((p, n) => {
- let money = n.money;
- if (!(n.source === '0' || n.source === '1')) money = -money;
- return this.ctx.plus(p, money);
- }, 0);
- return total;
- }
- /**
- * 添加检查返现
- * @param {String} orderDetail_id 订单详情id
- * @param {Transaction} tran 数据库事务
- */
- async create(orderDetail_id, tran) {
- const { populate } = this.ctx.service.trade.orderDetail.getRefMods();
- const orderDetail = await this.orderDetailModel.findById(orderDetail_id).populate(populate);
- if (!orderDetail) return;
- // 找到商品的返现类型
- let rmoney = 0;
- const { goods: goodsSpec, type } = orderDetail;
- // 根据订单类型判断应该取哪个价钱,为下面的百分比计算取值用
- let priceKey;
- if (type === '1') priceKey = 'ggrp';
- else priceKey = 'grp';
- const moneyDetail = this.ctx.service.util.orderDetail.moneyDetail(orderDetail);
- for (const gs of goodsSpec) {
- const goods = _.get(gs, 'goods');
- if (!goods) continue;
- const { is_cashBack, cb_config } = goods;
- // 0:返现(使用)
- if (is_cashBack !== '0') continue;
- const type = _.get(cb_config, 'back_type');
- if (!type) continue;
- const money = _.get(cb_config, 'money');
- if (type === 'fixed') rmoney = this.ctx.plus(rmoney, money);
- else if (type === 'percent') {
- const specId = _.get(gs, '_id');
- const realPay = _.get(moneyDetail, `${specId}.${priceKey}`);
- const grm = this.ctx.multiply(realPay, this.ctx.divide(money, 10));
- rmoney = this.ctx.plus(rmoney, grm);
- }
- }
- const { inviter, _id: order_detail } = orderDetail;
- if (!inviter) return;
- const obj = { inviter: _.get(inviter, '_id'), source_id: order_detail, source: '0', money: rmoney, time: moment().format('YYYY-MM-DD HH:mm:ss') };
- // 检查是否已经返利
- const num = await this.model.count({ inviter: _.get(inviter, '_id'), source_id: order_detail, source: '0' });
- if (num > 0) return;
- tran.insert('CashBack', obj);
- }
- }
- module.exports = CashBackService;
|