WorkFlowService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. <?php
  2. namespace App\Service;
  3. use App\Model\Draft;
  4. use App\Model\Employee;
  5. use App\Model\SysMenu;
  6. use App\Model\WorkFlowInstances;
  7. use App\Model\WorkFlowInstancesNodes;
  8. use App\Model\WorkFlowTemplates;
  9. use Illuminate\Support\Facades\DB;
  10. class WorkFlowService extends Service
  11. {
  12. public function workFlowEdit($data,$user){
  13. list($status,$msg) = $this->workFlowRule($data, $user, false);
  14. if(!$status) return [$status,$msg];
  15. try {
  16. DB::beginTransaction();
  17. $model = WorkFlowTemplates::where('id', $data['id'])->first();
  18. $model->code = $data['code'] ?? '';
  19. $model->title = $data['title'] ?? '';
  20. $model->content = $data['content'] ?? '';
  21. $model->save();
  22. DB::commit();
  23. }catch (\Exception $exception){
  24. DB::rollBack();
  25. return [false,$exception->getMessage()];
  26. }
  27. return [true, ''];
  28. }
  29. public function workFlowAdd($data,$user){
  30. list($status,$msg) = $this->workFlowRule($data, $user);
  31. if(!$status) return [$status,$msg];
  32. try {
  33. DB::beginTransaction();
  34. $model = new WorkFlowTemplates();
  35. $model->code = $data['code'] ?? '';
  36. $model->title = $data['title'] ?? '';
  37. $model->content = $data['content'] ?? '';
  38. $model->crt_id = $user['id'];
  39. $model->top_depart_id = $user['top_depart_id'];
  40. $model->save();
  41. DB::commit();
  42. }catch (\Exception $exception){
  43. DB::rollBack();
  44. return [false,$exception->getMessage()];
  45. }
  46. return [true, ''];
  47. }
  48. public function workFlowDetail($data, $user){
  49. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  50. $customer = WorkFlowTemplates::where('del_time',0)
  51. ->where('id',$data['id'])
  52. ->first();
  53. if(empty($customer)) return [false,'审批流不存在或已被删除'];
  54. $customer = $customer->toArray();
  55. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  56. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  57. return [true, $customer];
  58. }
  59. public function workFlowDel($data, $user){
  60. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  61. $customer = WorkFlowTemplates::where('del_time',0)
  62. ->where('id',$data['id'])
  63. ->first();
  64. if(empty($customer)) return [false,'审批流不存在或已被删除'];
  65. $customer->del_time = time();
  66. $customer->save();
  67. return [true, ''];
  68. }
  69. public function workFlowCommon($data,$user, $field = []){
  70. if(empty($field)) $field = WorkFlowTemplates::$field;
  71. $model = WorkFlowTemplates::TopClear($user,$data);
  72. $model = $model->where('del_time',0)
  73. ->select($field)
  74. ->orderby('id', 'desc');
  75. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  76. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  77. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  78. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  79. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  80. $model->where('crt_time','>=',$return[0]);
  81. $model->where('crt_time','<=',$return[1]);
  82. }
  83. return $model;
  84. }
  85. public function workFlowList($data,$user){
  86. $model = $this->workFlowCommon($data, $user);
  87. $list = $this->limit($model,'',$data);
  88. $list = $this->fillData($list);
  89. return [true, $list];
  90. }
  91. public function workFlowRule(&$data, $user, $is_add = true) {
  92. if(empty($data['title'])) return [false, '审批流名称不能为空'];
  93. if(empty($data['code'])) return [false, '审批流编码不能为空'];
  94. if(empty($data['content'])) return [false, '审批流内容不能为空'];
  95. // 1. JSON 格式校验与转换
  96. $content = $data['content'];
  97. if (is_string($content)) {
  98. $content = json_decode($content, true);
  99. if (json_last_error() !== JSON_ERROR_NONE) {
  100. return [false, '审批流内容格式错误,不是有效的JSON'];
  101. }
  102. }
  103. // 2. 结构完整性校验
  104. if (!isset($content['nodes']) || !is_array($content['nodes'])) {
  105. return [false, '审批流配置缺少节点(nodes)信息'];
  106. }
  107. if (!isset($content['edges']) || !is_array($content['edges'])) {
  108. return [false, '审批流配置缺少连线(edges)信息'];
  109. }
  110. $data['content'] = $content;
  111. // 4. 业务唯一性校验
  112. $query = WorkFlowTemplates::where('code', $data['code'])
  113. ->where('top_depart_id', $user['top_depart_id'])
  114. ->where('del_time', 0);
  115. if (!$is_add) {
  116. if (empty($data['id'])) return [false, 'ID不能为空'];
  117. $query->where('id', '<>', $data['id']);
  118. }
  119. if ($query->exists()) return [false, '审批流编码已存在'];
  120. return [true, ''];
  121. }
  122. public function fillData($data){
  123. if(empty($data['data'])) return $data;
  124. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_merge_recursive(array_column($data['data'],'charge_id'), array_column($data['data'],'crt_id'))));
  125. foreach ($data['data'] as $key => $value){
  126. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  127. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  128. }
  129. return $data;
  130. }
  131. /**
  132. * 触发审批流实例
  133. * * @param string $templateCode 审批流唯一编码
  134. * @param int $documentId 业务单据ID
  135. * @param string $documentType 业务模型类名
  136. * @param array $user 当前操作用户信息
  137. */
  138. public function triggerWorkflow($templateID, $documentId, $documentType, $user)
  139. {
  140. if($user['select_tree_type'] == SysMenu::tree_type_zero) return [true, ''];
  141. // 1. 获取对应的审批流模板
  142. $template = WorkFlowTemplates::where('id', $templateID)
  143. ->where('top_depart_id', $user['top_depart_id'])
  144. ->where('del_time', 0)
  145. ->first();
  146. if (!$template) return [false, '审批模板不存在'];
  147. // 2. 创建流程主实例
  148. $instance = WorkFlowInstances::create([
  149. 'template_id' => $template->id,
  150. 'document_id' => $documentId,
  151. 'document_type' => $documentType,
  152. 'status' => WorkFlowInstances::status_two, // 激活
  153. 'crt_id' => $user['id'],
  154. 'crt_time' => time(),
  155. 'upd_time' => time(),
  156. 'top_depart_id' => $user['top_depart_id']
  157. ]);
  158. // 获取前端原始 JSON 中的节点和连线 [cite: 1]
  159. $nodes = $template->content['nodes'];
  160. $edges = $template->content['edges'];
  161. // 3. 准备批量插入的节点数据
  162. $insertNodes = [];
  163. foreach ($nodes as $node) {
  164. $nodeKey = $node['id'];
  165. // 从 edges 中寻找当前节点的前置 (source 为谁) 和 后置 (target 为谁) [cite: 1]
  166. // 这里的 source 和 target 是 edges 顶层的字符串 ID
  167. $prev = collect($edges)->where('target', $nodeKey)->pluck('source')->first();
  168. $next = collect($edges)->where('source', $nodeKey)->pluck('target')->first();
  169. $tempAssignees = $node['data']['assignees'] ?? [];
  170. foreach($tempAssignees as $k => $person) {
  171. $tempAssignees[$k]['is_pass'] = 0; // 0-未审,1-通过,2-驳回
  172. $tempAssignees[$k]['mark'] = '';
  173. $tempAssignees[$k]['pass_time'] = 0;
  174. }
  175. $insertNodes[] = [
  176. 'instance_id' => $instance->id,
  177. 'node_key' => $nodeKey,
  178. 'label' => $node['label'] ?? '未命名节点',
  179. 'prev_node_key' => $prev, // 上级节点 ID
  180. 'next_node_key' => $next, // 下级节点 ID
  181. // 审批人快照存储 [cite: 1]
  182. 'assignees' => json_encode($tempAssignees),
  183. // 审批类型:1 会签,2 或签 [cite: 1]
  184. 'approval_type' => $node['data']['type'] ?? 2,
  185. // 初始状态逻辑:如果没有前置节点,说明是首节点,直接进入“审批中”状态
  186. 'status' => $prev ? 0 : 1,
  187. 'handled_time' => 0,
  188. 'crt_time' => time(),
  189. 'upd_time' => time(),
  190. 'crt_id' => $user['id'],
  191. 'top_depart_id' => $user['top_depart_id']
  192. ];
  193. }
  194. // 4. 写入节点实例表
  195. WorkFlowInstancesNodes::insert($insertNodes);
  196. return [true, $instance->id];
  197. }
  198. /**
  199. * 获取当前用户的待办审核列表
  200. */
  201. public function getMyPendingApprovals($data, $user)
  202. {
  203. $userId = $user['id'];
  204. $topDepartId = $user['top_depart_id'];
  205. // 1. 构造查询对象
  206. $model = WorkFlowInstancesNodes::where('del_time', 0)
  207. ->where('top_depart_id', $topDepartId)
  208. ->where('status', 1)
  209. ->whereRaw('JSON_CONTAINS(assignees, JSON_OBJECT("id", ?))', [$userId])
  210. ->whereRaw('NOT JSON_CONTAINS(assignees, JSON_OBJECT("id", ?, "is_pass", 1))', [$userId])
  211. ->select('*')
  212. ->orderBy('id', 'desc');
  213. $pageData = $this->limit($model, '', $data);
  214. if (empty($pageData['data'])) return [true, $pageData];
  215. // 2. 提取当前页的所有流程实例 ID
  216. $instanceIds = array_unique(array_column($pageData['data'], 'instance_id'));
  217. // 3. 获取流程实例及其关联的模板
  218. $instances = WorkFlowInstances::with(['template'])
  219. ->whereIn('id', $instanceIds)
  220. ->get()
  221. ->keyBy('id');
  222. // --- 处理动态业务单据数据 ---
  223. // 4. 按业务类型分组,批量查出单据的 code 和 title
  224. $documentGroups = [];
  225. foreach ($instances as $ins) {
  226. $documentGroups[$ins->document_type][] = $ins->document_id;
  227. }
  228. $documentDataMap = []; // 存储结构: [type][id] => ['code' => ..., 'title' => ...]
  229. foreach ($documentGroups as $type => $ids) {
  230. // 这里根据你的 document_type (如 'item') 动态查询
  231. // 假设你的业务表都有 code 和 title 字段
  232. $docs = DB::table($type)
  233. ->whereIn('id', array_unique($ids))
  234. ->select('id', 'code', 'title')
  235. ->get()
  236. ->keyBy('id')
  237. ->toArray();
  238. $documentDataMap[$type] = $docs;
  239. }
  240. // 5. 组装最终返回数据
  241. foreach ($pageData['data'] as $key => $node) {
  242. $instance = $instances[$node['instance_id']] ?? null;
  243. // 获取关联业务表的具体数据
  244. $docDetail = null;
  245. if ($instance) {
  246. $docDetail = $documentDataMap[$instance->document_type][$instance->document_id] ?? null;
  247. }
  248. $pageData['data'][$key] = [
  249. 'node_instance_id' => $node['id'],
  250. 'instance_id' => $node['instance_id'],
  251. 'node_label' => $node['label'],
  252. 'document_id' => $instance->document_id ?? 0,
  253. 'document_type' => $instance->document_type ?? '',
  254. // --- 新增字段 ---
  255. 'document_code' => $docDetail->code ?? '', // 业务单据编号
  256. 'document_title' => $docDetail->title ?? '', // 业务单据标题
  257. 'workflow_title' => $instance->template->title ?? '', // 审批模板名
  258. 'crt_time' => !empty($instance->crt_time->timestamp) ? date('Y-m-d H:i:s', $instance->crt_time->timestamp) : '',
  259. 'approval_type' => $node['approval_type'],
  260. 'approval_type_title' => WorkFlowInstancesNodes::approval_type[$node['approval_type']] ?? '',
  261. ];
  262. }
  263. return [true, $pageData];
  264. }
  265. public function approval($data, $user){
  266. list($status, $msg, $result) = $this->approve($data, $user);
  267. if(! $status) return [false, $msg];
  268. if($result == 1 || $result == 2){
  269. $instance_id = $msg;
  270. $this->businessSettle($result, $instance_id);
  271. }
  272. return [true, ''];
  273. }
  274. public function businessSettle($result, $instance_id){
  275. $w = WorkFlowInstances::where('id', $instance_id)->first();
  276. if(empty($w)) return;
  277. $w = $w->toArray();
  278. $draft = Draft::where('del_time',0)
  279. ->where('document_type', $w['document_type'])
  280. ->where('document_id', $w['document_id'])
  281. ->where('top_depart_id', $w['top_depart_id'])
  282. ->latest()
  283. ->first();
  284. if($result == 1){ // 审核最终通过
  285. if(! empty($draft)){
  286. $draft_array = $draft->toArray();
  287. if($draft_array['opt_type'] == 1){
  288. //调用编辑接口 覆盖数据
  289. if($draft_array['document_type'] == 'item'){
  290. list($status, $msg) = (new ItemService())->itemEditSave($draft_array['content'], $draft_array['opt_user']);
  291. }elseif ($draft_array['document_type'] == 'item_node'){
  292. list($status, $msg) = (new ItemService())->itemNodeEditSave($draft_array['content'], $draft_array['opt_user']);
  293. }elseif ($draft_array['document_type'] == 'item_node_mission'){
  294. list($status, $msg) = (new ItemService())->itemNodeMissionEditSave($draft_array['content'], $draft_array['opt_user']);
  295. }
  296. }else{
  297. //单纯更新某个字段
  298. }
  299. }
  300. if(! $status) {
  301. //todo 回滚---;
  302. }
  303. }
  304. //通过驳回都要把源业务数据的审批中标识更新掉 目前只有审核中 和 无
  305. DB::table($w['document_type'])->where('id', $w['document_id'])->update(['approval_state' => 0]);
  306. //草稿更新
  307. if(! empty($draft)){
  308. $draft->del_time = time();
  309. $draft->save();
  310. }
  311. }
  312. /**
  313. * @param int $nodeInstanceId 节点实例ID
  314. * @param int $status 结果:2-通过,3-驳回
  315. * @param string $remark 意见
  316. * @param array $user 当前操作人
  317. *
  318. * 业务结果说明:0-审批中(继续等待), 1-最终通过(业务单据可改为已完成), 2-已驳回(业务单据可改为已拒绝)
  319. */
  320. public function approve($data, $user)
  321. {
  322. $nodeInstanceId = $data['node_instance_id'] ?? 0;
  323. $status = $data['status'] ?? 2;
  324. $remark = $data['mark'] ?? '';
  325. $currentNode = WorkFlowInstancesNodes::where('del_time',0)
  326. ->where('id', $nodeInstanceId)
  327. ->where('top_depart_id', $user['top_depart_id'])
  328. ->first();
  329. if (!$currentNode || $currentNode->status != 1) return [false, '环节无效或已处理', 0];
  330. $assignees = is_string($currentNode->assignees) ? json_decode($currentNode->assignees, true) : $currentNode->assignees;
  331. $myIndex = collect($assignees)->search(fn($item) => $item['id'] == $user['id']);
  332. if ($myIndex === false) return [false, '您不在审批人名单中', 0];
  333. try {
  334. DB::beginTransaction();
  335. $time = time();
  336. $assignees[$myIndex]['mark'] = $remark;
  337. $assignees[$myIndex]['pass_time'] = $time;
  338. // --- 情况 A:驳回 ---
  339. if ($status == 3) {
  340. $currentNode->status = 3;
  341. $currentNode->handled_time = $time;
  342. $assignees[$myIndex]['is_pass'] = 2;
  343. $currentNode->assignees = $assignees;
  344. $currentNode->save();
  345. WorkFlowInstances::where('id', $currentNode->instance_id)->update(['status' => WorkFlowInstances::status_four]);
  346. DB::commit();
  347. return [true, $currentNode->instance_id, 2];
  348. }
  349. // --- 情况 B:通过 ---
  350. $assignees[$myIndex]['is_pass'] = 1;
  351. $currentNode->assignees = $assignees;
  352. $shouldMoveToNext = false;
  353. if ($currentNode->approval_type == 2) {
  354. $shouldMoveToNext = true;
  355. } else {
  356. $unPassedCount = collect($assignees)->where('is_pass', '!=', 1)->count();
  357. if ($unPassedCount == 0) {
  358. $shouldMoveToNext = true;
  359. }
  360. }
  361. $finalResult = 0; // 默认:还在审批中
  362. if ($shouldMoveToNext) {
  363. $currentNode->status = 2;
  364. $currentNode->handled_time = $time;
  365. $currentNode->save();
  366. if (!empty($currentNode->next_node_key)) {
  367. $hasActiveNext = $this->activateNextNode($currentNode->instance_id, $currentNode->next_node_key);
  368. if (!$hasActiveNext) {
  369. // 如果逻辑上虽然有key但没找到下个节点,也视为终结
  370. WorkFlowInstances::where('id', $currentNode->instance_id)->update(['status' => WorkFlowInstances::status_three]);
  371. $finalResult = 1;
  372. }
  373. } else {
  374. // 没有下个节点,流程最终终结
  375. WorkFlowInstances::where('id', $currentNode->instance_id)->update(['status' => WorkFlowInstances::status_three]);
  376. $finalResult = 1; // 返回 1,表示业务层面可以执行“生效”动作
  377. }
  378. } else {
  379. // 会签中,还有人没审
  380. $currentNode->save();
  381. $finalResult = 0;
  382. }
  383. DB::commit();
  384. return [true, $currentNode->instance_id, $finalResult];
  385. } catch (\Exception $e) {
  386. DB::rollBack();
  387. return [false, $e->getMessage(), 0];
  388. }
  389. }
  390. private function activateNextNode($instanceId, $nextNodeKey)
  391. {
  392. $nextNode = WorkFlowInstancesNodes::where('instance_id', $instanceId)
  393. ->where('node_key', $nextNodeKey)
  394. ->where('del_time',0)
  395. ->first();
  396. if ($nextNode) {
  397. $nextNode->status = 1;
  398. $nextNode->save();
  399. return true;
  400. }
  401. return false;
  402. }
  403. }