123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- '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 PointService extends CrudService {
- constructor(ctx) {
- super(ctx, 'point');
- this.model = this.ctx.model.User.Point;
- this.orderDetailModel = this.ctx.model.Trade.OrderDetail;
- this.userModel = this.ctx.model.User.User;
- }
- async computedTotal({ customer }) {
- assert(customer, '缺少用户信息');
- const res = await this.model.find({ customer });
- const total = res.reduce((p, n) => {
- let point = n.point;
- if (!(n.source === '0' || n.source === '1')) point = -point;
- return this.ctx.plus(p, point);
- }, 0);
- return total;
- }
- /**
- * 添加积分;将处理添加至事务之中
- * @param {String} orderDetail_id 订单详情id
- * @param {Transaction} tran 数据库事务
- */
- async addPoints(orderDetail_id, tran) {
- const orderDetail = await this.orderDetailModel.findById(orderDetail_id);
- assert(orderDetail, '缺少订单信息');
- const realPay = this.ctx.service.util.orderDetail.computedRealPay(orderDetail);
- // 支付金额/设定金额 为积分;
- const config = await this.ctx.service.system.config.query();
- const setting = _.get(config, 'config.buyPoint', 10);
- const point = this.ctx.divide(realPay, setting);
- const { customer, _id: source_id } = orderDetail;
- const obj = { customer, source_id, source: '0' };
- const r = await this.checkHasAdd(obj);
- if (r) return;
- obj.point = point;
- obj.time = moment().format('YYYY-MM-DD HH:mm:ss');
- // await this.model.create(obj);
- tran.insert('Point', obj);
- }
- // 检查是否已经添加过该来源的积分
- async checkHasAdd(query) {
- const { customer, source_id, source } = query;
- const num = await this.model.count({ customer, source_id, source });
- return num > 0;
- }
- /**
- * 订单退货,退积分
- * @param {String} source_id 拆分后的订单id
- * @param {Transaction} tran 数据库事务
- */
- async refundOrderPoint(source_id, tran) {
- const record = await this.model.findOne({ source_id, source: '0' });
- // 没有该订单收货后的积分记录,直接返回
- if (!record) return;
- // 查找该订单是否已经退积分
- const num = await this.model.count({ source_id, source: '-1' });
- // 有记录,返回
- if (num > 0) return;
- const { customer, point } = record;
- const data = { customer, point, time: moment().format('YYYY-MM-DD HH:mm:ss'), source: '-1', source_id };
- tran.insert('Point', data);
- }
- }
- module.exports = PointService;
|