statistics.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. this.lessonStudentModel = this.ctx.model.Business.LessonStudent;
  17. this.lessonModel = this.ctx.model.Business.Lesson;
  18. }
  19. // 学校统计,教练收入
  20. async schoolCoachIn({ school_id, coach_id }) {
  21. assert(school_id, '缺少学校信息');
  22. assert(coach_id, '缺少教练信息');
  23. // 教练收入分为私教课和公开课,公开课是根据给教练设置的钱计算,
  24. const query = { school_id, coach_id };
  25. const { year } = this.getPartsOfNow();
  26. const yearEnd = `${year}-12-01`;
  27. let monthList = this.getMonthList(12, yearEnd);
  28. monthList = monthList.map(i => {
  29. const start = moment(i).startOf('month').format('YYYY-MM-DD HH:mm:ss');
  30. const end = moment(i).endOf('month').format('YYYY-MM-DD HH:mm:ss');
  31. return [ start, end ];
  32. });
  33. query.$and = [{ 'meta.createdAt': { $gte: `${year}-01-01 00:00:00` } }, { 'meta.createdAt': { $lte: `${year}-12-31 23:59:59` } }];
  34. const lcList = await this.lessonCoachModel.find(query).populate('lesson_id');
  35. const lessonList = lcList.map(i => i.lesson_id).map(i => _.pick(i, [ '_id', 'type', 'title', 'meta' ]));
  36. const arr = [];
  37. for (const months of monthList) {
  38. const s = _.head(months);
  39. const l = _.last(months);
  40. const m = moment(s).month() + 1;
  41. const obj = { m, total: 0 };
  42. const list = lessonList.filter(f => moment(_.get(f, 'meta.createdAt')).isBetween(s, l, null, '[]'));
  43. // console.log(m);
  44. const privateLesson = list.filter(f => f.type === '1');
  45. const publicLesson = list.filter(f => f.type === '0');
  46. // 先算公开课
  47. for (const pl of publicLesson) {
  48. // 找到该教练的价格,这节公开课的人头数 算出教练应得金额
  49. const { _id: lesson_id } = pl;
  50. const lessonCoach = lcList.find(f => ObjectId(f.lesson_id._id).equals(lesson_id));
  51. if (!lessonCoach) continue;
  52. const studentNumber = await this.lessonStudentModel.count({ lesson_id, is_pay: '1' });
  53. const { money = 0 } = lessonCoach;
  54. const total = money * studentNumber;
  55. obj.total += total;
  56. }
  57. for (const pl of privateLesson) {
  58. // 私教课,lessonStudent中这个课学生交的钱
  59. const { _id: lesson_id } = pl;
  60. const studentList = await this.lessonStudentModel.find({ lesson_id, is_pay: '1' });
  61. const total = studentList.reduce((p, n) => p + (n.money || 0), 0);
  62. obj.total += total;
  63. }
  64. arr.push(obj);
  65. }
  66. return arr;
  67. }
  68. // 学校统计 教练出勤率
  69. async schoolSignCoach({ school_id, coach_id }) {
  70. assert(school_id, '缺少学校信息');
  71. assert(coach_id, '缺少教练信息');
  72. // 查出这个学校下面的教练
  73. const query = { school_id, coach_id };
  74. const { year } = this.getPartsOfNow();
  75. const yearEnd = `${year}-12-01`;
  76. query.$and = [{ 'meta.createdAt': { $gte: `${year}-01-01 00:00:00` } }, { 'meta.createdAt': { $lte: `${year}-12-31 23:59:59` } }];
  77. let monthList = this.getMonthList(12, yearEnd);
  78. monthList = monthList.map(i => {
  79. const start = moment(i).startOf('month').format('YYYY-MM-DD HH:mm:ss');
  80. const end = moment(i).endOf('month').format('YYYY-MM-DD HH:mm:ss');
  81. return [ start, end ];
  82. });
  83. let lcList = await this.lessonCoachModel.find(query, { coach_id: 1, is_sign: 1, meta: 1 });
  84. if (lcList.length > 0) lcList = JSON.parse(JSON.stringify((lcList)));
  85. const arr = [];
  86. for (const months of monthList) {
  87. const s = _.head(months);
  88. const l = _.last(months);
  89. const m = moment(s).month() + 1;
  90. const obj = { m };
  91. const list = lcList.filter(f => moment(_.get(f, 'meta.createdAt')).isBetween(s, l, null, '[]'));
  92. let total = 0;
  93. let is_signed = 0;
  94. for (const lc of list) {
  95. if (lc.is_sign === '1') is_signed++;
  96. total++;
  97. }
  98. obj.total = total;
  99. obj.is_sign = is_signed;
  100. obj.value = `${_.floor(_.divide(is_signed, total) * 100) || 0}%`;
  101. arr.push(obj);
  102. }
  103. return arr;
  104. }
  105. // 学校统计:学员按岁数区间
  106. async schoolStudentAge({ school_id }) {
  107. assert(school_id, '缺少学校信息');
  108. // 年龄组
  109. const ageList = [
  110. [ null, 6 ],
  111. [ 7, 9 ],
  112. [ 10, 12 ],
  113. [ 12, 18 ],
  114. [ 19, 30 ],
  115. [ 31, null ],
  116. ];
  117. const data = [];
  118. let list = await this.rssModel.find({ school_id }).populate('student_id', 'age');
  119. if (list.length > 0)list = JSON.parse(JSON.stringify(list));
  120. for (const a of ageList) {
  121. const start = _.head(a);
  122. const end = _.last(a);
  123. const obj = {};
  124. if (start && end) obj.name = `${start}-${end}岁`;
  125. else if (!start) obj.name = `${end}岁以下`;
  126. else if (!end) obj.name = `${start}岁以上`;
  127. const l = list.filter(f => {
  128. const age = _.get(f, 'student_id.age');
  129. if (start && end) return age >= start && age <= end;
  130. else if (!start) return age <= end;
  131. else if (!end) return age >= start;
  132. return false;
  133. });
  134. obj.value = l.length;
  135. data.push(obj);
  136. }
  137. return data;
  138. }
  139. /**
  140. * 羽校总收入
  141. * 统计账单的 收入(类型为-1/-2) - 退款(至余额,2) 且 is_pay 为 1
  142. * m:当前这个月; 3m: 往前推3个月; 6m:往前推6个月; 1y:当前年
  143. * @param {Object} query 查询条件
  144. * @property {String} school_id 学校id
  145. * @property {String} time 时间 m:月;3m:3月;6m:6个月; 1y:1年
  146. */
  147. async schoolTotalIn({ school_id, time }) {
  148. assert(school_id, '缺少羽校信息');
  149. assert(time, '缺少时间范围');
  150. let query = { is_pay: '1', $or: [{ type: '-1' }, { type: '-2' }, { type: '2' }], school_id };
  151. const { year, month, lastDate } = this.getPartsOfNow();
  152. const timeQuery = (start, end) => ({ $and: [{ time: { $gte: start } }, { time: { $lte: end } }] });
  153. let xList;
  154. const yList = [];
  155. if (time === 'm') {
  156. // 这个月,按天查
  157. const start = `${year}-${month}-01`;
  158. const end = `${year}-${month}-${lastDate}`;
  159. query = { ...query, ...timeQuery(start, end) };
  160. xList = this.getEachDay(start, end);
  161. } else if ([ '3m', '6m' ].includes(time)) {
  162. const ms = _.head(time.split('')); // 月份数量 3/6/...
  163. xList = this.getMonthList(ms);
  164. const start = _.last(xList);
  165. const { year, month, lastDate } = this.getPartsOfNow(_.head(xList));
  166. const end = `${year}-${month}-${lastDate}`;
  167. query = { ...query, ...timeQuery(start, end) };
  168. } else if (time === '1y') {
  169. const { year } = this.getPartsOfNow();
  170. const start = `${year}-01-01`;
  171. const end = `${year}-12-31`;
  172. xList = this.getMonthList(12, end);
  173. query = { ...query, ...timeQuery(start, end) };
  174. }
  175. let billList = await this.billModel.find(query, { pay_for: 1, from_id: 1, type: 1, money: 1, time: 1, payer_id: 1 });
  176. if (billList.length > 0) billList = JSON.parse(JSON.stringify(billList));
  177. for (const i of billList) {
  178. const { time } = i;
  179. const date = this.getDate(time);
  180. i.date = date;
  181. }
  182. if (time === 'm') {
  183. for (const x of xList) {
  184. const date = x;
  185. const list = billList.filter(f => f.date === date);
  186. const inList = list.filter(f => f.type !== '2');
  187. const outList = list.filter(f => f.type === '2');
  188. const inTotal = inList.reduce((p, n) => p + (n.money || 0), 0);
  189. const outTotal = outList.reduce((p, n) => p + (n.money || 0), 0);
  190. const total = inTotal - outTotal;
  191. yList.push(total);
  192. }
  193. xList = xList.map(i => {
  194. const { date } = this.getPartsOfNow(i);
  195. return `${date}日`;
  196. });
  197. } else if ([ '3m', '6m', '1y' ].includes(time)) {
  198. for (const x of xList) {
  199. const start = x;
  200. const { year, month, lastDate } = this.getPartsOfNow(x);
  201. const end = `${year}-${month}-${lastDate}`;
  202. const list = billList.filter(f => moment(f.date).isBetween(start, end, null, '[]'));
  203. const inList = list.filter(f => f.type !== '2');
  204. const outList = list.filter(f => f.type === '2');
  205. const inTotal = inList.reduce((p, n) => p + (n.money || 0), 0);
  206. const outTotal = outList.reduce((p, n) => p + (n.money || 0), 0);
  207. const total = inTotal - outTotal;
  208. yList.unshift(total);
  209. }
  210. xList = xList.map(i => {
  211. const { month } = this.getPartsOfNow(i);
  212. return `${parseInt(month)}月`;
  213. });
  214. xList = _.reverse(xList);
  215. }
  216. console.log('line 189 in function:');
  217. return { x: xList, y: yList };
  218. }
  219. // 获取现在时间的各个部分 年月日时分秒 和 当月最后一天是几号
  220. getPartsOfNow(time = new Date()) {
  221. const year = moment(time).year();
  222. let month = moment(time).month() + 1;
  223. if (month < 10) month = `0${month}`;
  224. const date = moment(time).date();
  225. const hour = moment(time).hour();
  226. const minute = moment(time).minute();
  227. const second = moment(time).second();
  228. const lastDate = moment(`${year}-${month}-01`).add(1, 'months').subtract(1, 'days')
  229. .date();
  230. return { year, month, date, hour, minute, second, lastDate };
  231. }
  232. // 获取两个时间点内的每天
  233. getEachDay(start, end) {
  234. const arr = [];
  235. let i = 0;
  236. const addDay = (s, i) => moment(s).add(i, 'days').format('YYYY-MM-DD');
  237. while (!moment(addDay(start, i)).isAfter(end, 'day')) {
  238. arr.push(addDay(start, i));
  239. i++;
  240. }
  241. return arr;
  242. }
  243. // 根据数据获取日期
  244. getDate(time) {
  245. const year = moment(time).year();
  246. let month = moment(time).month() + 1;
  247. if (month < 10) month = `0${month}`;
  248. const date = moment(time).date();
  249. return `${year}-${month}-${date}`;
  250. }
  251. // 获取月份第一天的列表, 往前推 pushNum 个月
  252. getMonthList(pushNum, date) {
  253. if (!_.isNumber(pushNum)) pushNum = parseInt(pushNum);
  254. const arr = [];
  255. const { year, month } = this.getPartsOfNow(date);
  256. const sDate = `${year}-${month}-01`;
  257. for (let i = 0; i < pushNum; i++) {
  258. const { year, month } = this.getPartsOfNow(moment(sDate).subtract(i, 'months'));
  259. arr.push(`${year}-${month}-01`);
  260. }
  261. return arr;
  262. }
  263. }
  264. module.exports = StatisticsService;