Skip to content

fix(profile): prioriza nickname na exibição do card com fallback e validação#401

Open
GustavoSimao wants to merge 3 commits into
4.xfrom
fix/profile-nickname-display
Open

fix(profile): prioriza nickname na exibição do card com fallback e validação#401
GustavoSimao wants to merge 3 commits into
4.xfrom
fix/profile-nickname-display

Conversation

@GustavoSimao

@GustavoSimao GustavoSimao commented Jul 8, 2026

Copy link
Copy Markdown
Member

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:

  1. Apelido, quando preenchido
  2. Nome da conta conectada (Discord, GitHub, etc.)
  3. Nome de usuário

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). O data.nickname usado no card de preview só é atualizado depois que o valor passa pela validação, no save(). 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, null representava 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

…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.
@GustavoSimao GustavoSimao requested a review from a team July 8, 2026 21:28
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Nickname persistence now converts empty strings to null and applies new nickname validation rules. ProfilePage uses a separate nicknameInput state, handles ValidationException from UpsertProfile, and dispatches scroll-to-nickname on nickname validation failure. The profile media header input now binds to nicknameInput; the preview card fallback order now prefers nickname, then user name, then username.

Suggested reviewers: danielhe4rt, gvieira18, danielmendss, Clintonrocha98, YuriSouzaDev

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed O título descreve bem a mudança principal: prioridade do nickname no card com fallback e validação.
Description check ✅ Passed A descrição está alinhada às mudanças do PR e cobre exibição, validação e persistência do nickname.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
app-modules/profile/src/Actions/UpsertProfile.php (1)

78-85: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use __() 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

📥 Commits

Reviewing files that changed from the base of the PR and between b6393d5 and 1ecde74.

📒 Files selected for processing (4)
  • app-modules/panel-app/resources/views/components/profile-media-header.blade.php
  • app-modules/panel-app/resources/views/components/profile-preview-card.blade.php
  • app-modules/panel-app/src/Pages/ProfilePage.php
  • app-modules/profile/src/Actions/UpsertProfile.php

Comment on lines +407 to +416
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
app-modules/profile/src/Actions/UpsertProfile.php (1)

82-89: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Hardcoded 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 \s which matches any whitespace (newlines, tabs, carriage returns), but the error message on line 86 says "espaços" (spaces). Consider replacing \s with 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 win

Missing 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ecde74 and 5aee85a.

📒 Files selected for processing (3)
  • app-modules/panel-app/src/Pages/ProfilePage.php
  • app-modules/panel-app/tests/Feature/ProfilePageTest.php
  • app-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

@GustavoSimao GustavoSimao requested a review from danielhe4rt July 9, 2026 13:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants