Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gerenciamento de usuário criar campos adicionais tabela #31

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

mgescobar
Copy link
Collaborator

@mgescobar mgescobar commented Jan 14, 2025

Removido o campo "linkedin" já existente conforme relato do @lthurler

Summary by CodeRabbit

  • Novos Recursos

    • Adicionados novos campos de localização e identificadores de redes sociais para perfis de usuário.
  • Alterações de Banco de Dados

    • Incluídos campos para cidade e estado.
    • Adicionado campo único para identificador do Discord.
    • Removido campo do LinkedIn.

Copy link

coderabbitai bot commented Jan 14, 2025

Walkthrough

As alterações envolvem a adição de novos campos de localização e identificação social para o modelo de usuário. A migração do banco de dados foi atualizada para incluir colunas para city (cidade), state (estado) e discord, removendo simultaneamente o campo linkedin. O modelo User foi modificado para permitir a atribuição em massa desses novos atributos, expandindo as informações que podem ser capturadas sobre um usuário.

Changes

Arquivo Resumo das Alterações
app/Models/User.php Adicionados city, state e discord à propriedade $fillable
database/migrations/2024_01_25_210912_create_users_table.php Removida coluna linkedin, adicionadas colunas city, state e discord
database/migrations/2024_11_29_185241_add_new_fields.php Nova migração para adicionar campos city, state, linkedin e discord

Poem

🐰 Um coelho salta de alegria,
Novos campos na base de dados, que magia!
Cidade, estado, Discord à vista,
Perfil de usuário ganha nova pista!
Migração suave, sem nenhum penar,
Dados fluem, prontos para brilhar! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e874fc1 and c01fc2b.

📒 Files selected for processing (3)
  • app/Models/User.php (1 hunks)
  • database/migrations/2024_01_25_210912_create_users_table.php (1 hunks)
  • database/migrations/2024_11_29_185241_add_new_fields.php (1 hunks)
🔇 Additional comments (1)
database/migrations/2024_01_25_210912_create_users_table.php (1)

Line range hint 12-29: Verificar impacto da condição isLocal()

A criação da tabela users está envolta em uma condição if (app()->isLocal()). Isso significa que a tabela só será criada em ambiente local.

Confirme se este é o comportamento desejado, pois isso pode causar problemas em outros ambientes.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@mgescobar mgescobar changed the base branch from master to develop January 14, 2025 21:48
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 3

🛑 Comments failed to post (3)
database/migrations/2024_11_29_185241_add_new_fields.php (1)

14-19: ⚠️ Potential issue

Migração duplicada e conflitante detectada

Esta migração apresenta problemas críticos:

  1. Os campos city, state e discord já estão definidos em create_users_table.php
  2. O campo linkedin está sendo adicionado aqui, mas deveria ser removido conforme objetivo do PR
  3. Ter duas migrações definindo as mesmas colunas causará erro

Recomendação: Esta migração deve ser removida pois os campos já existem em create_users_table.php. Se necessário remover o LinkedIn, crie uma migração específica para isso.

app/Models/User.php (1)

27-30: ⚠️ Potential issue

Remover campo 'linkedin' do array $fillable

O campo 'linkedin' ainda está presente no array $fillable mas deveria ser removido conforme objetivo do PR.

    protected $fillable = [
        'uuid',
        'name',
        'email',
        'password',
        'city',
        'state',
-       'linkedin',
        'discord',
        'permission',
    ];

Committable suggestion skipped: line range outside the PR's diff.

database/migrations/2024_01_25_210912_create_users_table.php (1)

20-22: 💡 Codebase verification

Confirmada a necessidade de validações para os novos campos

Após análise do código, confirmo que não existem validações implementadas para os campos city, state e discord. Os campos estão corretamente definidos na migration e configurados como fillable no modelo User, porém as validações sugeridas ainda não foram implementadas:

  1. Validação de estados válidos para o campo state
  2. Validação de formato para o campo discord (username#0000)
🔗 Analysis chain

Considerar adição de validações para os novos campos

A implementação dos novos campos está correta, porém sugiro algumas melhorias:

  1. Para o campo state, considerar usar um enum ou check constraint para garantir apenas estados válidos
  2. Para o campo discord, considerar adicionar uma validação de formato (ex: username#0000)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verificar se já existem validações implementadas
rg -l "discord.*validate|state.*validate" app/

Length of output: 48


Script:

#!/bin/bash
# Procurar por arquivos de validação e regras relacionadas aos novos campos
echo "=== Procurando classes Request ==="
fd -e php request app/

echo -e "\n=== Procurando modelo User ==="
fd -e php "User.php" app/Models/

echo -e "\n=== Procurando regras nos arquivos encontrados ==="
rg -l "city|state|discord" app/

Length of output: 404


Script:

#!/bin/bash
echo "=== Conteúdo do Model User ==="
cat app/Models/User.php

Length of output: 1248

@lthurler lthurler requested a review from michelsouza February 1, 2025 18:43
Copy link
Contributor

@michelsouza michelsouza left a comment

Choose a reason for hiding this comment

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

Apos ser criado os novos campos atraves da nova migration (2024_11_29_185241_add_new_fields.php) eh necessario remover os mesmos da migration de usuario.

Ver documentacao do laraval sobre migration, toda e qualquer alteracao feita em banco de dados, devem ser feitas a partir da criacao de novos arquivos de migrations e nao alterando as ja existentes, visto que pode ocorrer conflitos tentar rodar essas operacoes na base de dados, como ocorre no momento.

image

Copy link
Contributor

@michelsouza michelsouza left a comment

Choose a reason for hiding this comment

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

Todos os campos que estao sendo duplicados em users e na migration 2024_11_29_185241_add_new_fields dao erro, sendo necessario a remocao de todos, foi removido apenas linkedin. Para fins de teste, apos alteracoes, caso nao seja possivel reconstruir o banco de dados com o php artisan migrate:fresh, sugiro criar um novo banco de dados e fazer o apontamento para teste, APENAS PARA TESTE rodando o comando php artisan migrate

@rigonlucas
Copy link
Collaborator

@mgescobar dá uma olhada nessa questão para nós?

@@ -19,7 +19,6 @@ public function up(): void
$table->string('password');
$table->string('city', 60)->nullable();
$table->string('state', 20)->nullable();
$table->string('linkedin', 101)->nullable()->unique();
Copy link

@Diegiwg Diegiwg Feb 27, 2025

Choose a reason for hiding this comment

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

@mgescobar normalmente, não se mexe em migrations antigas.

O ideal é criar uma nova migration, que será responsavel por modificar a tabela, removendo o campo no UP e o adicionando novamente no DOWN.

Sugestão

// php artisan make:migration remove_linkedin_column_from_users_table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table
                ->dropColumn('linkedin');
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table
                ->string('linkedin')
                ->nullable()
                ->unique()
                ->after('password');
        });
    }
};

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.

7 participants