1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- '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
- */
- async addPoints(orderDetail_id) {
- 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);
- }
- // 检查是否已经添加过该来源的积分
- async checkHasAdd(query) {
- const { customer, source_id, source } = query;
- const num = await this.model.count({ customer, source_id, source });
- return num > 0;
- }
- }
- module.exports = PointService;
|