From e1e1f444eabfd2b885720b12a4c174f38bada9a5 Mon Sep 17 00:00:00 2001 From: Felipe Aquino Date: Sun, 22 Feb 2026 19:26:28 +0000 Subject: [PATCH] atualizacao de responsavel --- app/Http/Controllers/AlunosController.php | 81 ++++++--- app/Http/Controllers/UsersController.php | 192 +++++++++++++--------- dump.rdb | Bin 1704 -> 1704 bytes 3 files changed, 172 insertions(+), 101 deletions(-) diff --git a/app/Http/Controllers/AlunosController.php b/app/Http/Controllers/AlunosController.php index 53640a6..501834e 100644 --- a/app/Http/Controllers/AlunosController.php +++ b/app/Http/Controllers/AlunosController.php @@ -3,32 +3,42 @@ namespace App\Http\Controllers; use App\Models\Aluno; -use App\Models\turmas; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; +use Illuminate\Support\Facades\DB; class AlunosController extends Controller { public function index() { - $user = Auth()->user(); + $user = Auth::user(); // coordenação/secretaria (ou quem tiver) if ($user->can('alunos.ver_todos')) { - $alunos = Aluno::query()->get(); + $alunos = Aluno::query() + ->with(['turma', 'escola', 'user', 'responsaveis']) + ->orderBy('nome') + ->get(); + + // ✅ mantenha UMA view só (ajuste o nome conforme sua tela real) return view('escolas.alunos', compact('alunos')); } // aluno/responsável if ($user->can('alunos.ver_meus')) { $alunos = Aluno::query() + ->with(['turma', 'escola', 'user', 'responsaveis']) ->where(function ($q) use ($user) { $q->where('user_id', $user->id) - ->orWhereHas('responsaveis', fn($r) => $r->where('users.id', $user->id)); + ->orWhereHas('responsaveis', function ($r) use ($user) { + $r->where('users.id', $user->id); + }); }) + ->orderBy('nome') ->get(); - return view('alunos.index', compact('alunos')); + // ✅ a mesma view (evita duplicar telas) + return view('escolas.alunos', compact('alunos')); } abort(403); @@ -36,20 +46,53 @@ class AlunosController extends Controller public function updateOrCreate(Request $request) { + // ✅ Validação mínima (ajuste se quiser campos extras) + $data = $request->validate([ + 'cpf' => ['required', 'string', 'max:20'], + 'nome' => ['required', 'string', 'max:255'], + 'id_turma' => ['required', 'integer', 'exists:turmas,id'], + 'id_escola' => ['required', 'integer', 'exists:escolas,id'], + 'data_nascimento' => ['required', 'date'], + 'data_inscricao' => ['required', 'date'], + 'user_id' => ['nullable', 'integer', 'exists:users,id'], - $aluno = Aluno::updateOrCreate( - ['cpf' => $request->cpf], - [ - 'nome' => $request->nome, - 'id_turma' => $request->id_turma, - 'id_escola' => $request->id_escola, - 'data_nascimento' => $request->data_nascimento, - 'data_inscricao' => $request->data_inscricao, - 'cpf' => $request->cpf, - 'user_id' => $request->user_id, - 'responsavel_user_id' => $request->responsavel_user_id, - ] - ); - return redirect()->route('alunos')->with('success', 'Aluno Criado|Atualizado com sucesso.'); + // ✅ múltiplos responsáveis (users ids) + 'responsavel_ids' => ['nullable', 'array'], + 'responsavel_ids.*' => ['integer', 'exists:users,id'], + ]); + + DB::beginTransaction(); + + try { + $aluno = Aluno::updateOrCreate( + ['cpf' => $data['cpf']], + [ + 'nome' => $data['nome'], + 'id_turma' => $data['id_turma'], + 'id_escola' => $data['id_escola'], + 'data_nascimento' => $data['data_nascimento'], + 'data_inscricao' => $data['data_inscricao'], + 'cpf' => $data['cpf'], + 'user_id' => $data['user_id'] ?? null, + ] + ); + + // ✅ Pivot N:N responsáveis (se vier no request) + // - syncWithoutDetaching: adiciona sem apagar os existentes + // - sync: substitui os existentes + if (!empty($data['responsavel_ids'])) { + $aluno->responsaveis()->sync($data['responsavel_ids']); + } + + DB::commit(); + + return redirect() + ->route('alunos') + ->with('success', 'Aluno Criado|Atualizado com sucesso.'); + + } catch (\Throwable $e) { + DB::rollBack(); + throw $e; + } } } diff --git a/app/Http/Controllers/UsersController.php b/app/Http/Controllers/UsersController.php index ba0d2dc..cd61006 100644 --- a/app/Http/Controllers/UsersController.php +++ b/app/Http/Controllers/UsersController.php @@ -60,98 +60,126 @@ class UsersController extends Controller return response()->json($alunos); } - public function store(Request $request) - { - // validação base - $data = $request->validate([ - 'name' => ['required', 'string', 'max:255'], - 'email' => ['required', 'email', 'max:255', 'unique:users,email'], - 'password' => ['required', 'string', 'min:6', 'confirmed'], - 'escola_id' => ['nullable', 'integer', 'exists:escolas,id'], - 'role_name' => ['nullable', 'string'], // coordenacao/secretaria/responsavel/aluno/representante_de_turma - 'is_super_admin' => ['nullable', 'boolean'], +public function store(Request $request) +{ + // validação base + $data = $request->validate([ + 'name' => ['required', 'string', 'max:255'], + 'email' => ['required', 'email', 'max:255', 'unique:users,email'], + 'password' => ['required', 'string', 'min:6', 'confirmed'], - // usado quando role for aluno/responsavel - 'aluno_id' => ['nullable', 'integer', 'exists:alunos,id'], - ]); + 'escola_id' => ['nullable', 'integer', 'exists:escolas,id'], + 'role_name' => ['nullable', 'string'], // coordenacao/secretaria/responsavel/aluno/representante_de_turma + 'is_super_admin' => ['nullable', 'boolean'], - // super admin não precisa escola/role - $isSuper = (bool)($data['is_super_admin'] ?? false); - if ($isSuper) { - $data['escola_id'] = null; - $data['role_name'] = null; - $data['aluno_id'] = null; - } else { - // usuário comum precisa escola + role - if (empty($data['escola_id']) || empty($data['role_name'])) { - return back()->withErrors(['escola_id' => 'Selecione escola e cargo.'])->withInput(); - } + // aluno (1) + 'aluno_id' => ['nullable', 'integer', 'exists:alunos,id'], + + // responsável (N) + 'aluno_ids' => ['nullable', 'array'], + 'aluno_ids.*' => ['integer', 'exists:alunos,id'], + ]); + + $isSuper = (bool)($data['is_super_admin'] ?? false); + + // super admin não precisa escola/role + if ($isSuper) { + $data['escola_id'] = null; + $data['role_name'] = null; + $data['aluno_id'] = null; + $data['aluno_ids'] = []; + } else { + if (empty($data['escola_id']) || empty($data['role_name'])) { + return back()->withErrors(['escola_id' => 'Selecione escola e cargo.'])->withInput(); + } + } + + // valida vínculo de aluno conforme cargo + if (!$isSuper && $data['role_name'] === 'aluno') { + + if (empty($data['aluno_id'])) { + return back()->withErrors(['aluno_id' => 'Selecione o aluno para vincular.'])->withInput(); } - // Se for responsável/aluno, aluno_id é obrigatório - if (!$isSuper && in_array($data['role_name'], ['responsavel', 'aluno'], true)) { - if (empty($data['aluno_id'])) { - return back()->withErrors(['aluno_id' => 'Selecione o aluno para vincular.'])->withInput(); - } + $ok = Aluno::query() + ->withoutGlobalScope('escola') + ->where('id', $data['aluno_id']) + ->where('id_escola', $data['escola_id']) + ->exists(); - // valida se o aluno pertence à escola selecionada - $ok = Aluno::query() + if (!$ok) { + return back()->withErrors(['aluno_id' => 'Aluno não pertence à escola selecionada.'])->withInput(); + } + } + + if (!$isSuper && $data['role_name'] === 'responsavel') { + + $alunoIds = $request->input('aluno_ids', []); + if (count($alunoIds) === 0) { + return back()->withErrors(['aluno_ids' => 'Selecione pelo menos 1 aluno.'])->withInput(); + } + + // valida se TODOS os alunos pertencem à escola selecionada + $count = Aluno::query() + ->withoutGlobalScope('escola') + ->whereIn('id', $alunoIds) + ->where('id_escola', $data['escola_id']) + ->count(); + + if ($count !== count($alunoIds)) { + return back()->withErrors(['aluno_ids' => 'Um ou mais alunos não pertencem à escola selecionada.'])->withInput(); + } + + $data['aluno_ids'] = $alunoIds; + } + + app(PermissionRegistrar::class)->forgetCachedPermissions(); + + // cria usuário + $user = User::create([ + 'name' => $data['name'], + 'email' => $data['email'], + 'password' => Hash::make($data['password']), + 'is_super_admin' => $isSuper, + 'current_escola_id' => $data['escola_id'] ?? null, + ]); + + // vincula à escola (pivot user_escolas) + role por escola + if (!$isSuper && $user->current_escola_id) { + + $user->escolas()->syncWithoutDetaching([$user->current_escola_id]); + + // seta team e atribui role da escola + setPermissionsTeamId($user->current_escola_id); + + $role = Role::query() + ->where('name', $data['role_name']) + ->where('guard_name', 'web') + ->where('id_escola', $user->current_escola_id) + ->firstOrFail(); + + $user->syncRoles([$role]); + + // ✅ associações automáticas + if ($data['role_name'] === 'aluno') { + Aluno::query() ->withoutGlobalScope('escola') ->where('id', $data['aluno_id']) - ->where('id_escola', $data['escola_id']) - ->exists(); - - if (!$ok) { - return back()->withErrors(['aluno_id' => 'Aluno não pertence à escola selecionada.'])->withInput(); - } + ->update(['user_id' => $user->id]); } - app(PermissionRegistrar::class)->forgetCachedPermissions(); - - // cria usuário - $user = User::create([ - 'name' => $data['name'], - 'email' => $data['email'], - 'password' => Hash::make($data['password']), - 'is_super_admin' => $isSuper, - 'current_escola_id' => $data['escola_id'] ?? null, - ]); - - // vincula à escola (pivot) - if (!$isSuper && $user->current_escola_id) { - $user->escolas()->syncWithoutDetaching([$user->current_escola_id]); - - // seta team e atribui role da escola - setPermissionsTeamId($user->current_escola_id); - - $role = Role::query() - ->where('name', $data['role_name']) - ->where('guard_name', 'web') - ->where('id_escola', $user->current_escola_id) - ->firstOrFail(); - - $user->syncRoles([$role]); - - // associações automáticas com aluno - if ($data['role_name'] === 'responsavel') { - Aluno::query() - ->withoutGlobalScope('escola') - ->where('id', $data['aluno_id']) - ->update(['responsavel_user_id' => $user->id]); - } - - if ($data['role_name'] === 'aluno') { - Aluno::query() - ->withoutGlobalScope('escola') - ->where('id', $data['aluno_id']) - ->update(['user_id' => $user->id]); - } + if ($data['role_name'] === 'responsavel') { + // pivot aluno_responsaveis (N:N) + $user->alunosComoResponsavel()->syncWithoutDetaching($data['aluno_ids'] ?? []); } - - app(PermissionRegistrar::class)->forgetCachedPermissions(); - setPermissionsTeamId(null); - - return back()->with('success', 'Usuário criado com sucesso!'); } + + app(PermissionRegistrar::class)->forgetCachedPermissions(); + setPermissionsTeamId(null); + + return back()->with('success', 'Usuário criado com sucesso!'); +} + + } diff --git a/dump.rdb b/dump.rdb index 524c128359c2e9befc6ee3a3dac166fb5791d7ef..86feb614f5028875500a7702aff98a76a232126a 100644 GIT binary patch delta 116 zcmZ3%yMlLuf#9L=*_ppMN{drdbaPX44+V5jbc|wF=R7}g-eYbxw)1Us7#SD@9NZ^w zWHOz6knsi6!SKnenZh{^0=2RJ7qJ718%&mC