'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; } /** * 添加检查返现 * @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, order_detail, money: rmoney, time: moment().format('YYYY-MM-DD HH:mm:ss') }; tran.insert('CashBack', obj); } } module.exports = CashBackService;