statistics.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. const moment = require('moment');
  7. const { ObjectId } = require('mongoose').Types;
  8. //
  9. class StatisticsService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx, 'statistics');
  12. this.billModel = this.ctx.model.Business.Bill;
  13. this.rssModel = this.ctx.model.Relation.RelationStudentSchool;
  14. this.rcsModel = this.ctx.model.Relation.RelationCoachSchool;
  15. this.lessonCoachModel = this.ctx.model.Business.LessonCoach;
  16. }
  17. // 学校统计 教练出勤率
  18. async schoolSignCoach({ school_id, coach_id }) {
  19. // 查出这个学校下面的教练
  20. const query = { school_id, coach_id };
  21. const { year } = this.getPartsOfNow();
  22. const yearEnd = `${year}-12-01`;
  23. query.$and = [{ 'meta.createdAt': { $gte: `${year}-01-01 00:00:00` } }, { 'meta.createdAt': { $lte: `${year}-12-31 23:59:59` } }];
  24. let monthList = this.getMonthList(12, yearEnd);
  25. monthList = monthList.map(i => {
  26. const start = moment(i).startOf('month').format('YYYY-MM-DD HH:mm:ss');
  27. const end = moment(i).endOf('month').format('YYYY-MM-DD HH:mm:ss');
  28. return [ start, end ];
  29. });
  30. let lcList = await this.lessonCoachModel.find(query, { coach_id: 1, is_sign: 1, meta: 1 });
  31. if (lcList.length > 0) lcList = JSON.parse(JSON.stringify((lcList)));
  32. const arr = [];
  33. for (const months of monthList) {
  34. const s = _.head(months);
  35. const l = _.last(months);
  36. const m = moment(s).month() + 1;
  37. const obj = { m };
  38. const list = lcList.filter(f => moment(_.get(f, 'meta.createdAt')).isBetween(s, l, null, '[]'));
  39. let total = 0;
  40. let is_signed = 0;
  41. for (const lc of list) {
  42. if (lc.is_sign === '1') is_signed++;
  43. total++;
  44. }
  45. obj.total = total;
  46. obj.is_sign = is_signed;
  47. obj.value = `${_.floor(_.divide(is_signed, total) * 100) || 0}%`;
  48. arr.push(obj);
  49. }
  50. return arr;
  51. }
  52. // 学校统计:学员按岁数区间
  53. async schoolStudentAge({ school_id }) {
  54. // 年龄组
  55. const ageList = [
  56. [ null, 6 ],
  57. [ 7, 9 ],
  58. [ 10, 12 ],
  59. [ 12, 18 ],
  60. [ 19, 30 ],
  61. [ 31, null ],
  62. ];
  63. const data = [];
  64. let list = await this.rssModel.find({ school_id }).populate('student_id', 'age');
  65. if (list.length > 0)list = JSON.parse(JSON.stringify(list));
  66. for (const a of ageList) {
  67. const start = _.head(a);
  68. const end = _.last(a);
  69. const obj = {};
  70. if (start && end) obj.name = `${start}-${end}岁`;
  71. else if (!start) obj.name = `${end}岁以下`;
  72. else if (!end) obj.name = `${start}岁以上`;
  73. const l = list.filter(f => {
  74. const age = _.get(f, 'student_id.age');
  75. if (start && end) return age >= start && age <= end;
  76. else if (!start) return age <= end;
  77. else if (!end) return age >= start;
  78. return false;
  79. });
  80. obj.value = l.length;
  81. data.push(obj);
  82. }
  83. return data;
  84. }
  85. /**
  86. * 羽校总收入
  87. * 统计账单的 收入(类型为-1/-2) - 退款(至余额,2) 且 is_pay 为 1
  88. * m:当前这个月; 3m: 往前推3个月; 6m:往前推6个月; 1y:当前年
  89. * @param {Object} query 查询条件
  90. * @property {String} school_id 学校id
  91. * @property {String} time 时间 m:月;3m:3月;6m:6个月; 1y:1年
  92. */
  93. async schoolTotalIn({ school_id, time }) {
  94. assert(school_id, '缺少羽校信息');
  95. assert(time, '缺少时间范围');
  96. let query = { is_pay: '1', $or: [{ type: '-1' }, { type: '-2' }, { type: '2' }], school_id };
  97. const { year, month, lastDate } = this.getPartsOfNow();
  98. const timeQuery = (start, end) => ({ $and: [{ time: { $gte: start } }, { time: { $lte: end } }] });
  99. let xList;
  100. const yList = [];
  101. if (time === 'm') {
  102. // 这个月,按天查
  103. const start = `${year}-${month}-01`;
  104. const end = `${year}-${month}-${lastDate}`;
  105. query = { ...query, ...timeQuery(start, end) };
  106. xList = this.getEachDay(start, end);
  107. } else if ([ '3m', '6m' ].includes(time)) {
  108. const ms = _.head(time.split('')); // 月份数量 3/6/...
  109. xList = this.getMonthList(ms);
  110. const start = _.last(xList);
  111. const { year, month, lastDate } = this.getPartsOfNow(_.head(xList));
  112. const end = `${year}-${month}-${lastDate}`;
  113. query = { ...query, ...timeQuery(start, end) };
  114. } else if (time === '1y') {
  115. const { year } = this.getPartsOfNow();
  116. const start = `${year}-01-01`;
  117. const end = `${year}-12-31`;
  118. xList = this.getMonthList(12, end);
  119. query = { ...query, ...timeQuery(start, end) };
  120. }
  121. let billList = await this.billModel.find(query);
  122. if (billList.length > 0) billList = JSON.parse(JSON.stringify(billList));
  123. for (const i of billList) {
  124. const { time } = i;
  125. const date = this.getDate(time);
  126. i.date = date;
  127. }
  128. if (time === 'm') {
  129. for (const x of xList) {
  130. const date = x;
  131. const list = billList.filter(f => f.date === date);
  132. const inList = list.filter(f => f.type !== '2');
  133. const outList = list.filter(f => f.type === '2');
  134. const inTotal = inList.reduce((p, n) => p + (n.money || 0), 0);
  135. const outTotal = outList.reduce((p, n) => p + (n.money || 0), 0);
  136. const total = inTotal - outTotal;
  137. yList.push(total);
  138. }
  139. xList = xList.map(i => {
  140. const { date } = this.getPartsOfNow(i);
  141. return `${date}日`;
  142. });
  143. } else if ([ '3m', '6m', '1y' ].includes(time)) {
  144. for (const x of xList) {
  145. const start = x;
  146. const { year, month, lastDate } = this.getPartsOfNow(x);
  147. const end = `${year}-${month}-${lastDate}`;
  148. const list = billList.filter(f => moment(f.date).isBetween(start, end, null, '[]'));
  149. const inList = list.filter(f => f.type !== '2');
  150. const outList = list.filter(f => f.type === '2');
  151. const inTotal = inList.reduce((p, n) => p + (n.money || 0), 0);
  152. const outTotal = outList.reduce((p, n) => p + (n.money || 0), 0);
  153. const total = inTotal - outTotal;
  154. yList.unshift(total);
  155. }
  156. xList = xList.map(i => {
  157. const { month } = this.getPartsOfNow(i);
  158. return `${parseInt(month)}月`;
  159. });
  160. xList = _.reverse(xList);
  161. }
  162. return { x: xList, y: yList };
  163. }
  164. // 获取现在时间的各个部分 年月日时分秒 和 当月最后一天是几号
  165. getPartsOfNow(time = new Date()) {
  166. const year = moment(time).year();
  167. let month = moment(time).month() + 1;
  168. if (month < 10) month = `0${month}`;
  169. const date = moment(time).date();
  170. const hour = moment(time).hour();
  171. const minute = moment(time).minute();
  172. const second = moment(time).second();
  173. const lastDate = moment(`${year}-${month}-01`).add(1, 'months').subtract(1, 'days')
  174. .date();
  175. return { year, month, date, hour, minute, second, lastDate };
  176. }
  177. // 获取两个时间点内的每天
  178. getEachDay(start, end) {
  179. const arr = [];
  180. let i = 0;
  181. const addDay = (s, i) => moment(s).add(i, 'days').format('YYYY-MM-DD');
  182. while (!moment(addDay(start, i)).isAfter(end, 'day')) {
  183. arr.push(addDay(start, i));
  184. i++;
  185. }
  186. return arr;
  187. }
  188. // 根据数据获取日期
  189. getDate(time) {
  190. const year = moment(time).year();
  191. let month = moment(time).month() + 1;
  192. if (month < 10) month = `0${month}`;
  193. const date = moment(time).date();
  194. return `${year}-${month}-${date}`;
  195. }
  196. // 获取月份第一天的列表, 往前推 pushNum 个月
  197. getMonthList(pushNum, date) {
  198. if (!_.isNumber(pushNum)) pushNum = parseInt(pushNum);
  199. const arr = [];
  200. const { year, month } = this.getPartsOfNow(date);
  201. const sDate = `${year}-${month}-01`;
  202. for (let i = 0; i < pushNum; i++) {
  203. const { year, month } = this.getPartsOfNow(moment(sDate).subtract(i, 'months'));
  204. arr.push(`${year}-${month}-01`);
  205. }
  206. return arr;
  207. }
  208. }
  209. module.exports = StatisticsService;