statistics.js 14 KB

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