kimi
2020-05-23 82fbbf24939e150ee3cef90dc0dd843c9897a7e6
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
package com.highdatas.mdm.controller;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.highdatas.mdm.entity.*;
import com.highdatas.mdm.mapper.FlowsMapper;
import com.highdatas.mdm.pojo.*;
import com.highdatas.mdm.service.*;
import com.highdatas.mdm.service.act.*;
import com.highdatas.mdm.util.Constant;
import com.highdatas.mdm.util.DbUtils;
import com.highdatas.mdm.util.TodoClient;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author kimi
 * @description
 * @date 2019-12-13 10:57
 */
 
@Slf4j
@RestController
@RequestMapping("/act")
public class ActivitiController {
 
    @Autowired
    IdentityService identityService;
 
    @Autowired
    IFlowsService flowsService;
    @Autowired
    FlowsMapper flowsMapper;
 
    @Autowired
    HistoryService historyService;
 
    @Autowired
    RepositoryService repositoryService;
 
    @Autowired
    RuntimeService runtimeService;
 
    @Autowired
    TaskService taskService;
 
    @Autowired
    ActivitiService activitiService;
 
    @Autowired
    IMaintainService maintainService;
 
    @Autowired
    IMasterModifiedService masterModifiedService;
 
    @Autowired
    IMaintainFieldService maintainFieldService;
    @Autowired
    ISysFieldService fieldService;
    @Autowired
    TodoClient client;
    @Autowired
    IMenuMappingService menuMappingService;
 
 
 
    @RequestMapping(value = "/list/{pageNo}", method = RequestMethod.GET)
    public Result<List<Map<String, Object>>> list(@PathVariable Integer pageNo, HttpServletRequest request) {
        String filterSegment = request.getParameter("filterSegment");
        String pageSize = request.getParameter("pageSize");
        if (StringUtils.isEmpty(filterSegment)) {
            filterSegment = Constant.WHERE_DEFAULT;
        }
        List<Map<String, Object>> list = flowsMapper.selectVersion(filterSegment);
        for (Map<String, Object> one : list) {
            String newModelId = (String) one.get(Constant.ID);
            String url = "act/img/" + newModelId;
            one.put("imgurl", url);
        }
        Integer size;
        if (StringUtils.isEmpty(pageSize)) {
            size = 15;
        } else {
            size = Integer.valueOf(pageSize);
        }
        return fieldService.getPagedDataByList(list, pageNo, size);
    }
 
    @RequestMapping(value = "/img/{modelId}", method = RequestMethod.GET)
    public void image(@PathVariable String modelId, HttpServletResponse response) {
        InputStream is = repositoryService.getModelImg(modelId);
        if (is == null) {
            return;
        }
        response.setHeader("Content-Type", "image/png");
        try {
            OutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b, 0, 1024)) != -1) {
                outputStream.write(b, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
        }
 
    }
 
    @RequestMapping(value = "/deleteModel/{modelId}", method = RequestMethod.GET)
    public Result deleteModel(@PathVariable String modelId) {
        boolean b = repositoryService.deleteModel(modelId);
        if (b) {
            return Result.success(null);
        } else {
            return Result.error(CodeMsg.DELETE_ERROR);
        }
    }
 
    @RequestMapping(value = "/processlist", method = RequestMethod.GET)
    public Result<Result<JSONArray>> processlist(HttpServletRequest request) {
        Result<JSONArray> processList = repositoryService.getProcessList();
        return Result.success(processList);
    }
 
    @RequestMapping(value = "/modellist", method = RequestMethod.GET)
    public Result<Result<JSONArray>> modellist(HttpServletRequest request) {
        Result<JSONArray> processList = repositoryService.getProcessList();
        return Result.success(processList);
    }
 
    @RequestMapping(value = "/started", method = RequestMethod.POST)
    public Result<Object> startRun(@RequestBody JSONArray result) {
        for (int i = 0; i < result.size(); i++) {
            String flowId = result.getString(i);
            log.info(flowId);
        }
        return Result.success(null);
    }
 
    @RequestMapping(value = "/startRun/{key}", method = RequestMethod.GET)
    public Result<Object> startRun(@PathVariable String key, @RequestParam String businessId, HttpServletRequest request) {
        TUser user = DbUtils.getUser(request);
        String businessType = request.getParameter("businessType");
        ActivitiBusinessType type;
        if (StringUtils.isEmpty(businessType)) {
            type = ActivitiBusinessType.maintain;
        } else {
            type = ActivitiBusinessType.valueOf(businessType);
        }
        String content;
        if (type.equals(ActivitiBusinessType.maintain)) {
            Maintain maintain = maintainService.selectById(businessId);
            SysMenu menuByTableName = menuMappingService.getMenuByTableName(maintain.getTableName());
            content = menuByTableName.getName() + "主题新增版本需要审批";
        } else {
            MaintainField maintainField = maintainFieldService.selectById(businessId);
            SysMenu menuByTableName = menuMappingService.getMenuByTableName(maintainField.getTableName());
            content = menuByTableName.getName() + "主题修改字段需要审批";
        }
        boolean open = client.open(key, businessId, content, user.getUserId(), type);
        if (open) {
            return Result.success(CodeMsg.SUCCESS);
        } else {
            return Result.error(CodeMsg.Client_fail);
        }
    }
 
    @RequestMapping(value = "/start/{key}", method = RequestMethod.POST)
    public Result<Object> start(@PathVariable String key, @RequestBody JSONObject reqObj, HttpServletRequest request) {
        log.info("process start..");
        if (StringUtils.isEmpty(key)) {
            return Result.error(new CodeMsg(1000, "key is not found"));
        }
 
        String businessId = reqObj.getString("businessId");
        if (StringUtils.isEmpty(businessId)) {
            return Result.error(new CodeMsg(1000, "businessId is not found"));
        }
        String businessType = reqObj.getString("businessType");
        JSONObject variableObj = reqObj.getJSONObject("variableMap");
        Map<String, Object> variableMap = new HashMap<>();
        if (variableObj != null) {
            variableMap = DbUtils.JsonObjectToHashMap(variableObj);
        }
        ActivitiBusinessType type;
        if (StringUtils.isEmpty(businessType)) {
            type = ActivitiBusinessType.maintain;
        } else {
            type = ActivitiBusinessType.valueOf(businessType);
        }
 
        if (type.equals(ActivitiBusinessType.maintain)) {
            Maintain maintain = maintainService.selectById(businessId);
            boolean canStart = maintainService.getCanAct(maintain.getTableName());
            if (!canStart) {
                return Result.error(CodeMsg.ACT_RUN_ERROR);
            }
        }
 
        Object descObj = variableMap.get("desc");
        String desc;
        if (descObj == null) {
            desc = "创建新版本";
        } else {
            desc = descObj.toString();
        }
        HttpSession session = request.getSession();
        Date startDate = new Date();
        Flows flows = activitiService.start(key, session, businessId, type, variableMap);
        Date endDate = new Date();
        log.info("process start:" + (endDate.getTime() - startDate.getTime()) + "ms");
        if (flows == null) {
            return Result.error(CodeMsg.INSERT_ERROR);
        } else {
            if (type.equals(ActivitiBusinessType.field)) {
                MaintainField maintainField = maintainFieldService.selectById(businessId);
                maintainField.setFlowId(flows.getId());
                maintainField.setDesp(desc);
                maintainField.updateById();
            } else if (type.equals(ActivitiBusinessType.maintain)) {
                Maintain maintain = maintainService.selectById(businessId);
                maintain.setFlowId(flows.getId());
                maintain.setDesp(desc);
                maintain.updateById();
            }
            startDate = new Date();
            log.info("process save status:" + (startDate.getTime() - endDate.getTime()) + "ms");
            HashMap<String, Object> body = new HashMap();
            NextTaskUserInfo nestTaskAssignee = taskService.getNestTaskAssignee(flows.getWorkflowId());
            endDate = new Date();
            log.info("process find user info:" + (endDate.getTime() - startDate.getTime()) + "ms");
            body.put("activitiId", flows.getId());
            if (nestTaskAssignee == null) {
                body.put("roleIdList", null);
                body.put("userIdList", null);
            } else {
                body.put("roleIdList", nestTaskAssignee.getRoleIdList());
                body.put("userIdList", nestTaskAssignee.getUserIdList());
            }
            return Result.success(body);
        }
    }
 
    @RequestMapping(value = "/status/{flowid}", method = RequestMethod.GET)
    public ArrayList<HistoricActivityInstance> status(@PathVariable String flowid, HttpServletRequest request) {
        if (StringUtils.isEmpty(flowid)) {
            return null;
        }
        historyService.setSession(request.getSession());
        Flows flows = flowsService.selectById(flowid);
        if (flows == null) {
            return null;
        }
        String workflowid = flows.getWorkflowId();
        ArrayList<HistoricActivityInstance> historyAction = historyService.getHistoryAction(workflowid);
        return historyAction;
    }
 
    @RequestMapping(value = "{tableName}/history/{pageNo}", method = RequestMethod.GET)
    public Result history(@PathVariable String tableName, @PathVariable Integer pageNo, HttpServletRequest request) {
        historyService.setSession(request.getSession());
        String pageSizeStr = request.getParameter("pageSize");
 
        List<HistoricProcessInstance> processInstanceList = historyService.getHistoryTask();
        List<HistoricProcessInstance> subList = new ArrayList<>();
        for (HistoricProcessInstance historicProcessInstance : processInstanceList) {
            Flows flows = flowsService.selectOne(new EntityWrapper<Flows>().eq("workflow_id", historicProcessInstance.getId()));
            if (flows == null) {
                continue;
            }
            ActivitiBusinessType businessType = flows.getBusinessType();
            if (ActivitiBusinessType.maintain.equals(businessType)) {
                String businessId = flows.getBusinessId();
                Maintain maintain = maintainService.selectById(businessId);
                if (maintain == null) {
                    continue;
                }
                String maintainTableName = maintain.getTableName();
                if (maintainTableName.equalsIgnoreCase(tableName)) {
                    subList.add(historicProcessInstance);
                }
            }
        }
 
        Page page = new Page(subList.size());
        page.setPageNo(pageNo);
        if (!StringUtils.isEmpty(pageSizeStr)) {
            page.setPageSize(Integer.valueOf(pageSizeStr));
        }
 
        subList = subList.stream().skip(page.getBeginRecordNo_1()).limit(page.getPageSize()).collect(Collectors.toList());
        ArrayList<Map<String, Object>> result = new ArrayList<>();
        for (HistoricProcessInstance historicProcessInstance : subList) {
            HashMap<String, Object> one = new HashMap<>();
            String workflowId = historicProcessInstance.getId();
            String startUserId = historicProcessInstance.getStartUserId();
            TUser user = DbUtils.getUserById(startUserId);
            Flows flows = flowsService.selectOne(new EntityWrapper<Flows>().eq("workflow_id", workflowId));
            Maintain maintain = maintainService.selectById(flows.getBusinessId());
            one.put("userName", user.getUserName());
            one.put("id", flows.getId());
            one.put("status", flows.getStatus());
            one.put("createTime", flows.getCreateTime());
            result.add(one);
        }
 
        Collections.sort(result, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Date o1Date = (Date) o1.get("createTime");
                Date o2Date = (Date) o2.get("createTime");
                return o2Date.compareTo(o1Date);
            }
        });
 
        JSONObject object = new JSONObject();
        object.fluentPut("total", page.getRecordCount());
        object.fluentPut("size", page.getPageSize());
        object.fluentPut("pages", page.getPageCount());
        object.fluentPut("current", page.getPageNo());
        object.fluentPut("record", result);
 
        return Result.success(object);
    }
 
 
    @RequestMapping(value = "/diagram/{flowid}", method = RequestMethod.GET)
    public void getDiagram(@PathVariable String flowid, HttpServletResponse response) {
        if (StringUtils.isEmpty(flowid)) {
            return;
        }
        Flows flows = flowsService.selectById(flowid);
        if (flows == null) {
            return;
        }
        String workflowid = flows.getWorkflowId();
        runtimeService.getDiagram(workflowid, response);
    }
 
    @RequestMapping(value = "/run", method = RequestMethod.GET)
    public List<Map<String, String>> runTask(HttpServletRequest request) {
        historyService.setSession(request.getSession());
        List<Map<String, String>> myRunTask = historyService.getMyRunTask();
        return myRunTask;
    }
 
    @RequestMapping(value = "/todo", method = RequestMethod.GET)
    public Result todoTask(HttpServletRequest request) {
        String pageNo = request.getParameter("pageNo");
        String pageSize = request.getParameter("pageSize");
        if (StringUtils.isEmpty(pageNo)) {
            return activitiService.todoTask(request.getSession(), request.getParameter(Constant.tableName), 1, 15);
        }
        if (StringUtils.isEmpty(pageSize)) {
            return activitiService.todoTask(request.getSession(), request.getParameter(Constant.tableName), Integer.valueOf(pageNo), 15);
        }
        return activitiService.todoTask(request.getSession(), request.getParameter(Constant.tableName), Integer.valueOf(pageNo), Integer.valueOf(pageSize));
    }
 
    @RequestMapping(value = "/deal/{flowid}", method = RequestMethod.POST)
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Result doTask(@PathVariable String flowid, @RequestBody JSONObject reqObj, HttpServletRequest request) {
        if (StringUtils.isEmpty(flowid)) {
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        Flows flows = flowsService.selectById(flowid);
        if (flows == null) {
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        Boolean pass;
        try {
            pass = (boolean) reqObj.get("pass");
            if (pass == null) {
                return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
            }
 
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(CodeMsg.ERROR_PARAMS_NOT_MATHED);
        }
        HashMap<String, Object> vailableMap = DbUtils.JsonObjectToHashMap(reqObj);
 
        HttpSession session = request.getSession();
        taskService.setSession(session);
        ActivitiStatus status = flows.getStatus();
        String workflowId = flows.getWorkflowId();
//        Task task = TimeTaskService.geTask(workflowId);
//        String id = task.getId();
        String taskId = null;
        if (taskService.checkClaim(workflowId)) {
            taskId = taskService.claimTask(workflowId);
        }
 
        String reason;
        Object reasonObj = vailableMap.get("reason");
        if (reasonObj == null) {
            reason = "确认处理";
        }else  {
            reason = reasonObj.toString();
        }
        if (taskId == null) {
            Task task = taskService.geTask(workflowId);
            if (task == null) {
                return Result.error(CodeMsg.ERROR_ACTIVITI_NEXTTASK);
            }
            taskId = task.getId();
        }
 
        boolean completed = taskService.completeTask(taskId, pass, reason, vailableMap);
 
        if (completed) {
            NextTaskUserInfo nextTaskDefinition = null;
            boolean taskFinished = historyService.isTaskFinished(workflowId);
            if (taskFinished) {
                if (ActivitiStatus.refuse.equals(status)) {
                    flows.setStatus(ActivitiStatus.close);
                } else {
                    flows.setStatus(ActivitiStatus.open);
                }
 
                if (!pass) {
                    flows.setStatus(ActivitiStatus.close);
                }
 
                flowsService.aduitFinish(flows);
 
            } else {
                if (pass && flows.getStatus().equals(ActivitiStatus.refuse)) {
                    flows.setStatus(ActivitiStatus.working);
                } else if (!pass && flows.getStatus().equals(ActivitiStatus.working)) {
                    flows.setStatus(ActivitiStatus.refuse);
                }
                nextTaskDefinition = taskService.getNestTaskAssignee(workflowId);
 
            }
            HashMap<String, Object> body = new HashMap();
 
            body.put("status", flows.getStatus().name());
            if (nextTaskDefinition == null) {
                body.put("roleIdList", null);
                body.put("userIdList", null);
            } else {
                body.put("roleIdList", nextTaskDefinition.getRoleIdList());
                body.put("userIdList", nextTaskDefinition.getUserIdList());
            }
 
            flows.setUpdateTime(new Date());
            flowsService.updateById(flows);
            return Result.success(body);
        } else {
            return Result.success(CodeMsg.INSERT_ERROR);
        }
    }
 
    @RequestMapping(value = "/addActUser")
    public Result addActUser(@RequestParam String userId) {
        return identityService.addUser(userId);
    }
 
    @RequestMapping(value = "/addActRole")
    public Result addActRole(@RequestParam String roleId) {
        return identityService.addRole(roleId);
    }
 
    @RequestMapping(value = "/addActUserRole")
    public Result addActUserRole(@RequestParam String roleId, @RequestParam String userId) {
        return identityService.addUserRole(roleId, userId);
    }
 
    @RequestMapping(value = "/deleteActUserRole")
    public Result deleteActUserRole(@RequestParam String roleId, @RequestParam String userId) {
        return identityService.deleteUserRole(roleId, userId);
    }
 
    @RequestMapping(value = "/deleteActRole")
    public Result deleteActRole(@RequestParam String roleId) {
        return identityService.deleteRole(roleId);
    }
 
    @RequestMapping(value = "/deleteActUser")
    public Result deleteActUser(@RequestParam String userId) {
        return identityService.deleteUser(userId);
    }
 
 
    @RequestMapping(value = "/test")
    public Result test(@RequestParam String roleId, @RequestParam String roleId2, @RequestParam String userId) {
        identityService.deleteUserRole(roleId, userId);
        identityService.addUserRole(roleId, userId);
        identityService.deleteUserRole(roleId2, userId);
        return identityService.addUserRole(roleId2, userId);
    }
}