statistics.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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, is_sign: 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. let total = 0;
  213. let is_signed = 0;
  214. for (const lc of list) {
  215. if (lc.is_sign === '1') is_signed++;
  216. total++;
  217. }
  218. obj.total = total;
  219. obj.is_sign = is_signed;
  220. obj.value = `${_.floor(_.divide(is_signed, total) * 100) || 0}%`;
  221. arr.push(obj);
  222. }
  223. return arr;
  224. }
  225. // 学校统计:学员按岁数区间
  226. async schoolStudentAge({ school_id }) {
  227. assert(school_id, '缺少学校信息');
  228. // 年龄组
  229. const ageList = [
  230. [ null, 6 ],
  231. [ 7, 9 ],
  232. [ 10, 12 ],
  233. [ 12, 18 ],
  234. [ 19, 30 ],
  235. [ 31, null ],
  236. ];
  237. const data = [];
  238. let list = await this.rssModel.find({ school_id }).populate('student_id', 'age');
  239. if (list.length > 0)list = JSON.parse(JSON.stringify(list));
  240. for (const a of ageList) {
  241. const start = _.head(a);
  242. const end = _.last(a);
  243. const obj = {};
  244. if (start && end) obj.name = `${start}-${end}岁`;
  245. else if (!start) obj.name = `${end}岁以下`;
  246. else if (!end) obj.name = `${start}岁以上`;
  247. const l = list.filter(f => {
  248. const birth = _.get(f, 'sstudent_id.birth');
  249. const age = moment().diff(birth, 'years');
  250. if (start && end) return age >= start && age <= end;
  251. else if (!start) return age <= end;
  252. else if (!end) return age >= start;
  253. return false;
  254. });
  255. obj.value = l.length;
  256. data.push(obj);
  257. }
  258. return data;
  259. }
  260. /**
  261. * 羽校总收入
  262. * 统计账单的 收入(类型为-1/-2) - 退款(至余额,2) 且 is_pay 为 1
  263. * m:当前这个月; 3m: 往前推3个月; 6m:往前推6个月; 1y:当前年
  264. * @param {Object} query 查询条件
  265. * @property {String} school_id 学校id
  266. * @property {String} time 时间 m:月;3m:3月;6m:6个月; 1y:1年
  267. */
  268. async schoolTotalIn({ school_id, time }) {
  269. assert(school_id, '缺少羽校信息');
  270. assert(time, '缺少时间范围');
  271. let query = { is_pay: '1', $or: [{ type: '-1' }, { type: '-2' }, { type: '2' }], school_id };
  272. const { year, month, lastDate } = this.getPartsOfNow();
  273. const timeQuery = (start, end) => ({ $and: [{ time: { $gte: start } }, { time: { $lte: end } }] });
  274. let xList;
  275. const yList = [];
  276. if (time === 'm') {
  277. // 这个月,按天查
  278. const start = `${year}-${month}-01`;
  279. const end = `${year}-${month}-${lastDate}`;
  280. query = { ...query, ...timeQuery(start, end) };
  281. xList = this.getEachDay(start, end);
  282. } else if ([ '3m', '6m' ].includes(time)) {
  283. const ms = _.head(time.split('')); // 月份数量 3/6/...
  284. xList = this.getMonthList(ms);
  285. const start = _.last(xList);
  286. const { year, month, lastDate } = this.getPartsOfNow(_.head(xList));
  287. const end = `${year}-${month}-${lastDate}`;
  288. query = { ...query, ...timeQuery(start, end) };
  289. } else if (time === '1y') {
  290. const { year } = this.getPartsOfNow();
  291. const start = `${year}-01-01`;
  292. const end = `${year}-12-31`;
  293. xList = this.getMonthList(12, end);
  294. query = { ...query, ...timeQuery(start, end) };
  295. }
  296. let billList = await this.billModel.find(query, { pay_for: 1, from_id: 1, type: 1, money: 1, time: 1, payer_id: 1 });
  297. if (billList.length > 0) billList = JSON.parse(JSON.stringify(billList));
  298. for (const i of billList) {
  299. const { time } = i;
  300. const date = this.getDate(time);
  301. i.date = date;
  302. }
  303. if (time === 'm') {
  304. for (const x of xList) {
  305. const date = x;
  306. const list = billList.filter(f => f.date === date);
  307. const inList = list.filter(f => f.type !== '2');
  308. const outList = list.filter(f => f.type === '2');
  309. const inTotal = inList.reduce((p, n) => p + (n.money || 0), 0);
  310. const outTotal = outList.reduce((p, n) => p + (n.money || 0), 0);
  311. const total = inTotal - outTotal;
  312. yList.push(total);
  313. }
  314. xList = xList.map(i => {
  315. const { date } = this.getPartsOfNow(i);
  316. return `${date}日`;
  317. });
  318. } else if ([ '3m', '6m', '1y' ].includes(time)) {
  319. for (const x of xList) {
  320. const start = x;
  321. const { year, month, lastDate } = this.getPartsOfNow(x);
  322. const end = `${year}-${month}-${lastDate}`;
  323. const list = billList.filter(f => moment(f.date).isBetween(start, end, null, '[]'));
  324. const inList = list.filter(f => f.type !== '2');
  325. const outList = list.filter(f => f.type === '2');
  326. const inTotal = inList.reduce((p, n) => p + (n.money || 0), 0);
  327. const outTotal = outList.reduce((p, n) => p + (n.money || 0), 0);
  328. const total = inTotal - outTotal;
  329. yList.unshift(total);
  330. }
  331. xList = xList.map(i => {
  332. const { month } = this.getPartsOfNow(i);
  333. return `${parseInt(month)}月`;
  334. });
  335. xList = _.reverse(xList);
  336. }
  337. console.log('line 189 in function:');
  338. return { x: xList, y: yList };
  339. }
  340. // 获取现在时间的各个部分 年月日时分秒 和 当月最后一天是几号
  341. getPartsOfNow(time = new Date()) {
  342. const year = moment(time).year();
  343. let month = moment(time).month() + 1;
  344. if (month < 10) month = `0${month}`;
  345. const date = moment(time).date();
  346. const hour = moment(time).hour();
  347. const minute = moment(time).minute();
  348. const second = moment(time).second();
  349. const lastDate = moment(`${year}-${month}-01`).add(1, 'months').subtract(1, 'days')
  350. .date();
  351. return { year, month, date, hour, minute, second, lastDate };
  352. }
  353. // 获取两个时间点内的每天
  354. getEachDay(start, end) {
  355. const arr = [];
  356. let i = 0;
  357. const addDay = (s, i) => moment(s).add(i, 'days').format('YYYY-MM-DD');
  358. while (!moment(addDay(start, i)).isAfter(end, 'day')) {
  359. arr.push(addDay(start, i));
  360. i++;
  361. }
  362. return arr;
  363. }
  364. // 根据数据获取日期
  365. getDate(time) {
  366. const year = moment(time).year();
  367. let month = moment(time).month() + 1;
  368. if (month < 10) month = `0${month}`;
  369. const date = moment(time).date();
  370. return `${year}-${month}-${date}`;
  371. }
  372. // 获取月份第一天的列表, 往前推 pushNum 个月
  373. getMonthList(pushNum, date) {
  374. if (!_.isNumber(pushNum)) pushNum = parseInt(pushNum);
  375. const arr = [];
  376. const { year, month } = this.getPartsOfNow(date);
  377. const sDate = `${year}-${month}-01`;
  378. for (let i = 0; i < pushNum; i++) {
  379. const { year, month } = this.getPartsOfNow(moment(sDate).subtract(i, 'months'));
  380. arr.push(`${year}-${month}-01`);
  381. }
  382. return arr;
  383. }
  384. }
  385. module.exports = StatisticsService;