WorkFlowService.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. <?php
  2. namespace App\Service;
  3. use App\Model\Employee;
  4. use App\Model\WorkFlowInstances;
  5. use App\Model\WorkFlowInstancesNodes;
  6. use App\Model\WorkFlowTemplates;
  7. use Illuminate\Support\Facades\DB;
  8. class WorkFlowService extends Service
  9. {
  10. public function workFlowEdit($data,$user){
  11. list($status,$msg) = $this->workFlowRule($data, $user, false);
  12. if(!$status) return [$status,$msg];
  13. try {
  14. DB::beginTransaction();
  15. $model = WorkFlowTemplates::where('id', $data['id'])->first();
  16. $model->code = $data['code'] ?? '';
  17. $model->title = $data['title'] ?? '';
  18. $model->content = $data['content'] ?? '';
  19. $model->save();
  20. DB::commit();
  21. }catch (\Exception $exception){
  22. DB::rollBack();
  23. return [false,$exception->getMessage()];
  24. }
  25. return [true, ''];
  26. }
  27. public function workFlowAdd($data,$user){
  28. list($status,$msg) = $this->workFlowRule($data, $user);
  29. if(!$status) return [$status,$msg];
  30. try {
  31. DB::beginTransaction();
  32. $model = new WorkFlowTemplates();
  33. $model->code = $data['code'] ?? '';
  34. $model->title = $data['title'] ?? '';
  35. $model->content = $data['content'] ?? '';
  36. $model->crt_id = $user['id'];
  37. $model->top_depart_id = $user['top_depart_id'];
  38. $model->save();
  39. DB::commit();
  40. }catch (\Exception $exception){
  41. DB::rollBack();
  42. return [false,$exception->getMessage()];
  43. }
  44. return [true, ''];
  45. }
  46. public function workFlowDetail($data, $user){
  47. if($this->isEmpty($data,'id')) return [false,'请选择数据!'];
  48. $customer = WorkFlowTemplates::where('del_time',0)
  49. ->where('id',$data['id'])
  50. ->first();
  51. if(empty($customer)) return [false,'审批流不存在或已被删除'];
  52. $customer = $customer->toArray();
  53. $customer['crt_name'] = Employee::where('id',$customer['crt_id'])->value('title');
  54. $customer['crt_time'] = $customer['crt_time'] ? date("Y-m-d H:i:s",$customer['crt_time']): '';
  55. return [true, $customer];
  56. }
  57. public function workFlowCommon($data,$user, $field = []){
  58. if(empty($field)) $field = WorkFlowTemplates::$field;
  59. $model = WorkFlowTemplates::TopClear($user,$data);
  60. $model = $model->where('del_time',0)
  61. ->select($field)
  62. ->orderby('id', 'desc');
  63. if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
  64. if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
  65. if(! empty($data['id'])) $model->whereIn('id', $data['id']);
  66. if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
  67. $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
  68. $model->where('crt_time','>=',$return[0]);
  69. $model->where('crt_time','<=',$return[1]);
  70. }
  71. return $model;
  72. }
  73. public function workFlowList($data,$user){
  74. $model = $this->workFlowCommon($data, $user);
  75. $list = $this->limit($model,'',$data);
  76. $list = $this->fillData($list);
  77. return [true, $list];
  78. }
  79. public function workFlowRule(&$data, $user, $is_add = true) {
  80. if(empty($data['title'])) return [false, '审批流名称不能为空'];
  81. if(empty($data['code'])) return [false, '审批流编码不能为空'];
  82. if(empty($data['content'])) return [false, '审批流内容不能为空'];
  83. // 1. JSON 格式校验与转换
  84. $content = $data['content'];
  85. if (is_string($content)) {
  86. $content = json_decode($content, true);
  87. if (json_last_error() !== JSON_ERROR_NONE) {
  88. return [false, '审批流内容格式错误,不是有效的JSON'];
  89. }
  90. }
  91. // 2. 结构完整性校验
  92. if (!isset($content['nodes']) || !is_array($content['nodes'])) {
  93. return [false, '审批流配置缺少节点(nodes)信息'];
  94. }
  95. if (!isset($content['edges']) || !is_array($content['edges'])) {
  96. return [false, '审批流配置缺少连线(edges)信息'];
  97. }
  98. // 4. 业务唯一性校验
  99. $query = WorkFlowTemplates::where('code', $data['code'])
  100. ->where('top_depart_id', $user['top_depart_id'])
  101. ->where('del_time', 0);
  102. if (!$is_add) {
  103. if (empty($data['id'])) return [false, 'ID不能为空'];
  104. $query->where('id', '<>', $data['id']);
  105. }
  106. if ($query->exists()) return [false, '审批流编码已存在'];
  107. return [true, ''];
  108. }
  109. public function fillData($data){
  110. if(empty($data['data'])) return $data;
  111. $emp = (new EmployeeService())->getEmployeeMap(array_unique(array_merge_recursive(array_column($data['data'],'charge_id'), array_column($data['data'],'crt_id'))));
  112. foreach ($data['data'] as $key => $value){
  113. $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d H:i:s',$value['crt_time']) : '';
  114. $data['data'][$key]['crt_name'] = $emp[$value['crt_id']] ?? '';
  115. }
  116. return $data;
  117. }
  118. /**
  119. * 触发审批流实例
  120. * * @param string $templateCode 审批流唯一编码
  121. * @param int $documentId 业务单据ID
  122. * @param string $documentType 业务模型类名
  123. * @param array $user 当前操作用户信息
  124. */
  125. public function triggerWorkflow($templateCode, $documentId, $documentType, $user)
  126. {
  127. // 1. 获取对应的审批流模板
  128. $template = WorkFlowTemplates::where('code', $templateCode)
  129. ->where('top_depart_id', $user['top_depart_id'])
  130. ->where('del_time', 0)
  131. ->first();
  132. if (!$template) return [false, '审批模板不存在'];
  133. // 2. 创建流程主实例
  134. $instance = WorkFlowInstances::create([
  135. 'template_id' => $template->id,
  136. 'document_id' => $documentId,
  137. 'document_type' => $documentType,
  138. 'status' => 'processing',
  139. 'crt_id' => $user['id'],
  140. 'crt_time' => time(),
  141. 'upd_time' => time(),
  142. 'top_depart_id' => $user['top_depart_id']
  143. ]);
  144. // 获取前端原始 JSON 中的节点和连线 [cite: 1]
  145. $nodes = $template->content['nodes'];
  146. $edges = $template->content['edges'];
  147. // 3. 准备批量插入的节点数据
  148. $insertNodes = [];
  149. foreach ($nodes as $node) {
  150. $nodeKey = $node['id'];
  151. // 从 edges 中寻找当前节点的前置 (source 为谁) 和 后置 (target 为谁) [cite: 1]
  152. // 这里的 source 和 target 是 edges 顶层的字符串 ID
  153. $prev = collect($edges)->where('target', $nodeKey)->pluck('source')->first();
  154. $next = collect($edges)->where('source', $nodeKey)->pluck('target')->first();
  155. $insertNodes[] = [
  156. 'instance_id' => $instance->id,
  157. 'node_key' => $nodeKey,
  158. 'label' => $node['label'] ?? '未命名节点',
  159. 'prev_node_key' => $prev, // 上级节点 ID
  160. 'next_node_key' => $next, // 下级节点 ID
  161. // 审批人快照存储 [cite: 1]
  162. 'assignees' => json_encode($node['data']['assignees'] ?? []),
  163. // 审批类型:1 会签,2 或签 [cite: 1]
  164. 'approval_type' => $node['data']['type'] ?? 2,
  165. // 初始状态逻辑:如果没有前置节点,说明是首节点,直接进入“审批中”状态
  166. 'status' => $prev ? 0 : 1,
  167. 'handled_time' => 0,
  168. 'crt_time' => time(),
  169. 'upd_time' => time(),
  170. 'crt_id' => $user['id'],
  171. 'top_depart_id' => $user['top_depart_id']
  172. ];
  173. }
  174. // 4. 写入节点实例表
  175. WorkFlowInstancesNodes::insert($insertNodes);
  176. return [true, $instance->id];
  177. }
  178. /**
  179. * 获取当前用户的待办审核列表
  180. */
  181. public function getMyPendingApprovals($userId, $topDepartId)
  182. {
  183. // 1. 在节点实例表中查询
  184. // 条件:公司隔离 + 状态为审批中(1) + 审批人JSON中包含当前用户ID
  185. $pendingNodes = WorkFlowInstancesNodes::where('top_depart_id', $topDepartId)
  186. ->where('status', 1) // 1 = 审批中
  187. ->whereRaw('JSON_CONTAINS(assignees, JSON_OBJECT("id", ?))', [$userId])
  188. ->get();
  189. if ($pendingNodes->isEmpty()) {
  190. return [];
  191. }
  192. // 2. 获取关联的实例信息和业务单据信息
  193. // 建议在 Model 中定义好 belongsTo 关系
  194. $instanceIds = $pendingNodes->pluck('instance_id')->unique();
  195. $instances = WorkFlowInstances::with(['template']) // 关联查出模板名称等信息
  196. ->whereIn('id', $instanceIds)
  197. ->get()
  198. ->keyBy('id');
  199. // 3. 组装返回数据
  200. $result = $pendingNodes->map(function ($node) use ($instances) {
  201. $instance = $instances[$node->instance_id] ?? null;
  202. return [
  203. 'node_instance_id' => $node->id, // 节点实例ID(审批接口要用)
  204. 'instance_id' => $node->instance_id, // 流程实例ID
  205. 'node_label' => $node->label, // 当前环节名称(如:财务审批)
  206. 'document_id' => $instance->document_id ?? 0, // 业务单据ID
  207. 'document_type' => $instance->document_type ?? '', // 业务模型
  208. 'flow_title' => $instance->template->title ?? '未知流程',
  209. 'apply_time' => $instance->crt_time ?? 0, // 发起时间
  210. 'approval_type' => $node->approval_type, // 1会签/2或签
  211. ];
  212. });
  213. return $result;
  214. }
  215. }