1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- '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');
- //
- class GoodsRateService extends CrudService {
- constructor(ctx) {
- super(ctx, 'goodsrate');
- this.model = this.ctx.model.Shop.GoodsRate;
- }
- /**
- * @param {Object} body 添加内容
- * @param {Object} data 添加后的结果
- */
- async afterCreate(body, data) {
- const { shop } = data;
- if (shop) await this.computedShopRate(shop);
- return data;
- }
- async computedShopRate(shop) {
- const list = await this.model.find({ shop });
- const gsList = list.map(i => i.goods_score);
- const ssList = list.map(i => i.shop_score);
- const tsList = list.map(i => i.transport_score);
- const goods_score = this.dealScore(gsList);
- const send_score = this.dealScore(ssList);
- const service_score = this.dealScore(tsList);
- await this.ctx.model.Shop.Shop.updateOne({ _id: shop }, { goods_score, send_score, service_score });
- }
- /**
- * 计算评分
- ** 该店铺所有评价的中位数以上是好评,中位数以下是差评
- ** 5分是满分,一个差评抵10个好评,一个差评 -0.01 分
- * @param {Array} arr 分数列表
- */
- dealScore(arr) {
- let score = 5;
- arr = arr.sort((a, b) => b - a);
- const length = arr.length;
- let mid,
- midIndex;
- const gl = [];
- let wl = [];
- if (length % 2 !== 0) {
- midIndex = this.ctx.plus(Math.floor(length / 2), 1);
- mid = arr[midIndex];
- } else {
- midIndex = this.ctx.divide(length, 2);
- mid = this.ctx.divide(this.ctx.plus(arr[midIndex], arr[midIndex + 1]), 2);
- }
- for (const i of arr) {
- if (i >= mid) gl.push(i);
- else wl.push(i);
- }
- const offset = _.floor(this.ctx.divide(gl.length, 10));
- wl = wl.splice(1, offset);
- score = this.ctx.minus(score, this.ctx.multiply(wl.length, 0.01));
- return score;
- }
- }
- module.exports = GoodsRateService;
|