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