Files
workflow/app/service/task.js
T
2024-05-17 11:58:04 +08:00

586 lines
26 KiB
JavaScript

'use strict';
const Service = require('egg').Service;
const _ = require("lodash");
const validateUtil = require('@jianghujs/jianghu/app/common/validateUtil');
const idGenerateUtil = require("@jianghujs/jianghu/app/common/idGenerateUtil");
const { BizError, errorInfoEnum } = require("../constant/error");
const dayjs = require('dayjs');
class TaskService extends Service {
async appendFileAfterHook() {
const { jianghuKnex } = this.app;
const { taskFormInput, taskId } = this.ctx.request.body.appData.actionData;
const fileInput = JSON.parse(taskFormInput).filter(item => item.type == 'file')
if (fileInput.length > 0) {
const insertData = []
const idSequence = await idGenerateUtil.idPlus({
knex: jianghuKnex,
startValue: 1000,
tableName: 'jianghujs_workflow.file',
columnName: 'idSequence',
plusValue: 1
});
fileInput.forEach(async element => {
element.answer.forEach(async file => {
const { filename, downloadPath, binarySize } = file
insertData.push({
fileId: "F" + (idSequence),
idSequence: idSequence,
fileBizId: taskId,
filename,
downloadPath,
binarySize
})
idSequence++
});
});
if (insertData.length > 0) await jianghuKnex('file', this.ctx).jhInsert(insertData);
}
}
async createTask() {
const { jianghuKnex } = this.app;
const { actionData } = this.ctx.request.body.appData;
const { taskConfigId, taskInfo, taskWorkflow, taskFormInput } = actionData
await jianghuKnex('task', this.ctx).jhInsert(actionData);
if (taskConfigId.startsWith('noticeTask-')) {
var data = {
...actionData,
taskInfo: JSON.parse(taskInfo),
taskWorkflow: JSON.parse(taskWorkflow),
taskFormInput: JSON.parse(taskFormInput),
}
// 往下走
await this.submitNode(data, '同意', 1, 'createTask')
}
}
async submitApproval() {
const { actionData } = this.ctx.request.body.appData;
const { updateItem, type } = actionData;
await this.submitNode(updateItem, type, 0, 'updateTask')
}
async amendTask() {
const { actionData } = this.ctx.request.body.appData;
var updateItem = {
...actionData,
taskInfo: JSON.parse(actionData.taskInfo),
taskWorkflow: JSON.parse(actionData.taskWorkflow)
}
await this.submitNode(updateItem, '同意', 1, 'createTask')
}
async submitNode(taskData, type, times, action) {
const { jianghuKnex } = this.app;
const { updateTaskData, historyInsertData, noticeInsertData } = await this.buildNext({ taskData: taskData, type: type, times: times, action: action })
console.log('updateTaskData------', updateTaskData);
console.log('historyInsertData------', historyInsertData);
console.log('noticeInsertData------', noticeInsertData);
await jianghuKnex.transaction(async trx => {
if (updateTaskData) await trx("task", this.ctx).where({ taskId: taskData.taskId }).jhUpdate(updateTaskData);
if (noticeInsertData.length > 0) await trx("notice_push", this.ctx).jhInsert(noticeInsertData);
if (historyInsertData.length > 0) await trx("task_history", this.ctx).jhInsert(historyInsertData);
})
}
async buildNext({ taskData, type, times, action }) {
var that = this
const { jianghuKnex } = that.app;
const { userId, username } = this.ctx.userInfo;
const { taskId, taskInfo, taskWorkflow, taskConfigId, taskEditUserList, taskEditedUserList, taskViewUserList } = taskData;
const taskHistory = await jianghuKnex('task_history')
.where({ taskId })
.where('taskConfigId', 'like', 'approvalTask-%')
.whereNot('taskHandleDesc', '=', '系统自动转交')
.select();
const userList = await jianghuKnex('enterprise_user').select();
var updateTaskData = {},
historyInsertData = [],
noticeInsertData = [],
curNode = await taskWorkflow.nodeList.find(node => node.id == taskConfigId),
curNodeType = curNode?.properties.type,
taskStatus = "running",
taskHistoryUser = [...taskHistory.map(h => h.createHistoryBy)],
editUserList = taskEditUserList && taskEditUserList.split(',') || [],
editedUserList = taskEditedUserList && taskEditedUserList.split(',') || [],
bannedUser = [];
const { autoApproval, abnormalType, abnormalUser } = taskInfo;
// 如果是审批进入,就加上本次审批人,用来判断可以自动审批的人
if (action == 'updateTask') taskHistoryUser.push(userId)
// 审批进入是没有createHistoryBy的,自动流转到下一个节点是有createHistoryBy的
if (!taskData?.createHistoryBy) taskData.createHistoryBy = [userId]
switch (curNodeType) {
case 'noticeTask':
taskData = {
...taskData,
taskLineTypeList: '抄送',
taskExplain: '抄送节点',
taskHandleDesc: '抄送',
createHistoryBy: taskEditUserList && taskEditUserList.split(',') || []
}
historyInsertData.push(...await this.createTaskHistory({ taskData, taskStatus, type }))
break;
case 'end':
taskData = {
...taskData,
taskLineTypeList: '结束',
taskExplain: '结束节点',
taskHandleDesc: '结束',
createHistoryBy: [userId]
}
// 插入任务的结束记录
historyInsertData.push(...await this.createTaskHistory({ taskData, taskStatus, type }))
break;
case 'approvalTask':
// times为0表示首次进入该函数,无迭代
if (times == 0) {
editUserList = editUserList.filter(u => u != userId)
editedUserList.splice(-1, 0, userId)
historyInsertData.push(...await this.createTaskHistory({ taskData, taskStatus, type }))
}
break;
default:
break;
}
// 再判断是否需要结束审批流或流转到下一节点
if (type == '同意') {
switch (curNodeType) {
case 'approvalTask':
var curApprovalType = curNode?.properties.approvalType;
if (['会签'].includes(curApprovalType)) {
await handleBanned()
// 自动审批
if (autoApproval == 1 && times == 1) {
var autoApprovelUser = _.intersection(taskHistoryUser, editUserList)
taskData = {
...taskData,
taskComment: null,
taskExplain: "自动审批",
taskHandleDesc: "同意",
taskLineTypeList: "同意",
createHistoryBy: autoApprovelUser,
operationAt: dayjs().format("YYYY-MM-DD HH:mm:ss")
}
historyInsertData.push(...await this.createTaskHistory({ taskData, taskStatus, type }))
editUserList = editUserList.filter(u => !autoApprovelUser.includes(u))
editedUserList = editedUserList.concat(autoApprovelUser)
}
// 判断是否全部审批完成
if (_.differenceWith(curNode.properties.userIdList, editedUserList, _.isEqual).length == 0) {
await goToNextNode()
} else {
_.assign(updateTaskData, {
taskConfigId: curNode.id,
taskEditUserList: editUserList?.join(','),
taskEditedUserList: editedUserList?.join(','),
})
}
} else if (['或签'].includes(curApprovalType)) {
if (times == 0) {
// 手动审批直接进入下一节点
await goToNextNode()
} else {
await handleBanned()
if (abnormalType == -1 && editedUserList.length > 0
|| abnormalType == 1 && editedUserList.filter(editUser => !bannedUser.includes(editUser)).length > 0
|| editUserList.length == 0) {
await goToNextNode()
} else {
// 自动流转,识别是否需要自动审批
if (editUserList.length > 0 && autoApproval == 1) {
var autoApprovelUser = _.intersection(taskHistoryUser, editUserList)
if (autoApprovelUser.length > 0) {
taskData = {
...taskData,
taskComment: null,
taskExplain: "自动审批",
taskHandleDesc: "同意",
taskLineTypeList: "同意",
createHistoryBy: [autoApprovelUser[0]],
operationAt: dayjs().format("YYYY-MM-DD HH:mm:ss")
}
historyInsertData.push(...await this.createTaskHistory({ taskData, taskStatus, type }))
await goToNextNode()
} else {
_.assign(updateTaskData, {
taskConfigId: curNode.id,
taskEditUserList: editUserList?.join(','),
taskEditedUserList: editedUserList?.join(','),
})
}
} else {
_.assign(updateTaskData, {
taskConfigId: curNode.id,
taskEditUserList: editUserList?.join(','),
taskEditedUserList: editedUserList?.join(','),
})
}
}
}
} else if (['依次审批'].includes(curApprovalType)) {
// 判断是否全部审批完成
if (_.differenceWith(curNode.properties.userIdList, editedUserList, _.isEqual).length == 0) {
await goToNextNode()
} else {
await handleBanned()
// 判断下一个是否可以自动审批
if (editUserList.length > 0) {
if (autoApproval == 1) {
while (editUserList.length > 0 && taskHistoryUser.includes(editUserList[0])) {
// 插入历史
taskData = {
...taskData,
taskEditUserList: editedUserList?.join(','),
taskEditedUserList: editedUserList?.join(','),
createHistoryBy: [editUserList[0]],
taskComment: null,
taskExplain: "自动审批",
taskHandleDesc: "同意",
taskLineTypeList: "同意",
operationAt: dayjs().format("YYYY-MM-DD HH:mm:ss")
}
historyInsertData.push(...await this.createTaskHistory({ taskData, taskStatus, type }))
editedUserList.push(editUserList[0])
editUserList.splice(0, 1)
}
if (editUserList.length == 0) {
await goToNextNode()
} else {
_.assign(updateTaskData, {
taskConfigId: curNode.id,
taskEditUserList: editUserList?.join(','),
taskEditedUserList: editedUserList?.join(','),
})
}
} else {
_.assign(updateTaskData, {
taskConfigId: curNode.id,
taskEditUserList: editUserList?.join(','),
taskEditedUserList: editedUserList?.join(','),
})
}
} else {
await goToNextNode()
}
}
}
break;
case 'noticeTask':
noticeInsertData.push({
noticeId: await idGenerateUtil.uuid(),
noticeName: "通知-审批-" + taskId,
noticeContent: taskData.taskEditUserList,
pushContent: '{}',
pushStatus: "success",
pushAt: dayjs().format("YYYY-MM-DD HH:mm:ss")
})
await goToNextNode()
break;
case 'end':
_.assign(updateTaskData, {
taskStatus: "success",
taskConfigId: null,
taskLineType: null,
taskEditUserList: null,
taskEditedUserList: null,
taskFinishAt: dayjs().format("YYYY-MM-DD HH:mm:ss")
})
break;
default:
break;
}
} else {
// 插入该条审批记录
historyInsertData.push(...await this.createTaskHistory({ taskData, taskStatus: 'end', type }))
// 直接结束任务
_.assign(updateTaskData, {
taskStatus: 'reject',
taskConfigId: null,
taskLineType: null,
taskEditUserList: null,
taskEditedUserList: null,
taskFinishAt: dayjs().format("YYYY-MM-DD HH:mm:ss")
})
}
return {
updateTaskData,
noticeInsertData,
historyInsertData
}
async function handleBanned() {
// 判断该节点有无账号被禁用的人
editUserList.forEach(editUser => {
var isBanned = userList.find(u => u.userId == editUser) == undefined ? true : false
if (isBanned) bannedUser.push(editUser)
return isBanned
})
if (bannedUser.length > 0) {
// 自动转交给指定人
if (abnormalType == 1 && userList.find(u => u.userId == abnormalUser) !== undefined) {
// 在被禁用账号后面加上被转交人
for (let i = editUserList.length - 1; i >= 0; i--) {
if (bannedUser.includes(editUserList[i])) {
editUserList.splice(i + 1, 0, abnormalUser);
}
}
var abnormalUserName = userList.find(u => u.userId == abnormalUser)?.username || abnormalUser + "(账号被禁用)"
// 插入禁用账号的历史记录
_.assign(taskData, {
taskComment: "账号禁用,系统自动转交" + abnormalUserName,
taskExplain: "系统自动转交",
taskHandleDesc: "同意",
taskLineTypeList: "同意",
createHistoryBy: bannedUser,
operationAt: dayjs().format("YYYY-MM-DD HH:mm:ss")
})
historyInsertData.push(...await that.createTaskHistory({ taskData, taskStatus, type }))
editUserList = editUserList.filter(editUser => !bannedUser.includes(editUser))
editedUserList = editedUserList ? editedUserList.concat(bannedUser) : bannedUser
// 修改审批流
var newUserIdList = curNode.properties.userIdList
for (let i = newUserIdList.length - 1; i >= 0; i--) {
if (bannedUser.includes(newUserIdList[i])) {
// 在被禁用账号后面加上被转交人
newUserIdList.splice(i + 1, 0, abnormalUser);
}
}
const foundNode = taskWorkflow.nodeList.find(node => node.id == curNode.id);
if (foundNode) {
foundNode.properties.userIdList = newUserIdList;
}
updateTaskData.taskWorkflow = JSON.stringify(_.cloneDeep(taskWorkflow))
if (taskViewUserList) {
updateTaskData.taskViewUserList = taskViewUserList.split(',').concat(abnormalUser).join(',')
} else {
updateTaskData.taskViewUserList = abnormalUser
}
} else {
// 自动同意
editUserList = editUserList.filter(editUser => !bannedUser.includes(editUser))
editedUserList = editedUserList ? editedUserList.concat(bannedUser) : bannedUser
_.assign(taskData, {
taskComment: "账号禁用,自动同意",
taskExplain: "系统自动转交",
taskHandleDesc: "同意",
taskLineTypeList: "同意",
createHistoryBy: bannedUser,
operationAt: dayjs().format("YYYY-MM-DD HH:mm:ss")
})
historyInsertData.push(...await that.createTaskHistory({ taskData, taskStatus, type }))
}
}
}
async function goToNextNode() {
var nextNode = await getNextNode()
const { id, properties: { userIdList } } = nextNode
editUserList = _.cloneDeep(userIdList);
editedUserList = null;
_.assign(taskData, {
taskConfigId: id,
taskEditUserList: editUserList?.join(','),
taskEditedUserList: editedUserList?.join(','),
taskComment: null,
taskExplain: null,
taskHandleDesc: null,
taskLineTypeList: null,
createHistoryBy: null,
operationAt: dayjs().format("YYYY-MM-DD HH:mm:ss")
})
const result = await that.buildNext({ taskData, type: '同意', times: 1, action })
const { updateTaskData: newUpdateTaskData, historyInsertData: newHistoryInsertData, noticeInsertData: newNoticeInsertData } = result
_.assign(updateTaskData, newUpdateTaskData)
historyInsertData.push(...newHistoryInsertData)
noticeInsertData.push(...newNoticeInsertData)
async function getNextNode() {
const { lineList, nodeList } = taskWorkflow
var line = lineList.find(l => l.sourceNodeId == curNode.id),
nextNode = nodeList.find(n => n.id == line.targetNodeId);
if (nextNode.properties.type === "conditionTask") {
nextNode = await getNextNode()
}
return nextNode
}
}
}
async createTaskHistory({ taskData, taskStatus, type }) {
// 解构 taskData 对象以简化访问
const { taskId, taskFormInput, taskConfigId, taskNextConfigList,
taskLineType, taskEditUserList, taskViewUserList,
taskComment, taskWorkflow, operationAt, createHistoryBy,
taskHandleDesc, taskExplain, taskLineTypeList } = taskData;
const history = []
// 计算任务持续时间
const taskCostDuration = Math.round(dayjs().diff(dayjs(operationAt)) / 1000);
createHistoryBy.forEach(userId => {
history.push(
{
taskId,
taskStatus,
taskFormInput: JSON.stringify(taskFormInput),
taskConfigId,
taskNextConfigList,
taskLineTypeList: taskLineTypeList || type,
taskEditUserList,
taskViewUserList,
taskComment,
taskWorkflow: JSON.stringify(taskWorkflow),
taskExplain: taskExplain || type,
taskHandleDesc: taskHandleDesc || type,
taskCostDuration,
createHistoryBy: userId,
createHistoryAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
}
)
})
return history
}
async getTaskWorkflow() {
const { jianghuKnex } = this.app;
const { taskId } = this.ctx.request.body.appData.actionData;
// 获取当前审批
const task = await jianghuKnex('task').where({ taskId }).select('taskWorkflow', 'taskConfigId', 'taskViewUserList').first();
const { taskWorkflow, taskViewUserList } = task
// 获取审批流历史
const taskHistory = await jianghuKnex('task_history').where({ taskId })
.select('taskConfigId', 'createHistoryBy', 'taskComment', 'taskHandleDesc', 'createHistoryAt', 'taskStatus');
// 获取人员
const userList = await jianghuKnex('enterprise_user').whereIn('userId', taskViewUserList.split(',')).select('userId', 'username')
if (!task) throw new Error('Task not found');
var workflowHistory = JSON.parse(taskWorkflow).nodeList.filter(n => !['start', 'end', 'conditionTask'].includes(n.properties.type))
.map(node => {
const { id, label, userIdList, approvalType } = node.properties
const userConfig = userIdList?.map(appUserId => {
var username = userList.find(u => u.userId == appUserId)?.username,
historyRecord = taskHistory.find(h => h.taskConfigId == node.id && h.createHistoryBy == appUserId);
username = username ? username : appUserId + '(账号被禁用)'
if (historyRecord) {
const { taskComment, taskHandleDesc, createHistoryAt, taskStatus } = historyRecord
return {
userId: appUserId,
username: username,
comment: taskComment,
handleDesc: taskHandleDesc,
createHistoryAt: dayjs(createHistoryAt || '').format('YYYY-MM-DD HH:mm:ss'),
taskStatus: taskStatus,
}
} else {
return {
userId: appUserId,
username: username,
}
}
})
var nodeStatus = '审批中'
if (id.startsWith('approvalTask')) {
if (approvalType == "或签") {
nodeStatus = _.some(userConfig, ['handleDesc', '拒绝']) ? '已拒绝' : _.some(userConfig, ['handleDesc', '同意']) ? '已同意' : '审批中'
} else {
var nodeStatus = _.some(userConfig, ['handleDesc', '拒绝']) ? '已拒绝' : _.every(userConfig, ['handleDesc', '同意']) ? '已同意' : '审批中'
}
} else if (id.startsWith('noticeTask')) {
nodeStatus = _.every(userConfig, u => u.createHistoryAt) ? '已抄送' : '抄送中'
}
return {
id,
label,
approvalType: approvalType, // 是审批节点就取审批形式
userList: userConfig,
nodeStatus: nodeStatus
}
})
return workflowHistory
}
async getTaskList() {
const { jianghuKnex } = this.app;
const { userId } = this.ctx.userInfo;
const task = await jianghuKnex('task').where({ taskStatus: 'running' }).where('taskEditUserList', 'like', '%' + userId + '%').select();
// 判断是否到该人审批
const result = task.filter(item => {
const { taskWorkflow, taskConfigId, taskEditUserList } = item
// 查看当前节点是否是"依次审批"
var isApproval = true,
type = JSON.parse(taskWorkflow).nodeList.find(node => node.id === taskConfigId)?.properties.approvalType
if (type === '依次审批' && !taskEditUserList.startsWith(userId)) {
isApproval = false
}
return isApproval
})
return result
}
}
module.exports = TaskService;