statistics.js 15 KB

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