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 4 commits into
Conversation
|
Warning Review limit reached
Next review available in: 17 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Repository YAML (base), Central YAML (inherited) Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughNickname persistence now converts empty strings to null and applies expanded 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
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
…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.
…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.
Domain validation in UpsertProfile threw a ValidationException whose keys (about, birthdate, expected_salary_max, nickname...) did not match the form statePath (data.*), so Livewire swallowed them into the error bag and nothing rendered — no inline error, no toast. save() now wraps the mutation in a single try/catch that routes each error: nickname goes inline on its dedicated input (with scroll-to-nickname), fields that exist in the Filament schema get an inline error, and keys with no rendered input (e.g. birthdate) fall back to a danger toast. Also reconciles the broken merge (dangling catch, duplicated try) from the branch switch. Adds notifications.validation_error (en/pt_BR) and covers the inline, dedicated nickname input, and toast-fallback paths with tests.
fcde66e to
4f53087
Compare
BrunaDomingues
left a comment
There was a problem hiding this comment.
Só resolver os conflitos e dale!
Leave the nickname input in the media header so this change stays compatible with the nickname validation flow in he4rt#401. Only birthdate moves to the DatePicker. Co-authored-by: Cursor <cursoragent@cursor.com>
Keep the nickname markup aligned with 4.x and cover birthdate in a dedicated test so merges with he4rt#401 stay cleaner. Co-authored-by: Cursor <cursoragent@cursor.com>
…isplay # Conflicts: # app-modules/panel-app/src/Pages/ProfilePage.php
236076e
|
Gustavo, muito bom esse PR. Você não só resolveu o que a #398 tentou, como foi atrás do fluxo inteiro e achou os outros dois problemas de quebra (a validação e o apelido que não dava pra remover). E o Fui rodar aqui pra conferir e achei uma coisa que acho que vale ver antes de mergear. A troca pro A limpeza em si ficou ótima, sumiram umas 90 linhas de 'expected_salary_max' => ['nullable', 'numeric', 'min:0', 'gte:expected_salary_min'],Agora o Testei pela tela nos dois lados pra ter certeza que não era coisa que já existia: livewire(ProfilePage::class)
->fillForm([
'available_for_proposals' => true,
'expected_salary_max' => 5000,
])
->call('save');No 4.x o valor persiste, aqui fica Uma saída seria condicionar a regra e manter o resto como está: 'expected_salary_max' => ['nullable', 'numeric', 'min:0', Rule::when(
$dto->expectedSalaryMin !== null,
['gte:expected_salary_min'],
)],A descrição do PR fala de uma validação que eu não achei no código O corpo menciona que o apelido valida "apenas letras, números, espaços, hífens e apóstrofos, e pelo menos 2 letras consecutivas". Procurei nos 8 arquivos e só achei E se for pra implementar de fato, só um cuidado com a lista de caracteres permitidos: numa comunidade brasileira "José" e "Ana Luísa" precisam passar, e um Uma observação sem urgência Conferi o (Coisa boba: o |
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