lrf il y a 2 ans
Parent
commit
0973077f33
2 fichiers modifiés avec 54 ajouts et 2 suppressions
  1. 1 1
      app/model/shop/goodsRate.js
  2. 53 1
      app/service/shop/goodsRate.js

+ 1 - 1
app/model/shop/goodsRate.js

@@ -18,7 +18,7 @@ const goodsRate = {
   goodsSpec: { type: String, required: false, zh: '规格', ref: 'Shop.GoodsSpec' }, //
   reply: { type: Array, required: false, zh: '回复' }, //
   goods_score: { type: Number, required: false, default: 5, zh: '商品评分' }, //
-  shop_score: { type: Number, required: false, default: 5, zh: '店铺评分' }, //
+  shop_score: { type: Number, required: false, default: 5, zh: '服务评分' }, //
   transport_score: { type: Number, required: false, default: 5, zh: '快递评分' }, //
 };
 const schema = new Schema(goodsRate, { toJSON: { getters: true, virtuals: true } });

+ 53 - 1
app/service/shop/goodsRate.js

@@ -4,12 +4,64 @@ 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 wl = [],
+      gl = [];
+    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));
+    for (let i = 0; i < offset.length; i++) {
+      wl.pop();
+    }
+    score = this.ctx.minus(score, this.ctx.multiply(wl.length, 0.01));
+    return score;
+  }
 }
 
 module.exports = GoodsRateService;