atualizacao de responsavel

This commit is contained in:
2026-02-22 19:26:28 +00:00
parent 05b7d0a82b
commit e1e1f444ea
3 changed files with 172 additions and 101 deletions

View File

@@ -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!');
}
}