with(['template', 'applicant']); $query->when($request->has('status'), fn($q) => $q->where('status', $request->status)); $query->when($request->applicant_id, fn($q, $v) => $q->where('applicant_id', $v)); return $this->paginate($query->latest()->paginate($request->input('per_page', 15))); } public function store(Request $request): JsonResponse { $validated = $request->validate([ 'title' => 'required|string|max:255', 'template_id' => 'nullable|exists:approval_templates,id', 'form_data' => 'nullable|array', 'related_type' => 'nullable|string|max:50', 'related_id' => 'nullable|integer', ]); $validated['applicant_id'] = auth()->id(); $validated['status'] = 0; return $this->success(Approval::create($validated)); } public function show(Approval $approval): JsonResponse { return $this->success($approval->load(['template', 'applicant', 'nodes.approver'])); } public function update(Request $request, Approval $approval): JsonResponse { if ($approval->status > 1) { return $this->error('该审批已完结,无法修改', 40001); } $validated = $request->validate([ 'title' => 'sometimes|string|max:255', 'form_data' => 'nullable|array', ]); $approval->update($validated); return $this->success($approval); } public function destroy(Approval $approval): JsonResponse { if ($approval->status > 1) { return $this->error('该审批已完结,无法删除', 40001); } $approval->delete(); return $this->success(null); } public function approve(Approval $approval): JsonResponse { $node = $approval->nodes() ->where('approver_id', auth()->id()) ->where('action', 0) ->where('node_order', $approval->current_node) ->first(); if (!$node) { return $this->error('无待处理的审批节点', 40001); } $node->update(['action' => 1, 'acted_at' => now()]); $pendingNodes = $approval->nodes()->where('action', 0)->exists(); if (!$pendingNodes) { $approval->update(['status' => 2]); } else { $approval->update([ 'status' => 1, 'current_node' => $approval->current_node + 1, ]); } return $this->success($approval->load('nodes')); } public function reject(Request $request, Approval $approval): JsonResponse { $node = $approval->nodes() ->where('approver_id', auth()->id()) ->where('action', 0) ->where('node_order', $approval->current_node) ->first(); if (!$node) { return $this->error('无待处理的审批节点', 40001); } $validated = $request->validate([ 'comment' => 'nullable|string|max:255', ]); $node->update([ 'action' => 2, 'comment' => $validated['comment'] ?? null, 'acted_at' => now(), ]); $approval->update(['status' => 3]); return $this->success($approval->load('nodes')); } public function withdraw(Approval $approval): JsonResponse { if ($approval->status > 1) { return $this->error('该审批已完结,无法撤回', 40001); } $approval->update(['status' => 4]); return $this->success($approval); } }