ActTaskServiceImpl.java 17.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
package com.trash.activiti.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.activiti.api.runtime.shared.identity.UserGroupManager;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.runtime.shared.security.SecurityManager;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.bpmn.model.FormProperty;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.IdentityLink;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.trash.activiti.domain.ActWorkflowFormData;
import com.trash.activiti.domain.dto.ActTaskDTO;
import com.trash.activiti.domain.dto.ActWorkflowFormDataDTO;
import com.trash.activiti.mapper.ActReDeploymentMapper;
import com.trash.activiti.mapper.ActWorkflowFormDataMapper;
import com.trash.activiti.service.IActTaskService;
import com.trash.activiti.service.IActWorkflowFormDataService;
import com.trash.activiti.service.myTaskService;
import com.trash.common.core.page.PageDomain;
import com.trash.common.core.redis.RedisCache;
import com.trash.common.utils.RemoteServerUtils;
import com.trash.common.utils.SecurityUtils;
import com.trash.common.utils.ServletUtils;
import com.trash.common.utils.StringUtils;
import com.trash.common.utils.util.PostSms;
import com.trash.common.utils.vo.mt.JsonSmsSend;
import com.trash.common.utils.vo.mt.Mobile;

@Service
public class ActTaskServiceImpl implements IActTaskService {

	@Autowired
	private RepositoryService repositoryService;

	@Autowired
	private myTaskService taskRuntime;

	@Autowired
	private TaskService taskService;

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	private IActWorkflowFormDataService actWorkflowFormDataService;

	@Autowired
	private ActWorkflowFormDataMapper actWorkflowFormDataMapper;

	@Autowired
	private ActReDeploymentMapper actMapper;

	@Autowired
	SecurityManager securityManager;

	@Autowired
	UserGroupManager userGroupManager;

	HistoricProcessInstanceQuery processInstanceQuery;

	@Autowired
	private RedisCache redisCache;

	@Override
	public Page<ActTaskDTO> selectProcessDefinitionList(PageDomain pageDomain) {
		Page<ActTaskDTO> list = new Page<ActTaskDTO>();
		List<ActTaskDTO> actTaskDTOS = new ArrayList<>();

		if (ServletUtils.getParameter("role") != null) {
			List<String> posts = new ArrayList<>();
			posts.add(ServletUtils.getParameter("role"));
			SecurityUtils.getLoginUser().getUser().setPostIds(posts);
		}
		if (ServletUtils.getParameter("dept") != null) {
			List<String> roles = new ArrayList<>();
			roles.add(ServletUtils.getParameter("dept"));
			SecurityUtils.getLoginUser().getUser().setRoleIds(roles);
		}
		if (SecurityUtils.getLoginUser().getUser().getPostIds().size() == 0
				|| SecurityUtils.getLoginUser().getUser().getRoleIds().size() == 0) {
			return list;
		}

		String type = ServletUtils.getParameter("type");
		String prev = ServletUtils.getParameter("prev");
		String name = ServletUtils.getParameter("name");
		if (type != null && type.isEmpty()) {
			type = null;
		}
		if (prev != null && prev.isEmpty()) {
			prev = null;
		}

		String[] strings;
		Set<String> keys = new HashSet<String>();

		if (type != null && !type.isEmpty()) {
			strings = type.split(",");
			keys = new HashSet<String>();

			for (String str : strings) {
				keys.add(str);
			}
		}
		org.activiti.api.runtime.shared.query.Page<Task> pageTasks;

		int pageNum = pageDomain.getPageNum();
		int pageSize = pageDomain.getPageSize();
		if (prev == null) {
			pageTasks = taskRuntime.tasks(Pageable.of((pageNum - 1) * pageSize, pageSize), null, keys, name);
		} else {
			pageTasks = taskRuntime.tasks(Pageable.of(0, 999999), null, keys, name);
		}

		List<Task> tasks = pageTasks.getContent();
		int totalItems = pageTasks.getTotalItems();

		list.setTotal(totalItems);

		if (totalItems != 0) {

			Set<String> processInstanceIdIds = tasks.parallelStream().map(t -> t.getProcessInstanceId())
					.collect(Collectors.toSet());

			if (processInstanceIdIds.size() > 0) {

				List<Map<String, Object>> maps = actMapper.selectWorkByIds(processInstanceIdIds);

				for (Task task : tasks) {
					try {
						ActTaskDTO dto = new ActTaskDTO(task, maps.parallelStream()
								.filter(t -> t.get("instance_id").equals(task.getProcessInstanceId())).findAny().get());

						if (prev != null && !prev.isEmpty()
								&& (dto.getPrev() == null || !dto.getPrev().contains(prev))) {
							continue;
						}

						list.add(dto);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		if (prev != null) {
			list.setTotal(list.size());
		}

		return list;
	}

	@Override
	public Page<ActTaskDTO> selectTaskEndHistoryDefinitionList(PageDomain pageDomain) {

		int pageNum = pageDomain.getPageNum();
		int pageSize = pageDomain.getPageSize();

		Page<ActTaskDTO> list = new Page<ActTaskDTO>();

		ProcessEngine pes = ProcessEngines.getDefaultProcessEngine();
		HistoryService historyService = pes.getHistoryService();

		String username = securityManager.getAuthenticatedUserId();

		Map map = new HashedMap<>();

		String type = ServletUtils.getParameter("type");
		String name = ServletUtils.getParameter("name");
		if (type != null && type.isEmpty()) {
			type = null;
		}
		if (name != null && name.isEmpty()) {
			name = null;
		}
		map.put("username", username);
		if (name != null)
			map.put("name", name);

		List<HistoricProcessInstance> processInstanceList;

		HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery().involvedUser(username)
				.finished().orderByProcessInstanceStartTime().desc();

		if (name != null)
			query.processInstanceNameLike("%" + name + "%");

		if (type != null && !type.isEmpty()) {
			List<String> types = new ArrayList<String>();
			for (String string : type.split(",")) {
				types.add(string);
			}
			query.processDefinitionKeyIn(types);
		}

		list.setTotal(query.count());

		processInstanceList = query.listPage((pageNum - 1) * pageSize, pageSize);

		// List<ActWorkflowFormData> dataList =
		// actWorkflowFormDataMapper.selectActWorkFlowFormDataListByUser(username);

		if (processInstanceList.size() > 0) {

			Set<String> idString = new HashSet<String>();
			for (HistoricProcessInstance pi : processInstanceList) {
				idString.add(pi.getId());
			}

			List<Map<String, Object>> maps = actMapper.selectHistoryWorkByPIds(idString);

			for (HistoricProcessInstance p : processInstanceList) {
				try {
					ActTaskDTO dto = new ActTaskDTO(p, maps.parallelStream()
							.filter(pi -> p.getId().equals(pi.get("instance_id"))).findAny().get());

					list.add(dto);
				} catch (Exception e) {
					System.out.println(p.getBusinessKey());
					e.printStackTrace();
				}
			}

		}

		return list;
	}

	@Override
	public Page<ActTaskDTO> selectRuntimeTaskHistoryDefinitionList(PageDomain pageDomain) {
		Page<ActTaskDTO> list = new Page<ActTaskDTO>();

		int pageNum = pageDomain.getPageNum();
		int pageSize = pageDomain.getPageSize();
		String username = securityManager.getAuthenticatedUserId();

		Map map = new HashedMap<>();

		String type = ServletUtils.getParameter("type");
		String name = ServletUtils.getParameter("name");
		map.put("username", username);
		if (type != null && type.isEmpty()) {
			type = null;
		}
		if (name != null && name.isEmpty()) {
			name = null;
		}

		ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery().involvedUser(username);

		if (name != null)
			query.processInstanceNameLike("%" + name + "%");

		if (type != null && !type.isEmpty()) {
			Set<String> types = new HashSet<String>();
			for (String string : type.split(",")) {
				types.add(string);
			}
			query.processDefinitionKeys(types);
		}

		List<ProcessInstance> processInstanceList = query.list();

		list.setTotal(query.count());

		processInstanceList = query.listPage((pageNum - 1) * pageSize, pageSize);

		if (processInstanceList.size() > 0) {

			List<String> pids = processInstanceList.parallelStream().map(p -> p.getId()).collect(Collectors.toList());

			List<org.activiti.engine.task.Task> tasks = taskService.createTaskQuery().processInstanceIdIn(pids).list();

			Set<String> idString = new HashSet<String>();
			for (ProcessInstance pi : processInstanceList) {
				idString.add(pi.getId());
			}

			List<Map<String, Object>> maps = actMapper.selectWorkByIds(idString);

			List<ActWorkflowFormData> dataList = actWorkflowFormDataMapper
					.selectActWorkFlowFormDataListByUser(username);
			if (processInstanceList.size() > 0) {
				for (ProcessInstance p : processInstanceList) {
					try {
						ActTaskDTO dto = new ActTaskDTO(p, maps.parallelStream()
								.filter(pi -> p.getProcessInstanceId().equals(pi.get("instance_id"))).findAny().get(),
								dataList.parallelStream().filter(pi -> p.getBusinessKey().equals(pi.getBusinessKey()))
										.findAny().get(),
								tasks.parallelStream().filter(t -> p.getId().equals(t.getProcessInstanceId())).findAny()
										.get());

						list.add(dto);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
		}

		list.sort(new Comparator<ActTaskDTO>() {

			@Override
			public int compare(ActTaskDTO o1, ActTaskDTO o2) {
				// TODO Auto-generated method stub
				return (int) (o2.getCreatedDate().getTime() - o1.getCreatedDate().getTime());
			}
		});

		return list;
	}

	public void getCheckData(ActTaskDTO actTaskDTOS) {
		ActWorkflowFormData ActWorkflowFormData = new ActWorkflowFormData();
		ActWorkflowFormData.setBusinessKey(actTaskDTOS.getBusinessKey());
		ActWorkflowFormData.setCreateBy(securityManager.getAuthenticatedUserId());
		ActWorkflowFormData.setControlName("审批");

		ActWorkflowFormData = actWorkflowFormDataService.selectActWorkflowFormDataList(ActWorkflowFormData).get(0);

		actTaskDTOS.setCheckStatus(ActWorkflowFormData.getControlValue().equals("通过") ? "0" : "1");
		actTaskDTOS.setCreatedDate(ActWorkflowFormData.getCreateTime());

	}

	SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");

	@Override
	public List<String> formDataShow(String taskID) {
		Task task = taskRuntime.task(taskID);
		/*
		 * ---------------------------------------------------------------------
		 * --------- FormProperty_0ueitp2--__!!类型--__!!名称--__!!是否参数--__!!默认值 例子:
		 * FormProperty_0lovri0--__!!string--__!!姓名--__!!f--__!!同意!!__--驳回
		 * FormProperty_1iu6onu--__!!int--__!!年龄--__!!s
		 *
		 * 默认值:无、字符常量、FormProperty_开头定义过的控件ID
		 * 是否参数:f为不是参数,s是字符,t是时间(不需要int,因为这里int等价于string)
		 * 注:类型是可以获取到的,但是为了统一配置原则,都配置到
		 */

		// 注意!!!!!!!!:表单Key必须要任务编号一模一样,因为参数需要任务key,但是无法获取,只能获取表单key“task.getFormKey()”当做任务key
		UserTask userTask = (UserTask) repositoryService.getBpmnModel(task.getProcessDefinitionId())
				.getFlowElement(task.getFormKey());

		if (userTask == null) {
			return null;
		}
		List<FormProperty> formProperties = userTask.getFormProperties();
		List<String> collect = formProperties.stream().map(fp -> fp.getId()).collect(Collectors.toList());

		return collect;
	}

	@Override
	public int formDataSave(String taskID, List<ActWorkflowFormDataDTO> awfs) throws ParseException {
		Task task = taskRuntime.task(taskID);

		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).singleResult();

		Map<String, Object> str = processInstance.getProcessVariables();

		String desc = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult()
				.getDescription();
		// 办文办事功能:分管领导指定部门时,将部门code存入desc
		if (!StringUtils.isEmpty(awfs.get(0).getDeptCode())) {
			desc = awfs.get(0).getDeptCode();
		}

		Boolean hasVariables = false;// 没有任何参数
		HashMap<String, Object> variables = new HashMap<String, Object>();
		// 前端传来的字符串,拆分成每个控件
		List<ActWorkflowFormData> acwfds = new ArrayList<>();
		for (ActWorkflowFormDataDTO awf : awfs) {
			ActWorkflowFormData actWorkflowFormData = new ActWorkflowFormData(processInstance.getBusinessKey(), awf,
					task);
			acwfds.add(actWorkflowFormData);
			// 构建参数集合
			if (!"f".equals(awf.getControlIsParam())) {
				variables.put(awf.getControlId(), awf.getControlValue());
				hasVariables = true;
			}

			if (processInstance.getProcessDefinitionKey().equals("handleAffairs")
					&& awf.getControlId().equals("FormProperty_0aq22i0")) {
				variables.put("index", awf.getIndex());
			}
		} // for结束
		if (task.getAssignee() == null) {
			taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
		}
		if (hasVariables) {
			// 带参数完成任务
			taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID).withVariables(variables).build());
		} else {
			taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskID).build());
		}

		if (desc != null)
			updateThreesetpTask(processInstance, desc);

		// 写入数据库
		return actWorkflowFormDataService.insertActWorkflowFormDatas(acwfds);
	}

	private void updateThreesetpTask(ProcessInstance processInstance, String placeCode) {

		final org.activiti.engine.task.Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId())
				.singleResult();

		if (task == null)
			return;

		if (task != null) {
			new Thread(new Runnable() {

				@Override
				public void run() {

					List<Mobile> mobileList = new ArrayList<Mobile>();

					String number = actMapper.getPhoneNumber(processInstance.getProcessDefinitionKey(), task.getName());

					if (number != null) {
						String smsString = "工作提醒:您有新的工作流程,请及时处理。";
						Mobile mobile = new Mobile();
						mobile.setMobile(number);
						mobileList.add(mobile);

						if (processInstance.getProcessDefinitionKey().equals("workflow_constructsite")) {

							JSONObject json = RemoteServerUtils.getConstructionInfo(processInstance.getBusinessKey().split(":")[1]);
							if (json != null)
								smsString = "审批提醒:您有新的工作流程需要审批 " + json.getString("areaCodeName") + " "
										+ json.getString("name");

						}

						if (processInstance.getProcessDefinitionKey().equals("workflow_caseoffline")) {

							String dname = actMapper.getCaseTypeName("case_offline_type",
									processInstance.getBusinessKey().split(":")[1]);
							smsString = "案卷提醒:有一条" + dname + "的案卷,请及时处理。";
						}

						JsonSmsSend jsonSmsSend = PostSms.sendSms(mobileList, smsString);
						if (jsonSmsSend != null) {
							if (jsonSmsSend.getState() == 0) {
								System.out.println("发送成功");
							} else {
								System.out.println(jsonSmsSend.getMessage());
							}
						} else {
							System.out.println("发送返回空");
						}
					}

				}

			}).start();
		}

		task.setDescription(placeCode);

		List<IdentityLink> list = taskService.getIdentityLinksForTask(task.getId());

		if (list.size() == 1) {
			taskService.addCandidateUser(task.getId(), placeCode);
		}

		taskService.saveTask(task);

		if ("车辆所属企业".equals(task.getName())) {
			org.activiti.engine.task.Task task1 = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
			taskService.setAssignee(task1.getId(), placeCode);
			return;
		}

	}

	@Override
	public void deleteProcessById(String type) {
		runtimeService.deleteProcessInstance(type, "删除");
	}

	@Override
	public void endAllThreesteptask(String type) {

		List<ProcessInstance> processes = runtimeService.createProcessInstanceQuery().processDefinitionKey(type).list();

		for (ProcessInstance proc : processes) {
			if (type.equals(proc.getProcessDefinitionKey())) {
				try {

					String executionId = proc.getSuperExecutionId();
					Map<String, Object> map = proc.getProcessVariables();

					// runtimeService.removeVariable(executionId, variableName);

					runtimeService.deleteProcessInstance(proc.getId(), "超时");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}
}