You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

223 lines
6.9 KiB

'use strict';
const moment = require('moment');
async function getPatrolPlan (ctx, next) {
try {
const models = ctx.fs.dc.models;
const { limit, page, userId, name, projectName } = ctx.query;
let where = {}
let userWhere = {};
let projectWhere = {};
let options = {
order: [['id', 'desc']],
where,
include: [{
required: userId ? true : false,
model: models.User,
attributes: ['id', 'name'],
where: userWhere,
include: [{
model: models.Department,
attributes: ['id', 'name'],
}]
}, {
model: models.Project,
attributes: ['id', 'name'],
where: projectWhere,
}],
distinct: true,
};
if (name) {
options.where.name = { $like: `%${name}%` };
}
if (projectName) {
projectWhere.name = { $like: `%${projectName}%` };
}
if (limit) {
options.limit = Number(limit);
}
if (page && limit) {
options.offset = Number(page) * Number(limit);
}
if (userId) {
userWhere.id = userId;
where.startTime = { $lte: moment().format('YYYY-MM-DD') + ' 23:59:59' }
where.endTime = { $gte: moment().format('YYYY-MM-DD') + ' 00:00:00' }
where.nextTime = { $lte: moment().format('YYYY-MM-DD HH:mm:ss') }
}
let res = await models.PatrolPlan.findAndCountAll(options);
ctx.status = 200;
ctx.body = res;
} catch (error) {
ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
ctx.status = 400;
ctx.body = {
"message": "获取巡检计划失败"
}
}
}
async function createPatrolPlan(ctx, next) {
const transaction = await ctx.fs.dc.orm.transaction();
try {
const models = ctx.fs.dc.models;
const data = ctx.request.body;
const { name, way, structureId, startTime, endTime, frequency, points, userIds, templateId } = data;
let plan = { name, way, structureId, startTime, endTime, frequency, points, templateId };
const patrolPlanRes = await models.PatrolPlan.create({ ...plan, nextTime: moment().format() }, { transaction });
await models.PatrolPlanUser.bulkCreate(
userIds.map(uid => {
return {
patrolPlanId: patrolPlanRes.id,
userId: uid
}
}), { transaction }
)
await transaction.commit();
ctx.status = 204;
} catch (error) {
await transaction.rollback();
ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
ctx.status = 400;
ctx.body = {
"message": '新增巡检计划失败'
}
}
}
async function updatePatrolPlan (ctx, next) {
const transaction = await ctx.fs.dc.orm.transaction();
try {
let errMsg = '修改巡检计划失败';
const models = ctx.fs.dc.models;
const data = ctx.request.body;
const { name, way, structureId, startTime, endTime, frequency, points, userIds, templateId } = data;
const frequencyNum = Number(frequency.split('次')[0]);
const unit = frequency.split('/')[1];
const sTime = moment().startOf(unit === '天' ? 'day' : unit === '周' ? 'isoWeek' : 'month');
const eTime = moment().endOf(unit === '天' ? 'day' : unit === '周' ? 'isoWeek' : 'month');
const curPlanRecord = await models.PatrolRecord.findAll({
where: {
patrolPlanId: data.id,
inspectionTime: { $between: [sTime.format(), eTime.format()] },
}
});
const groupRecord = curPlanRecord.group(({ pointId }) => pointId);
let isComplete = true;
for (const p of points) {
if (!groupRecord[p.id]) {
isComplete = false;
continue;
} else {
if ((groupRecord[p.id].length) < frequencyNum) {
isComplete = false;
continue;
}
}
}
let plan = { name, way, structureId, startTime, endTime, frequency, points, templateId,
nextTime: isComplete ? eTime.format() : sTime.format()
};
if (data && data.id) {
await models.PatrolPlan.update(plan, {
where: { id: data.id },
transaction
})
await models.PatrolPlanUser.destroy({
where: { patrolPlanId: data.id },
transaction
})
await models.PatrolPlanUser.bulkCreate(
userIds.map(uid => {
return {
patrolPlanId: data.id,
userId: uid
}
}), { transaction }
)
} else {
errMsg = '请传入巡检计划id';
throw errMsg;
}
await transaction.commit();
ctx.status = 204;
} catch (error) {
await transaction.rollback();
ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
ctx.status = 400;
ctx.body = {
"message": errMsg
}
}
}
async function delPatrolPlan (ctx, next) {
const transaction = await ctx.fs.dc.orm.transaction();
try {
let errMsg = '删除巡检计划失败';
const models = ctx.fs.dc.models;
const { id } = ctx.params;
const record = await models.PatrolRecord.findOne({
where: { patrolPlanId: id }
});
if (record) {
errMsg = '不能删除有巡检记录的计划';
throw errMsg;
}
await models.PatrolPlanUser.destroy({
where: { patrolPlanId: id },
transaction
})
await models.PatrolPlan.destroy({
where: { id },
transaction
})
await transaction.commit();
ctx.status = 204;
} catch (error) {
await transaction.rollback();
ctx.fs.logger.error(`path: ${ctx.path}, error: ${error}`);
ctx.status = 400;
ctx.body = { message: error }
}
}
Array.prototype.group = function (callback, thisArg = null) {
// 参数合法性判断
if (typeof callback !== "function") {
throw new TypeError(`${callback} is not a function`);
}
const arr = this;
const length = this.length;
const grouper = Object.create(null);
for (let i = 0; i < length; i++) {
const key = callback.call(thisArg, arr[i], i, arr)
if (!grouper[key]) {
grouper[key] = [arr[i]]
} else {
grouper[key].push(arr[i])
}
}
return grouper;
};
module.exports = {
getPatrolPlan,
createPatrolPlan,
updatePatrolPlan,
delPatrolPlan,
}