clearApply.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. const Subscription = require('egg').Subscription;
  3. const { ObjectId } = require('mongoose').Types;
  4. class ClearApply extends Subscription {
  5. // 通过 schedule 属性来设置定时任务的执行间隔等配置
  6. static get schedule() {
  7. return {
  8. interval: '1h', // 1 分钟间隔
  9. type: 'worker', // 指定所有的 worker 都需要执行
  10. };
  11. }
  12. // 执行函数:清除错误申请(没有学科或者期,教师的申请数据)
  13. async subscribe() {
  14. const settingModel = this.ctx.model.Setting;
  15. const applyModel = this.ctx.model.Apply;
  16. const trainModel = this.ctx.model.Trainplan;
  17. const teacherModel = this.ctx.model.Teacher;
  18. const subjectModel = this.ctx.model.Subject;
  19. const defaultSetting = await settingModel.findOne();
  20. // 查出默认数据
  21. const tranPlan = await trainModel.findOne({ _id: defaultSetting.planid }).lean();
  22. const allTeacher = await teacherModel.find({}).lean();
  23. const allSubject = await subjectModel.find({}).lean();
  24. // 分两步:1,期id分开:不在任何一个计划中的&在计划中的; 2. 在计划中的.查看科目和授课教师是否存在.日子过没过期
  25. const termids = tranPlan.termnum.map(i => ObjectId(i._id).toString());
  26. const startDate = `${tranPlan.year}-01-01`;
  27. const endDate = `${tranPlan.year}-12-31`;
  28. const thisYearPlan = await applyModel.find({ date: { $gte: startDate, $lte: endDate } }).lean();
  29. const inTermPlans = thisYearPlan.filter(f => termids.includes(f.termid));
  30. const notInTermPlans = thisYearPlan.filter(f => !termids.includes(f.termid));
  31. const errorList = inTermPlans.filter(f => !(allTeacher.find(t => ObjectId(t._id).equals(f.teacherid)) && allSubject.find(s => ObjectId(s._id).equals(f.subid))));
  32. const deleteIds = [ ...errorList.map(i => ObjectId(i._id).toString()), ...notInTermPlans.map(i => ObjectId(i._id).toString()) ];
  33. await applyModel.deleteMany({ _id: deleteIds });
  34. }
  35. }
  36. module.exports = ClearApply;