statisticsService.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. 'use strict';
  2. const moment = require('moment');
  3. const Service = require('egg').Service;
  4. // 本地清洗数据的统计业务 通用所有模块
  5. class StatisticsService extends Service {
  6. async saveBefore(model, data) {
  7. const { ctx } = this;
  8. const { dateString } = data;
  9. const result = await model.findOne({ dateString });
  10. ctx.logger.info(`查询本地${model.modelName}时间${dateString}`);
  11. if (result) {
  12. return true;
  13. }
  14. return false;
  15. }
  16. async save(model, data, isUpdate) {
  17. const { ctx } = this;
  18. const { dateString } = data;
  19. ctx.logger.info(`执行本地${model.modelName}时间${dateString}`);
  20. if (isUpdate) {
  21. const result = await model.findOne({ dateString });
  22. if (result) {
  23. delete data._id;
  24. const updateResult = await model.updateOne({ dateString }, data);
  25. if (!updateResult) {
  26. ctx.throw(`${model.modelName}更新数据异常`);
  27. }
  28. return updateResult;
  29. }
  30. }
  31. const createResult = await model.create(data);
  32. if (!createResult) {
  33. ctx.throw(`${model.modelName}插入数据异常`);
  34. }
  35. return createResult;
  36. }
  37. async taskCond(baseData) {
  38. const { ctx } = this;
  39. await this.sign([ 'app_task', 'ivi_online_user' ], baseData, async () => {
  40. await ctx.service.onlineUserService2.statistics(baseData);// 重新处理
  41. });
  42. await this.sign([ 'app_task' ], baseData, async () => {
  43. await ctx.service.appBehaviorRecordService.statistics(baseData);
  44. await ctx.service.appExceptionRecordService.statistics(baseData);
  45. await ctx.service.appFeedbackRecordService.statistics(baseData);
  46. });
  47. await this.sign([ 't_rbac_user' ], baseData, async () => {
  48. await ctx.service.tRbacUserService.statistics(baseData);// 重新处理
  49. });
  50. await this.sign([ 't_register_info' ], baseData, async () => {
  51. await ctx.service.tRegisterInfoService.statistics(baseData);
  52. });
  53. await this.sign([ 't_vehicle_record' ], baseData, async () => {
  54. await ctx.service.tVehicleRecordService2.statistics(baseData);// 重新处理
  55. });
  56. await this.sign([ 'driving_behavior_info' ], baseData, async () => {
  57. await ctx.service.drivingBehaviorInfoService2.statistics(baseData);// 重新处理
  58. });
  59. await this.sign([ 'stats_base_info' ], baseData, async () => {
  60. await ctx.service.statsBaseInfoService2.statistics(baseData);// 重新处理
  61. });
  62. await this.sign([ 'ivi_behavior_record' ], baseData, async () => {
  63. await ctx.service.iviBehaviorRecordService.statistics(baseData);// 重新处理
  64. });
  65. await this.sign([ 'msc_query_record' ], baseData, async () => {
  66. await ctx.service.msgQueryRecordService.statistics(baseData);
  67. });
  68. await this.sign([ 'msg_center_record' ], baseData, async () => {
  69. await ctx.service.msgCenterRecordService2.statistics(baseData);
  70. });
  71. }
  72. async taskDo(baseData) {
  73. const { ctx } = this;
  74. await ctx.service.tVehicleReportInfoService.statistics(baseData);// 重新处理
  75. await ctx.service.tBoxAutoTestService.statistics(baseData);// 重新处理
  76. await ctx.service.tFsmHitoryService.statistics(baseData);// 重新处理
  77. }
  78. async task(flag, startTime, endTime) { // flag "cond" "do"
  79. const { ctx } = this;
  80. // 更新历史时间段数据 => 修改createBaseData的参数做循环请求即可
  81. if (process.env.NODE_ENV === 'development') {
  82. } else {
  83. if (this.app.redis) { // 分布式锁 防止重复执行定时任务
  84. const result = await this.app.redis.setnx(`chart_task_${moment().format('YYYY-MM-DD')}`, '1');
  85. await this.app.redis.expire(`chart_task_${moment().format('YYYY-MM-DD')}`, 10 * 60);
  86. if (!result) {
  87. return;
  88. }
  89. } else {
  90. return;
  91. }
  92. }
  93. let satrtMoment;
  94. if (startTime) {
  95. satrtMoment = moment(startTime);
  96. } else {
  97. if (flag) {
  98. const newVar = await ctx.model.Local.StatisticsModel.findOne({ type: flag }).sort({ create_date: 1 });
  99. if (newVar) {
  100. satrtMoment = moment(newVar.create_date);
  101. await ctx.model.Local.StatisticsModel.deleteMany({ type: flag });
  102. }
  103. } else {
  104. const newVar = await ctx.model.Local.StatisticsModel.findOne({}).sort({ create_date: 1 });
  105. if (newVar) {
  106. satrtMoment = moment(newVar.create_date);
  107. await ctx.model.Local.StatisticsModel.deleteMany();
  108. }
  109. }
  110. }
  111. if (!satrtMoment) {
  112. satrtMoment = moment(this.ctx.helper.yesterday());
  113. }
  114. endTime = endTime || this.ctx.helper.today();
  115. while (satrtMoment.valueOf() < endTime) {
  116. const startTime = satrtMoment.valueOf();
  117. const eTime = satrtMoment.add(1, 'days').valueOf();
  118. const baseData = this.createBaseData(startTime, eTime);
  119. try {
  120. if (!flag) {
  121. await this.taskCond(baseData);
  122. await this.taskDo(baseData);
  123. } else {
  124. switch (flag) {
  125. case 'do':
  126. await this.taskDo(baseData);
  127. break;
  128. case 'cond':
  129. await this.taskCond(baseData);
  130. break;
  131. default:
  132. break;
  133. }
  134. }
  135. } catch (e) {
  136. const errData =
  137. { ...baseData.initData, start_time: new Date(), end_time: new Date(),
  138. type: flag,
  139. msg: `任务出现错误${baseData.initData.dateString}:${e.message}` };
  140. this.ctx.logger.info(errData);
  141. await ctx.model.Local.StatisticsModel.create(errData);
  142. }
  143. }
  144. }
  145. async sign(ids, baseData, callback) {
  146. const { ctx } = this;
  147. const result = await ctx.model.TaskRecordModel.find({ _id: { $in: ids } });
  148. let flag = false;
  149. if (result) {
  150. flag = result.every(item => {
  151. const time = moment(item.last_task_data).valueOf();
  152. return time >= baseData.timeRangData.endTime;
  153. });
  154. }
  155. if (flag) {
  156. // 可以执行
  157. await callback();
  158. } else {
  159. // 不能执行 延迟执行
  160. const errData =
  161. { ...baseData.initData, start_time: new Date(), end_time: new Date(),
  162. type: 'cond',
  163. msg: `任务出现延时${baseData.initData.dateString}:${ids.join(',')}` };
  164. this.ctx.logger.info(errData);
  165. await ctx.model.Local.StatisticsModel.create(errData);
  166. }
  167. }
  168. createBaseData(start, end) {
  169. const isForceUpdate = false;
  170. const yesterday = start || this.ctx.helper.yesterday();
  171. const today = end || this.ctx.helper.today();
  172. const initData = {
  173. year: moment(yesterday).year(),
  174. month: moment(yesterday).month() + 1,
  175. day: moment(yesterday).date(),
  176. dateString: moment(yesterday).format('YYYY-MM-DD'),
  177. create_date: yesterday,
  178. // start_time: new Date(),
  179. // end_time: new Date()
  180. };
  181. if (yesterday > today) {
  182. this.ctx.throw('任务开始时间大于结束时间');
  183. }
  184. const timeRangData = { startTime: yesterday, endTime: today };// 这边可以做循环处理
  185. return { timeRangData, initData, isForceUpdate };
  186. }
  187. }
  188. module.exports = StatisticsService;