statistics.js 16 KB

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