goodsRate.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. //
  7. class GoodsRateService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'goodsrate');
  10. this.model = this.ctx.model.Shop.GoodsRate;
  11. }
  12. /**
  13. * @param {Object} body 添加内容
  14. * @param {Object} data 添加后的结果
  15. */
  16. async afterCreate(body, data) {
  17. const { shop } = data;
  18. if (shop) await this.computedShopRate(shop);
  19. return data;
  20. }
  21. async computedShopRate(shop) {
  22. const list = await this.model.find({ shop });
  23. const gsList = list.map(i => i.goods_score);
  24. const ssList = list.map(i => i.shop_score);
  25. const tsList = list.map(i => i.transport_score);
  26. const goods_score = this.dealScore(gsList);
  27. const send_score = this.dealScore(ssList);
  28. const service_score = this.dealScore(tsList);
  29. await this.ctx.model.Shop.Shop.updateOne({ _id: shop }, { goods_score, send_score, service_score });
  30. }
  31. /**
  32. * 计算评分
  33. ** 该店铺所有评价的中位数以上是好评,中位数以下是差评
  34. ** 5分是满分,一个差评抵10个好评,一个差评 -0.01 分
  35. * @param {Array} arr 分数列表
  36. */
  37. dealScore(arr) {
  38. let score = 5;
  39. arr = arr.sort((a, b) => b - a);
  40. const length = arr.length;
  41. let mid,
  42. midIndex;
  43. const gl = [];
  44. let wl = [];
  45. if (length % 2 !== 0) {
  46. midIndex = this.ctx.plus(Math.floor(length / 2), 1);
  47. mid = arr[midIndex];
  48. } else {
  49. midIndex = this.ctx.divide(length, 2);
  50. mid = this.ctx.divide(this.ctx.plus(arr[midIndex], arr[midIndex + 1]), 2);
  51. }
  52. for (const i of arr) {
  53. if (i >= mid) gl.push(i);
  54. else wl.push(i);
  55. }
  56. const offset = _.floor(this.ctx.divide(gl.length, 10));
  57. wl = wl.splice(1, offset);
  58. score = this.ctx.minus(score, this.ctx.multiply(wl.length, 0.01));
  59. return score;
  60. }
  61. }
  62. module.exports = GoodsRateService;