fix(profile): prioriza nickname na exibição do card com fallback e validação#401
fix(profile): prioriza nickname na exibição do card com fallback e validação#401GustavoSimao wants to merge 3 commits into
Conversation
…lidação - Card mostra nickname quando definido, cai para o nome da conta conectada quando vazio/nulo, e para o username quando não há nome. - Input de nickname passa a ter estado próprio (nicknameInput) com validação de formato e feedback visual (borda vermelha + mensagem) no submit, com scroll até o campo em caso de erro. - Corrige bug em UpsertProfile onde nickname nulo (usuário limpando o campo) era ignorado no update, impedindo remover o apelido salvo.
📝 WalkthroughWalkthroughNickname persistence now converts empty strings to null and applies new nickname validation rules. Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
app-modules/profile/src/Actions/UpsertProfile.php (1)
78-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
__()for nickname validation messages.Hardcoded Portuguese strings break i18n consistency — every other validation message in this method uses
__()(lines 71, 75, 89, 93, 97, 105).♻️ Proposed refactor
if ($dto->nickname !== null) { if (mb_strlen($dto->nickname) > 100) { - $errors['nickname'] = ['O apelido deve ter no máximo 100 caracteres.']; + $errors['nickname'] = [__('validation.max.string', ['attribute' => __('panel-app::profile.fields.nickname'), 'max' => 100])]; } elseif (!preg_match("/^[\p{L}\p{M}\p{N}\s\-']+$/u", $dto->nickname)) { - $errors['nickname'] = ['Apenas letras, números, espaços, hífens e apóstrofos são permitidos.']; + $errors['nickname'] = [__('profile.validation.nickname_characters')]; } elseif (!preg_match('/[\p{L}]{2,}/u', $dto->nickname)) { - $errors['nickname'] = ['O apelido deve conter pelo menos 2 letras juntas.']; + $errors['nickname'] = [__('profile.validation.nickname_consecutive_letters')]; } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app-modules/profile/src/Actions/UpsertProfile.php` around lines 78 - 85, The nickname validation messages in UpsertProfile::handle are hardcoded Portuguese strings and should follow the same i18n pattern used elsewhere in this method. Replace each literal message in the nickname validation branch with __()-wrapped translation keys, matching the style of the other validation errors so all messages remain consistent and translatable.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app-modules/panel-app/src/Pages/ProfilePage.php`:
- Around line 407-416: The catch in ProfilePage::save/update around
resolve(UpsertProfile::class)->handle() is too narrow and only surfaces nickname
errors, which can hide validation failures from UpsertProfile::validate() for
other fields. Update the ValidationException handling to read the actual
field-specific error from the exception/validator for whichever key failed, and
only call addError('nickname') and dispatch('scroll-to-nickname') when nickname
is the failing field; otherwise route the message to the correct input or
rethrow/handle generically so non-nickname validation errors are not lost.
---
Nitpick comments:
In `@app-modules/profile/src/Actions/UpsertProfile.php`:
- Around line 78-85: The nickname validation messages in UpsertProfile::handle
are hardcoded Portuguese strings and should follow the same i18n pattern used
elsewhere in this method. Replace each literal message in the nickname
validation branch with __()-wrapped translation keys, matching the style of the
other validation errors so all messages remain consistent and translatable.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository YAML (base), Central YAML (inherited)
Review profile: CHILL
Plan: Pro
Run ID: 2be931e9-f7c6-4187-83c4-25d31f775251
📒 Files selected for processing (4)
app-modules/panel-app/resources/views/components/profile-media-header.blade.phpapp-modules/panel-app/resources/views/components/profile-preview-card.blade.phpapp-modules/panel-app/src/Pages/ProfilePage.phpapp-modules/profile/src/Actions/UpsertProfile.php
| try { | ||
| resolve(UpsertProfile::class)->handle($profile, $dto); | ||
| } catch (ValidationException $validationException) { | ||
| $this->addError('nickname', $validationException->validator->errors()->first('nickname')); | ||
| $this->dispatch('scroll-to-nickname'); | ||
|
|
||
| return; | ||
| } | ||
|
|
||
| $this->data['nickname'] = mb_trim($this->nicknameInput ?? '') ?: null; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Catch block silently swallows non-nickname validation errors.
UpsertProfile::validate() throws ValidationException for fields beyond nickname (about, headline, years_experience, expected_salary_min, expected_salary_max, social_links). The catch only extracts first('nickname'), which returns '' when no nickname key exists — resulting in an empty error message on the nickname field, a scroll to the wrong input, and the actual error being lost.
This is reachable today: the form has no gte:expected_salary_min rule on expected_salary_max, so min > max passes form validation but fails in UpsertProfile at lines 100–109, and that error is never surfaced.
🐛 Proposed fix
try {
resolve(UpsertProfile::class)->handle($profile, $dto);
} catch (ValidationException $validationException) {
- $this->addError('nickname', $validationException->validator->errors()->first('nickname'));
- $this->dispatch('scroll-to-nickname');
+ $errors = $validationException->validator->errors();
+
+ foreach ($errors->keys() as $key) {
+ $this->addError($key, $errors->first($key));
+ }
+
+ if ($errors->has('nickname')) {
+ $this->dispatch('scroll-to-nickname');
+ }
return;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try { | |
| resolve(UpsertProfile::class)->handle($profile, $dto); | |
| } catch (ValidationException $validationException) { | |
| $this->addError('nickname', $validationException->validator->errors()->first('nickname')); | |
| $this->dispatch('scroll-to-nickname'); | |
| return; | |
| } | |
| $this->data['nickname'] = mb_trim($this->nicknameInput ?? '') ?: null; | |
| try { | |
| resolve(UpsertProfile::class)->handle($profile, $dto); | |
| } catch (ValidationException $validationException) { | |
| $errors = $validationException->validator->errors(); | |
| foreach ($errors->keys() as $key) { | |
| $this->addError($key, $errors->first($key)); | |
| } | |
| if ($errors->has('nickname')) { | |
| $this->dispatch('scroll-to-nickname'); | |
| } | |
| return; | |
| } | |
| $this->data['nickname'] = mb_trim($this->nicknameInput ?? '') ?: null; |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@app-modules/panel-app/src/Pages/ProfilePage.php` around lines 407 - 416, The
catch in ProfilePage::save/update around resolve(UpsertProfile::class)->handle()
is too narrow and only surfaces nickname errors, which can hide validation
failures from UpsertProfile::validate() for other fields. Update the
ValidationException handling to read the actual field-specific error from the
exception/validator for whichever key failed, and only call addError('nickname')
and dispatch('scroll-to-nickname') when nickname is the failing field; otherwise
route the message to the correct input or rethrow/handle generically so
non-nickname validation errors are not lost.
…ovo binding UpsertProfile usava null tanto para campo nao tocado quanto para limpar nickname, quebrando updates parciais de outros callers. String vazia agora sinaliza limpar; null continua sendo nao tocado. ProfilePageTest atualizado para setar nicknameInput em vez do antigo data.nickname.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
app-modules/profile/src/Actions/UpsertProfile.php (1)
82-89: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winHardcoded Portuguese validation messages inconsistent with
__()used elsewhere in this method.Lines 84, 86, and 88 use raw Portuguese strings while every other validation message in this method (lines 75, 79, 93, 97, 101, 109) uses Laravel's
__()translation helper. This breaks localization consistency and makes messages harder to maintain.Additionally, the regex on line 85 uses
\swhich matches any whitespace (newlines, tabs, carriage returns), but the error message on line 86 says "espaços" (spaces). Consider replacing\swith a literal space character to match the stated contract.♻️ Proposed fix
if ($dto->nickname !== null && $dto->nickname !== '') { if (mb_strlen($dto->nickname) > 100) { - $errors['nickname'] = ['O apelido deve ter no máximo 100 caracteres.']; + $errors['nickname'] = __('validation.max.string', ['attribute' => 'nickname', 'max' => 100]); } elseif (!preg_match("/^[\p{L}\p{M}\p{N} \-']+$/u", $dto->nickname)) { - $errors['nickname'] = ['Apenas letras, números, espaços, hífens e apóstrofos são permitidos.']; + $errors['nickname'] = [__('validation.nickname.characters')]; } elseif (!preg_match('/[\p{L}]{2,}/u', $dto->nickname)) { - $errors['nickname'] = ['O apelido deve conter pelo menos 2 letras juntas.']; + $errors['nickname'] = [__('validation.nickname.consecutive_letters')]; } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app-modules/profile/src/Actions/UpsertProfile.php` around lines 82 - 89, The nickname validation in UpsertProfile::handle uses hardcoded Portuguese strings instead of the __() helper used elsewhere in this method, so switch those error messages to translated keys for consistency and maintainability. Also align the nickname regex with the stated contract by replacing the broad whitespace match in the nickname check with a literal space, since the message only अनुमति spaces, not tabs or newlines.app-modules/panel-app/tests/Feature/ProfilePageTest.php (1)
76-95: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMissing test coverage for nickname validation and clearing behavior.
The test covers the happy path only. No tests exercise the new validation rules (invalid characters, no consecutive letters, max length) or the nickname clearing flow (empty string → null in DB).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app-modules/panel-app/tests/Feature/ProfilePageTest.php` around lines 76 - 95, The ProfilePage test only covers the happy path for nickname saving, so add coverage in ProfilePageTest for the new nickname rules and clearing behavior. Extend the existing livewire(ProfilePage::class) cases to assert validation failures for invalid characters, consecutive letters, and max length, and add a save scenario where nicknameInput is set to an empty string and the persisted profile nickname becomes null. Use the existing ProfilePage and $this->profile assertions to keep the tests aligned with the component behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@app-modules/panel-app/tests/Feature/ProfilePageTest.php`:
- Around line 76-95: The ProfilePage test only covers the happy path for
nickname saving, so add coverage in ProfilePageTest for the new nickname rules
and clearing behavior. Extend the existing livewire(ProfilePage::class) cases to
assert validation failures for invalid characters, consecutive letters, and max
length, and add a save scenario where nicknameInput is set to an empty string
and the persisted profile nickname becomes null. Use the existing ProfilePage
and $this->profile assertions to keep the tests aligned with the component
behavior.
In `@app-modules/profile/src/Actions/UpsertProfile.php`:
- Around line 82-89: The nickname validation in UpsertProfile::handle uses
hardcoded Portuguese strings instead of the __() helper used elsewhere in this
method, so switch those error messages to translated keys for consistency and
maintainability. Also align the nickname regex with the stated contract by
replacing the broad whitespace match in the nickname check with a literal space,
since the message only अनुमति spaces, not tabs or newlines.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository YAML (base), Central YAML (inherited)
Review profile: CHILL
Plan: Pro
Run ID: 7bdd261c-fda1-4a52-b3ea-e2b108079a52
📒 Files selected for processing (3)
app-modules/panel-app/src/Pages/ProfilePage.phpapp-modules/panel-app/tests/Feature/ProfilePageTest.phpapp-modules/profile/src/Actions/UpsertProfile.php
🚧 Files skipped from review as they are similar to previous changes (1)
- app-modules/panel-app/src/Pages/ProfilePage.php
Contexto
A PR #398 propunha corrigir a exibição do apelido no cartão de perfil, que até então nunca usava o valor do apelido, o card sempre mostrava o nome da conta conectada, independente do que o usuário salvasse. A correção proposta usava
??como fallback, mas esse operador não cobre string vazia (''), sónull. O CodeRabbit apontou o problema na revisão, e outros revisores confirmaram o mesmo comportamento. A #398 foi fechada antes de ser mergeada.Ao investigar o fluxo completo, apareceram mais dois problemas ligados ao apelido: falta de validação de formato no formulário e um bug que impedia remover um apelido já salvo. Esta PR substitui a #398 e resolve os três pontos juntos.
O que muda
Exibição do cartão
Ordem de prioridade do nome exibido:
O fallback agora trata corretamente apelido vazio (
''), não sónull.Estado do formulário
O campo de apelido passou a usar uma variável própria,
nicknameInput, ligada diretamente ao input (wire:model.blur). Odata.nicknameusado no card de preview só é atualizado depois que o valor passa pela validação, nosave(). Isso evita que o preview mude com um valor ainda inválido enquanto o usuário digita.Validação do apelido
O campo valida o formato no
save(), antes de persistir. Regras: máximo de 100 caracteres, apenas letras, números, espaços, hífens e apóstrofos, e pelo menos 2 letras consecutivas (bloqueia entradas tipo"a a a"ou só símbolos). Quando o valor é inválido, o campo fica destacado em vermelho, uma mensagem de erro aparece, e a página rola automaticamente até o campo.Persistência do apelido
Antes,
nullrepresentava dois casos ao mesmo tempo: campo não alterado e apelido removido. Como os dois caíam na mesma verificação, limpar o apelido nunca era persistido no banco.Agora:
null= campo não foi alterado''= remove o apelido salvo