diff --git a/Caddyfile b/Caddyfile index 0a3b0eca..f4394d72 100644 --- a/Caddyfile +++ b/Caddyfile @@ -5,6 +5,10 @@ reverse_proxy backend:8000 } + handle /media/* { + reverse_proxy backend:8000 + } + handle { reverse_proxy frontend:3000 } diff --git a/README.md b/README.md index 5cdeefc0..9e6a2e20 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,12 @@ Development uses its own Compose project and database volume; it requires no `.env` file. Existing volumes from the old default development stack are not migrated automatically. +Seed the local Semana event and an input challenge: + +```bash +docker compose -f docker-compose.dev.yml exec backend python -m scripts.seed_dev +``` + ```bash docker compose -f docker-compose.dev.yml exec backend ruff check . docker compose -f docker-compose.dev.yml exec backend ruff format --check . @@ -35,3 +41,9 @@ backups, and the firewall before running: ```bash docker compose up -d --build ``` + +To fill up the initial semana data (after confirming it right): + +```bash +docker compose exec backend python -m scripts.seed_semana_data +``` \ No newline at end of file diff --git a/backend/.env.example b/backend/.env.example index 1ad2f4ca..669592f4 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -5,4 +5,14 @@ SECRET_KEY=change_this_to_a_secure_random_key_in_production # JWT access/id tokens fields ISSUER=http://localhost:8000 -AUDIENCE=symcomp-frontend \ No newline at end of file +AUDIENCE=symcomp-frontend + +#oAuth +GOOGLE_CLIENT_ID= +GOOGLE_CLIENT_SECRET= + +GITHUB_CLIENT_ID= +GITHUB_CLIENT_SECRET= + +OAUTH_REDIRECT_BASE=http://localhost:8000 +FRONTEND_BASE_URL=http://localhost:3000 \ No newline at end of file diff --git a/backend/Dockerfile b/backend/Dockerfile index 0404882b..50abd007 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -54,4 +54,4 @@ RUN chown -R app:app /app USER app -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] \ No newline at end of file +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "3"] diff --git a/backend/README.md b/backend/README.md index 2cb4ed52..b5a3af27 100644 --- a/backend/README.md +++ b/backend/README.md @@ -63,3 +63,13 @@ $ uv run alembic upgrade head 5. Commit your changes. Commit together: SQLAlchemy model changes, migration files (under `alembic/versions/`) and tests for new behaviour. In new environments, `alembic upgrade head` builds the full schema from zero. + +### Login social (Google e GitHub) + +Defina no ambiente do backend `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, +`GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `OAUTH_REDIRECT_BASE` (origem pública +que encaminha `/api` ao backend) e `FRONTEND_BASE_URL`. Cadastre nos consoles OAuth +as callbacks `/api/v1/auth/oauth/google/callback` e +`/api/v1/auth/oauth/github/callback` sob essa origem. Execute `alembic upgrade head` +para adicionar `users.oauth_provider`. O login exige e-mail verificado; e-mails já +associados a contas com senha não são vinculados automaticamente. diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 8ae1338f..c6342024 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -15,7 +15,8 @@ from app.auth import models as auth_models # noqa: F401 noqa from app.users import models as user_models # noqa: F401 noqa from app.challenges import models as challenges_models # noqa: F401 noqa -from app.users.username import models as usernames_user_models # noqa: F401 noqa +from app.semana import models as semana_models # noqa: F401 noqa +from app.atividade import models as atividade_models # noqa: F401 noqa # this is the Alembic Config object, which provides # access to the values within the .ini file in use. diff --git a/backend/alembic/versions/4f21ac9d7b30_add_challenge_description.py b/backend/alembic/versions/4f21ac9d7b30_add_challenge_description.py new file mode 100644 index 00000000..93718cde --- /dev/null +++ b/backend/alembic/versions/4f21ac9d7b30_add_challenge_description.py @@ -0,0 +1,28 @@ +"""add description to challenges + +Revision ID: 4f21ac9d7b30 +Revises: 7e2b0a1c4d5f +""" + +from collections.abc import Sequence + +import sqlalchemy as sa + +from alembic import op + +revision: str = "4f21ac9d7b30" +down_revision: str | Sequence[str] | None = "7e2b0a1c4d5f" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.add_column( + "challenges", + sa.Column("description", sa.Text(), server_default="", nullable=False), + ) + op.alter_column("challenges", "description", server_default=None) + + +def downgrade() -> None: + op.drop_column("challenges", "description") diff --git a/backend/alembic/versions/508a25128b6c_initial_schema.py b/backend/alembic/versions/508a25128b6c_initial_schema.py new file mode 100644 index 00000000..b9b8de64 --- /dev/null +++ b/backend/alembic/versions/508a25128b6c_initial_schema.py @@ -0,0 +1,461 @@ +"""initial schema + +Revision ID: 508a25128b6c +Revises: +Create Date: 2026-09-30 08:10:30.465341 + +""" + +from collections.abc import Sequence + +import sqlalchemy as sa + +from alembic import op + +# revision identifiers, used by Alembic. +revision: str = "508a25128b6c" +down_revision: str | Sequence[str] | None = None +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + """Upgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + "semana_event", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("nome", sa.String(length=255), nullable=False), + sa.Column("ano", sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint("id", name=op.f("semana_event_pkey")), + ) + op.create_table( + "users", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("email", sa.String(length=255), nullable=False), + sa.Column("name", sa.String(length=255), nullable=False), + sa.Column("password_hash", sa.String(length=255), nullable=True), + sa.Column("is_admin", sa.Boolean(), server_default="false", nullable=False), + sa.Column("is_verified", sa.Boolean(), server_default="false", nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint("id", name=op.f("users_pkey")), + ) + op.create_index(op.f("users_deleted_at_idx"), "users", ["deleted_at"], unique=False) + op.create_index(op.f("users_email_idx"), "users", ["email"], unique=True) + op.create_table( + "atividades", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("semana_id", sa.Integer(), nullable=False), + sa.Column( + "tipo", + sa.Enum( + "PALESTRA", + "WORKSHOP", + "ENCERRAMENTO", + "CONVERSA", + "COFFEE_BREAK", + name="tipoatividade", + ), + nullable=False, + ), + sa.Column("titulo", sa.String(length=255), nullable=False), + sa.Column( + "status", + sa.Enum("PROVISORIA", "CONFIRMADA", name="statusatividade"), + nullable=False, + ), + sa.Column("comeca_as", sa.DateTime(timezone=True), nullable=False), + sa.Column("termina_as", sa.DateTime(timezone=True), nullable=False), + sa.Column("codigo", sa.String(length=4), nullable=False), + sa.Column("pontos", sa.Integer(), nullable=False), + sa.Column("horas", sa.Integer(), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint( + ["semana_id"], + ["semana_event.id"], + name=op.f("atividades_semana_id_fkey"), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("atividades_pkey")), + sa.UniqueConstraint("semana_id", "codigo", name="uq_atividade_semana_codigo"), + ) + op.create_index( + op.f("atividades_deleted_at_idx"), "atividades", ["deleted_at"], unique=False + ) + op.create_index( + op.f("atividades_semana_id_idx"), "atividades", ["semana_id"], unique=False + ) + op.create_index( + "ix_atividade_semana_schedule", + "atividades", + ["semana_id", "comeca_as"], + unique=False, + ) + op.create_table( + "challenges", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("title", sa.String(length=255), nullable=False), + sa.Column("prompt", sa.String(length=5000), nullable=False), + sa.Column( + "scoring_type", + sa.Enum( + "QUIZ", + "INPUT", + "MANUAL", + name="challengescoringtype", + native_enum=False, + length=20, + ), + nullable=False, + ), + sa.Column("image_path", sa.String(length=512), nullable=True), + sa.Column("resource_urls", sa.JSON(), nullable=False), + sa.Column("points_value", sa.Integer(), nullable=False), + sa.Column("input_answer", sa.String(length=255), nullable=True), + sa.Column("semana_id", sa.Integer(), nullable=True), + sa.Column( + "finishes_at", + sa.DateTime(timezone=True), + server_default=sa.text("now() + interval '1 day'"), + nullable=False, + ), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint( + ["semana_id"], ["semana_event.id"], name=op.f("challenges_semana_id_fkey") + ), + sa.PrimaryKeyConstraint("id", name=op.f("challenges_pkey")), + ) + op.create_index( + op.f("challenges_deleted_at_idx"), "challenges", ["deleted_at"], unique=False + ) + op.create_table( + "refresh_tokens", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("user_id", sa.Uuid(), nullable=False), + sa.Column("token_hash", sa.String(length=64), nullable=False), + sa.Column("scopes", sa.String(length=255), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("revoked_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint( + ["user_id"], ["users.id"], name=op.f("refresh_tokens_user_id_fkey") + ), + sa.PrimaryKeyConstraint("id", name=op.f("refresh_tokens_pkey")), + sa.UniqueConstraint("token_hash", name=op.f("refresh_tokens_token_hash_key")), + ) + op.create_table( + "semana_participants", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("semana_id", sa.Integer(), nullable=False), + sa.Column("user_id", sa.Uuid(), nullable=False), + sa.Column("nickname", sa.String(length=255), nullable=True), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint( + ["semana_id"], + ["semana_event.id"], + name=op.f("semana_participants_semana_id_fkey"), + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["user_id"], + ["users.id"], + name=op.f("semana_participants_user_id_fkey"), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("semana_participants_pkey")), + sa.UniqueConstraint( + "semana_id", "nickname", name="uq_semana_participant_nickname" + ), + sa.UniqueConstraint( + "semana_id", "user_id", name="uq_semana_participant_event_user" + ), + ) + op.create_index( + op.f("semana_participants_deleted_at_idx"), + "semana_participants", + ["deleted_at"], + unique=False, + ) + op.create_table( + "challenge_participants", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("user_id", sa.Uuid(), nullable=False), + sa.Column("challenge_id", sa.Uuid(), nullable=False), + sa.Column("semana_participant_id", sa.Uuid(), nullable=True), + sa.Column("score", sa.Integer(), nullable=False), + sa.Column("submitted_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("submission", sa.String(length=255), nullable=True), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint( + ["challenge_id"], + ["challenges.id"], + name=op.f("challenge_participants_challenge_id_fkey"), + ), + sa.ForeignKeyConstraint( + ["semana_participant_id"], + ["semana_participants.id"], + name=op.f("challenge_participants_semana_participant_id_fkey"), + ), + sa.ForeignKeyConstraint( + ["user_id"], + ["users.id"], + name=op.f("challenge_participants_user_id_fkey"), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("challenge_participants_pkey")), + sa.UniqueConstraint( + "user_id", "challenge_id", name="uq_participant_user_challenge" + ), + ) + op.create_index( + op.f("challenge_participants_deleted_at_idx"), + "challenge_participants", + ["deleted_at"], + unique=False, + ) + op.create_table( + "point_events", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("semana_participant_id", sa.Uuid(), nullable=False), + sa.Column("amount", sa.Integer(), nullable=False), + sa.Column("source_type", sa.String(length=32), nullable=False), + sa.Column("source_id", sa.Uuid(), nullable=True), + sa.Column("reason", sa.String(length=255), nullable=True), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint( + ["semana_participant_id"], + ["semana_participants.id"], + name=op.f("point_events_semana_participant_id_fkey"), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("point_events_pkey")), + sa.UniqueConstraint( + "semana_participant_id", + "source_type", + "source_id", + name="uq_point_event_source", + ), + ) + op.create_index( + op.f("point_events_deleted_at_idx"), + "point_events", + ["deleted_at"], + unique=False, + ) + op.create_table( + "presencas", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("atividade_id", sa.Uuid(), nullable=False), + sa.Column("user_id", sa.Uuid(), nullable=True), + sa.Column("nome", sa.String(length=255), nullable=False), + sa.Column("email", sa.String(length=255), nullable=False), + sa.Column("horas", sa.Integer(), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint( + ["atividade_id"], + ["atividades.id"], + name=op.f("presencas_atividade_id_fkey"), + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["user_id"], + ["users.id"], + name=op.f("presencas_user_id_fkey"), + ondelete="SET NULL", + ), + sa.PrimaryKeyConstraint("id", name=op.f("presencas_pkey")), + sa.UniqueConstraint( + "atividade_id", "email", name="uq_presenca_atividade_email" + ), + sa.UniqueConstraint( + "atividade_id", "user_id", name="uq_presenca_atividade_user" + ), + ) + op.create_index( + op.f("presencas_atividade_id_idx"), "presencas", ["atividade_id"], unique=False + ) + op.create_index( + op.f("presencas_deleted_at_idx"), "presencas", ["deleted_at"], unique=False + ) + op.create_index( + op.f("presencas_user_id_idx"), "presencas", ["user_id"], unique=False + ) + op.create_table( + "questions", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("prompt", sa.String(length=5000), nullable=False), + sa.Column("answer", sa.String(length=255), nullable=False), + sa.Column("points_value", sa.Integer(), nullable=False), + sa.Column("challenge_id", sa.Uuid(), nullable=False), + sa.ForeignKeyConstraint( + ["challenge_id"], + ["challenges.id"], + name=op.f("questions_challenge_id_fkey"), + ), + sa.PrimaryKeyConstraint("id", name=op.f("questions_pkey")), + ) + op.create_table( + "answers", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("participant_id", sa.Uuid(), nullable=False), + sa.Column("question_id", sa.Uuid(), nullable=False), + sa.Column("content", sa.String(length=255), nullable=False), + sa.Column("is_correct", sa.Boolean(), nullable=False), + sa.Column( + "created_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column( + "updated_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint( + ["participant_id"], + ["challenge_participants.id"], + name=op.f("answers_participant_id_fkey"), + ondelete="CASCADE", + ), + sa.ForeignKeyConstraint( + ["question_id"], + ["questions.id"], + name=op.f("answers_question_id_fkey"), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("answers_pkey")), + sa.UniqueConstraint( + "participant_id", "question_id", name="uq_participant_question" + ), + ) + op.create_index( + op.f("answers_deleted_at_idx"), "answers", ["deleted_at"], unique=False + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + """Downgrade schema.""" + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f("answers_deleted_at_idx"), table_name="answers") + op.drop_table("answers") + op.drop_table("questions") + op.drop_index(op.f("presencas_user_id_idx"), table_name="presencas") + op.drop_index(op.f("presencas_deleted_at_idx"), table_name="presencas") + op.drop_index(op.f("presencas_atividade_id_idx"), table_name="presencas") + op.drop_table("presencas") + op.drop_index(op.f("point_events_deleted_at_idx"), table_name="point_events") + op.drop_table("point_events") + op.drop_index( + op.f("challenge_participants_deleted_at_idx"), + table_name="challenge_participants", + ) + op.drop_table("challenge_participants") + op.drop_index( + op.f("semana_participants_deleted_at_idx"), table_name="semana_participants" + ) + op.drop_table("semana_participants") + op.drop_table("refresh_tokens") + op.drop_index(op.f("challenges_deleted_at_idx"), table_name="challenges") + op.drop_table("challenges") + op.drop_index("ix_atividade_semana_schedule", table_name="atividades") + op.drop_index(op.f("atividades_semana_id_idx"), table_name="atividades") + op.drop_index(op.f("atividades_deleted_at_idx"), table_name="atividades") + op.drop_table("atividades") + op.drop_index(op.f("users_email_idx"), table_name="users") + op.drop_index(op.f("users_deleted_at_idx"), table_name="users") + op.drop_table("users") + op.drop_table("semana_event") + # ### end Alembic commands ### diff --git a/backend/alembic/versions/75537158e76e_create_refresh_tokens_table.py b/backend/alembic/versions/75537158e76e_create_refresh_tokens_table.py deleted file mode 100644 index b591f3bf..00000000 --- a/backend/alembic/versions/75537158e76e_create_refresh_tokens_table.py +++ /dev/null @@ -1,48 +0,0 @@ -"""create_refresh_tokens_table - -Revision ID: 75537158e76e -Revises: d01c0010d74b -Create Date: 2026-09-10 02:47:45.422092 - -""" - -from collections.abc import Sequence - -import sqlalchemy as sa - -from alembic import op - -# revision identifiers, used by Alembic. -revision: str = "75537158e76e" -down_revision: str | Sequence[str] | None = "d01c0010d74b" -branch_labels: str | Sequence[str] | None = None -depends_on: str | Sequence[str] | None = None - - -def upgrade() -> None: - """Upgrade schema.""" - # ### commands auto generated by Alembic - please adjust! ### - op.create_table( - "refresh_tokens", - sa.Column("id", sa.Uuid(), nullable=False), - sa.Column("user_id", sa.Uuid(), nullable=False), - sa.Column("token_hash", sa.String(length=64), nullable=False), - sa.Column( - "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False - ), - sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False), - sa.Column("revoked_at", sa.DateTime(timezone=True), nullable=True), - sa.ForeignKeyConstraint( - ["user_id"], ["users.id"], name=op.f("refresh_tokens_user_id_fkey") - ), - sa.PrimaryKeyConstraint("id", name=op.f("refresh_tokens_pkey")), - sa.UniqueConstraint("token_hash", name=op.f("refresh_tokens_token_hash_key")), - ) - # ### end Alembic commands ### - - -def downgrade() -> None: - """Downgrade schema.""" - # ### commands auto generated by Alembic - please adjust! ### - op.drop_table("refresh_tokens") - # ### end Alembic commands ### diff --git a/backend/alembic/versions/7b14a96d2c83_add_challenge_finishes_at.py b/backend/alembic/versions/7b14a96d2c83_add_challenge_finishes_at.py deleted file mode 100644 index 68939ae3..00000000 --- a/backend/alembic/versions/7b14a96d2c83_add_challenge_finishes_at.py +++ /dev/null @@ -1,35 +0,0 @@ -"""add challenge finish deadline - -Revision ID: 7b14a96d2c83 -Revises: c8389c55b075 -Create Date: 2026-09-27 00:00:00.000000 - -""" - -from collections.abc import Sequence - -import sqlalchemy as sa - -from alembic import op - -# revision identifiers, used by Alembic. -revision: str = "7b14a96d2c83" -down_revision: str | Sequence[str] | None = "c8389c55b075" -branch_labels: str | Sequence[str] | None = None -depends_on: str | Sequence[str] | None = None - - -def upgrade() -> None: - op.add_column( - "challenges", - sa.Column( - "finishes_at", - sa.DateTime(timezone=True), - server_default=sa.text("now() + interval '1 day'"), - nullable=False, - ), - ) - - -def downgrade() -> None: - op.drop_column("challenges", "finishes_at") diff --git a/backend/alembic/versions/7e2b0a1c4d5f_add_challenge_inputs.py b/backend/alembic/versions/7e2b0a1c4d5f_add_challenge_inputs.py new file mode 100644 index 00000000..1863e2af --- /dev/null +++ b/backend/alembic/versions/7e2b0a1c4d5f_add_challenge_inputs.py @@ -0,0 +1,113 @@ +"""move input challenge data into its own table + +Revision ID: 7e2b0a1c4d5f +Revises: 9f1d7a2c4b6e +""" + +from collections.abc import Sequence + +import sqlalchemy as sa + +from alembic import op + +revision: str = "7e2b0a1c4d5f" +down_revision: str | Sequence[str] | None = "9f1d7a2c4b6e" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.create_table( + "inputs", + sa.Column("id", sa.Uuid(), nullable=False), + sa.Column("prompt", sa.String(length=5000), nullable=False), + sa.Column("input_answer", sa.String(length=255), nullable=True), + sa.Column("challenge_id", sa.Uuid(), nullable=False), + sa.ForeignKeyConstraint( + ["challenge_id"], + ["challenges.id"], + name=op.f("inputs_challenge_id_fkey"), + ondelete="CASCADE", + ), + sa.PrimaryKeyConstraint("id", name=op.f("inputs_pkey")), + sa.UniqueConstraint("challenge_id", name=op.f("inputs_challenge_id_key")), + ) + op.execute( + sa.text( + """ + UPDATE challenges + SET points_value = ( + SELECT COALESCE(SUM(questions.points_value), 0) + FROM questions + WHERE questions.challenge_id = challenges.id + ) + WHERE scoring_type = 'QUIZ' + """ + ) + ) + op.execute( + sa.text( + """ + INSERT INTO inputs (id, prompt, input_answer, challenge_id) + SELECT gen_random_uuid(), prompt, input_answer, id + FROM challenges + WHERE scoring_type = 'INPUT' + """ + ) + ) + op.drop_column("questions", "points_value") + op.drop_column("challenges", "input_answer") + op.drop_column("challenges", "prompt") + + +def downgrade() -> None: + op.add_column( + "challenges", + sa.Column("prompt", sa.String(length=5000), server_default="", nullable=False), + ) + op.add_column( + "challenges", sa.Column("input_answer", sa.String(length=255), nullable=True) + ) + op.execute( + sa.text( + """ + UPDATE challenges + SET prompt = inputs.prompt, input_answer = inputs.input_answer + FROM inputs + WHERE challenges.id = inputs.challenge_id + """ + ) + ) + op.alter_column("challenges", "prompt", server_default=None) + op.drop_table("inputs") + op.add_column( + "questions", + sa.Column("points_value", sa.Integer(), server_default="0", nullable=False), + ) + op.execute( + sa.text( + """ + WITH ranked_questions AS ( + SELECT questions.id, + challenges.points_value / COUNT(*) OVER ( + PARTITION BY questions.challenge_id + ) AS base_points, + challenges.points_value % COUNT(*) OVER ( + PARTITION BY questions.challenge_id + ) AS remainder, + ROW_NUMBER() OVER ( + PARTITION BY questions.challenge_id ORDER BY questions.id + ) AS question_number + FROM questions + JOIN challenges ON challenges.id = questions.challenge_id + ) + UPDATE questions + SET points_value = ranked_questions.base_points + + CASE WHEN ranked_questions.question_number <= ranked_questions.remainder + THEN 1 ELSE 0 END + FROM ranked_questions + WHERE questions.id = ranked_questions.id + """ + ) + ) + op.alter_column("questions", "points_value", server_default=None) diff --git a/backend/alembic/versions/91cc57573789_align_timestamps_to_timezone_awareness.py b/backend/alembic/versions/91cc57573789_align_timestamps_to_timezone_awareness.py deleted file mode 100644 index a4d6878c..00000000 --- a/backend/alembic/versions/91cc57573789_align_timestamps_to_timezone_awareness.py +++ /dev/null @@ -1,102 +0,0 @@ -"""align_timestamps_to_timezone_awareness - -Revision ID: 91cc57573789 -Revises: 75537158e76e -Create Date: 2026-09-10 04:40:10.591315 - -""" - -from collections.abc import Sequence - -import sqlalchemy as sa -from sqlalchemy.dialects import postgresql - -from alembic import op - -# revision identifiers, used by Alembic. -revision: str = "91cc57573789" -down_revision: str | Sequence[str] | None = "75537158e76e" -branch_labels: str | Sequence[str] | None = None -depends_on: str | Sequence[str] | None = None - - -def upgrade() -> None: - """Upgrade schema.""" - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column( - "refresh_tokens", - "created_at", - existing_type=postgresql.TIMESTAMP(), - type_=sa.DateTime(timezone=True), - existing_nullable=False, - existing_server_default=sa.text("now()"), - postgresql_using="created_at AT TIME ZONE 'UTC'", - ) - op.alter_column( - "users", - "created_at", - existing_type=postgresql.TIMESTAMP(), - type_=sa.DateTime(timezone=True), - existing_nullable=False, - existing_server_default=sa.text("now()"), - postgresql_using="created_at AT TIME ZONE 'UTC'", - ) - op.alter_column( - "users", - "updated_at", - existing_type=postgresql.TIMESTAMP(), - type_=sa.DateTime(timezone=True), - existing_nullable=False, - existing_server_default=sa.text("now()"), - postgresql_using="created_at AT TIME ZONE 'UTC'", - ) - op.alter_column( - "users", - "deleted_at", - existing_type=postgresql.TIMESTAMP(), - type_=sa.DateTime(timezone=True), - existing_nullable=True, - postgresql_using="created_at AT TIME ZONE 'UTC'", - ) - # ### end Alembic commands ### - - -def downgrade() -> None: - """Downgrade schema.""" - # ### commands auto generated by Alembic - please adjust! ### - op.alter_column( - "users", - "deleted_at", - existing_type=sa.DateTime(timezone=True), - type_=postgresql.TIMESTAMP(), - existing_nullable=True, - postgresql_using="created_at AT TIME ZONE 'UTC'", - ) - op.alter_column( - "users", - "updated_at", - existing_type=sa.DateTime(timezone=True), - type_=postgresql.TIMESTAMP(), - existing_nullable=False, - existing_server_default=sa.text("now()"), - postgresql_using="created_at AT TIME ZONE 'UTC'", - ) - op.alter_column( - "users", - "created_at", - existing_type=sa.DateTime(timezone=True), - type_=postgresql.TIMESTAMP(), - existing_nullable=False, - existing_server_default=sa.text("now()"), - postgresql_using="created_at AT TIME ZONE 'UTC'", - ) - op.alter_column( - "refresh_tokens", - "created_at", - existing_type=sa.DateTime(timezone=True), - type_=postgresql.TIMESTAMP(), - existing_nullable=False, - existing_server_default=sa.text("now()"), - postgresql_using="created_at AT TIME ZONE 'UTC'", - ) - # ### end Alembic commands ### diff --git a/backend/alembic/versions/9f1d7a2c4b6e_add_activity_schedule_details.py b/backend/alembic/versions/9f1d7a2c4b6e_add_activity_schedule_details.py new file mode 100644 index 00000000..98c90f15 --- /dev/null +++ b/backend/alembic/versions/9f1d7a2c4b6e_add_activity_schedule_details.py @@ -0,0 +1,36 @@ +"""add activity schedule details + +Revision ID: 9f1d7a2c4b6e +Revises: 508a25128b6c +""" + +from collections.abc import Sequence + +import sqlalchemy as sa + +from alembic import op + +revision: str = "9f1d7a2c4b6e" +down_revision: str | Sequence[str] | None = "508a25128b6c" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.add_column("atividades", sa.Column("descricao", sa.String(length=5000))) + op.add_column("atividades", sa.Column("local", sa.String(length=255))) + op.add_column( + "atividades", + sa.Column( + "palestrantes", sa.JSON(), nullable=False, server_default=sa.text("'[]'") + ), + ) + op.add_column("atividades", sa.Column("link_live", sa.String(length=500))) + op.alter_column("atividades", "palestrantes", server_default=None) + + +def downgrade() -> None: + op.drop_column("atividades", "link_live") + op.drop_column("atividades", "palestrantes") + op.drop_column("atividades", "local") + op.drop_column("atividades", "descricao") diff --git a/backend/alembic/versions/b81f3c2a6d40_add_challenge_starts_at.py b/backend/alembic/versions/b81f3c2a6d40_add_challenge_starts_at.py new file mode 100644 index 00000000..06c18cd5 --- /dev/null +++ b/backend/alembic/versions/b81f3c2a6d40_add_challenge_starts_at.py @@ -0,0 +1,32 @@ +"""add challenge start time + +Revision ID: b81f3c2a6d40 +Revises: 4f21ac9d7b30 +""" + +from collections.abc import Sequence + +import sqlalchemy as sa + +from alembic import op + +revision: str = "b81f3c2a6d40" +down_revision: str | Sequence[str] | None = "4f21ac9d7b30" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.add_column( + "challenges", + sa.Column( + "starts_at", + sa.DateTime(timezone=True), + server_default=sa.text("now()"), + nullable=False, + ), + ) + + +def downgrade() -> None: + op.drop_column("challenges", "starts_at") diff --git a/backend/alembic/versions/b84e1b2f6a90_user_owned_usernames.py b/backend/alembic/versions/b84e1b2f6a90_user_owned_usernames.py deleted file mode 100644 index b4edf37b..00000000 --- a/backend/alembic/versions/b84e1b2f6a90_user_owned_usernames.py +++ /dev/null @@ -1,97 +0,0 @@ -"""move username assignment from participants to users - -Revision ID: b84e1b2f6a90 -Revises: 597d02678cf0 -Create Date: 2026-09-27 23:10:00.000000 - -""" - -from collections.abc import Sequence - -import sqlalchemy as sa - -from alembic import op - -# revision identifiers, used by Alembic. -revision: str = "b84e1b2f6a90" -down_revision: str | Sequence[str] | None = "597d02678cf0" -branch_labels: str | Sequence[str] | None = None -depends_on: str | Sequence[str] | None = None - - -def upgrade() -> None: - op.add_column("users", sa.Column("username_id", sa.Uuid(), nullable=True)) - op.create_foreign_key( - "users_username_id_fkey", "users", "usernames", ["username_id"], ["id"] - ) - op.create_unique_constraint("users_username_id_key", "users", ["username_id"]) - - op.execute( - sa.text( - """ - WITH ranked_assignments AS ( - SELECT - user_id, - username_id, - row_number() OVER ( - PARTITION BY user_id ORDER BY created_at, id - ) AS user_rank, - row_number() OVER ( - PARTITION BY username_id ORDER BY created_at, id - ) AS username_rank - FROM challenge_participants - WHERE username_id IS NOT NULL - ) - UPDATE users - SET username_id = ranked_assignments.username_id - FROM ranked_assignments - WHERE users.id = ranked_assignments.user_id - AND ranked_assignments.user_rank = 1 - AND ranked_assignments.username_rank = 1 - """ - ) - ) - - op.drop_constraint( - "uq_participant_username_challenge", - "challenge_participants", - type_="unique", - ) - op.drop_constraint( - "challenge_participants_username_id_fkey", - "challenge_participants", - type_="foreignkey", - ) - op.drop_column("challenge_participants", "username_id") - - -def downgrade() -> None: - op.add_column( - "challenge_participants", - sa.Column("username_id", sa.Uuid(), nullable=True), - ) - op.create_foreign_key( - "challenge_participants_username_id_fkey", - "challenge_participants", - "usernames", - ["username_id"], - ["id"], - ) - op.create_unique_constraint( - "uq_participant_username_challenge", - "challenge_participants", - ["challenge_id", "username_id"], - ) - op.execute( - sa.text( - """ - UPDATE challenge_participants - SET username_id = users.username_id - FROM users - WHERE challenge_participants.user_id = users.id - """ - ) - ) - op.drop_constraint("users_username_id_key", "users", type_="unique") - op.drop_constraint("users_username_id_fkey", "users", type_="foreignkey") - op.drop_column("users", "username_id") diff --git a/backend/alembic/versions/c8389c55b075_challenges_tables.py b/backend/alembic/versions/c8389c55b075_challenges_tables.py deleted file mode 100644 index 7ae692d1..00000000 --- a/backend/alembic/versions/c8389c55b075_challenges_tables.py +++ /dev/null @@ -1,210 +0,0 @@ -"""challenges tables - -Revision ID: c8389c55b075 -Revises: dd4ca2ff096e -Create Date: 2026-09-27 00:27:26.225175 - -""" - -from collections.abc import Sequence - -import sqlalchemy as sa - -from alembic import op - -# revision identifiers, used by Alembic. -revision: str = "c8389c55b075" -down_revision: str | Sequence[str] | None = "dd4ca2ff096e" -branch_labels: str | Sequence[str] | None = None -depends_on: str | Sequence[str] | None = None - - -def upgrade() -> None: - """Upgrade schema.""" - # ### commands auto generated by Alembic - please adjust! ### - op.create_table( - "challenges", - sa.Column("id", sa.Uuid(), nullable=False), - sa.Column("title", sa.String(length=255), nullable=False), - sa.Column( - "scoring_type", - sa.Enum( - "QUIZ", - "MANUAL", - name="challengescoringtype", - native_enum=False, - length=20, - ), - nullable=False, - ), - sa.Column( - "created_at", - sa.DateTime(timezone=True), - server_default=sa.text("now()"), - nullable=False, - ), - sa.Column( - "updated_at", - sa.DateTime(timezone=True), - server_default=sa.text("now()"), - nullable=False, - ), - sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), - sa.PrimaryKeyConstraint("id", name=op.f("challenges_pkey")), - ) - op.create_index( - op.f("challenges_deleted_at_idx"), "challenges", ["deleted_at"], unique=False - ) - op.create_table( - "username_mothers", - sa.Column("id", sa.Uuid(), nullable=False), - sa.Column("first_name", sa.String(length=100), nullable=False), - sa.Column("last_name", sa.String(length=100), nullable=False), - sa.Column("full_name", sa.String(length=201), nullable=False), - sa.Column("description", sa.Text(), nullable=False), - sa.PrimaryKeyConstraint("id", name=op.f("username_mothers_pkey")), - sa.UniqueConstraint("full_name", name=op.f("username_mothers_full_name_key")), - ) - op.create_table( - "questions", - sa.Column("id", sa.Uuid(), nullable=False), - sa.Column("prompt", sa.String(length=5000), nullable=False), - sa.Column("answer", sa.String(length=255), nullable=False), - sa.Column("points_value", sa.Integer(), nullable=False), - sa.Column("challenge_id", sa.Uuid(), nullable=False), - sa.ForeignKeyConstraint( - ["challenge_id"], - ["challenges.id"], - name=op.f("questions_challenge_id_fkey"), - ), - sa.PrimaryKeyConstraint("id", name=op.f("questions_pkey")), - ) - op.create_table( - "usernames", - sa.Column("id", sa.Uuid(), nullable=False), - sa.Column("nickname", sa.String(length=255), nullable=False), - sa.Column("first_mother_id", sa.Uuid(), nullable=False), - sa.Column("last_mother_id", sa.Uuid(), nullable=False), - sa.ForeignKeyConstraint( - ["first_mother_id"], - ["username_mothers.id"], - name=op.f("usernames_first_mother_id_fkey"), - ), - sa.ForeignKeyConstraint( - ["last_mother_id"], - ["username_mothers.id"], - name=op.f("usernames_last_mother_id_fkey"), - ), - sa.PrimaryKeyConstraint("id", name=op.f("usernames_pkey")), - sa.UniqueConstraint("nickname", name=op.f("usernames_nickname_key")), - ) - op.create_table( - "challenge_participants", - sa.Column("id", sa.Uuid(), nullable=False), - sa.Column("user_id", sa.Uuid(), nullable=False), - sa.Column("challenge_id", sa.Uuid(), nullable=False), - sa.Column("username_id", sa.Uuid(), nullable=True), - sa.Column("score", sa.Integer(), nullable=False), - sa.Column("submitted_at", sa.DateTime(timezone=True), nullable=True), - sa.Column( - "created_at", - sa.DateTime(timezone=True), - server_default=sa.text("now()"), - nullable=False, - ), - sa.Column( - "updated_at", - sa.DateTime(timezone=True), - server_default=sa.text("now()"), - nullable=False, - ), - sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), - sa.ForeignKeyConstraint( - ["challenge_id"], - ["challenges.id"], - name=op.f("challenge_participants_challenge_id_fkey"), - ), - sa.ForeignKeyConstraint( - ["user_id"], - ["users.id"], - name=op.f("challenge_participants_user_id_fkey"), - ondelete="CASCADE", - ), - sa.ForeignKeyConstraint( - ["username_id"], - ["usernames.id"], - name=op.f("challenge_participants_username_id_fkey"), - ), - sa.PrimaryKeyConstraint("id", name=op.f("challenge_participants_pkey")), - sa.UniqueConstraint( - "challenge_id", "username_id", name="uq_participant_username_challenge" - ), - sa.UniqueConstraint( - "user_id", "challenge_id", name="uq_participant_user_challenge" - ), - ) - op.create_index( - op.f("challenge_participants_deleted_at_idx"), - "challenge_participants", - ["deleted_at"], - unique=False, - ) - op.create_table( - "answers", - sa.Column("id", sa.Uuid(), nullable=False), - sa.Column("participant_id", sa.Uuid(), nullable=False), - sa.Column("question_id", sa.Uuid(), nullable=False), - sa.Column("content", sa.String(length=255), nullable=False), - sa.Column("is_correct", sa.Boolean(), nullable=False), - sa.Column( - "created_at", - sa.DateTime(timezone=True), - server_default=sa.text("now()"), - nullable=False, - ), - sa.Column( - "updated_at", - sa.DateTime(timezone=True), - server_default=sa.text("now()"), - nullable=False, - ), - sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), - sa.ForeignKeyConstraint( - ["participant_id"], - ["challenge_participants.id"], - name=op.f("answers_participant_id_fkey"), - ondelete="CASCADE", - ), - sa.ForeignKeyConstraint( - ["question_id"], - ["questions.id"], - name=op.f("answers_question_id_fkey"), - ondelete="CASCADE", - ), - sa.PrimaryKeyConstraint("id", name=op.f("answers_pkey")), - sa.UniqueConstraint( - "participant_id", "question_id", name="uq_participant_question" - ), - ) - op.create_index( - op.f("answers_deleted_at_idx"), "answers", ["deleted_at"], unique=False - ) - # ### end Alembic commands ### - - -def downgrade() -> None: - """Downgrade schema.""" - # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f("answers_deleted_at_idx"), table_name="answers") - op.drop_table("answers") - op.drop_index( - op.f("challenge_participants_deleted_at_idx"), - table_name="challenge_participants", - ) - op.drop_table("challenge_participants") - op.drop_table("usernames") - op.drop_table("questions") - op.drop_table("username_mothers") - op.drop_index(op.f("challenges_deleted_at_idx"), table_name="challenges") - op.drop_table("challenges") - # ### end Alembic commands ### diff --git a/backend/alembic/versions/d01c0010d74b_create_users_table.py b/backend/alembic/versions/d01c0010d74b_create_users_table.py deleted file mode 100644 index b82900e0..00000000 --- a/backend/alembic/versions/d01c0010d74b_create_users_table.py +++ /dev/null @@ -1,53 +0,0 @@ -"""create users table - -Revision ID: d01c0010d74b -Revises: -Create Date: 2026-09-02 18:39:01.652422 - -""" - -from collections.abc import Sequence - -import sqlalchemy as sa - -from alembic import op - -# revision identifiers, used by Alembic. -revision: str = "d01c0010d74b" -down_revision: str | Sequence[str] | None = None -branch_labels: str | Sequence[str] | None = None -depends_on: str | Sequence[str] | None = None - - -def upgrade() -> None: - """Upgrade schema.""" - # ### commands auto generated by Alembic - please adjust! ### - op.create_table( - "users", - sa.Column("id", sa.Uuid(), nullable=False), - sa.Column("email", sa.String(length=255), nullable=False), - sa.Column("name", sa.String(length=255), nullable=False), - sa.Column("password_hash", sa.String(length=255), nullable=True), - sa.Column("is_admin", sa.Boolean(), server_default="false", nullable=False), - sa.Column("is_verified", sa.Boolean(), server_default="false", nullable=False), - sa.Column( - "created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False - ), - sa.Column( - "updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False - ), - sa.Column("deleted_at", sa.DateTime(), nullable=True), - sa.PrimaryKeyConstraint("id", name=op.f("users_pkey")), - ) - op.create_index(op.f("users_deleted_at_idx"), "users", ["deleted_at"], unique=False) - op.create_index(op.f("users_email_idx"), "users", ["email"], unique=True) - # ### end Alembic commands ### - - -def downgrade() -> None: - """Downgrade schema.""" - # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f("users_email_idx"), table_name="users") - op.drop_index(op.f("users_deleted_at_idx"), table_name="users") - op.drop_table("users") - # ### end Alembic commands ### diff --git a/backend/alembic/versions/dd4ca2ff096e_add_scopes_to_refresh_tokens.py b/backend/alembic/versions/dd4ca2ff096e_add_scopes_to_refresh_tokens.py deleted file mode 100644 index 2976b532..00000000 --- a/backend/alembic/versions/dd4ca2ff096e_add_scopes_to_refresh_tokens.py +++ /dev/null @@ -1,35 +0,0 @@ -"""add scopes to refresh_tokens - -Revision ID: dd4ca2ff096e -Revises: 91cc57573789 -Create Date: 2026-09-11 00:05:46.857827 - -""" - -from collections.abc import Sequence - -import sqlalchemy as sa - -from alembic import op - -# revision identifiers, used by Alembic. -revision: str = "dd4ca2ff096e" -down_revision: str | Sequence[str] | None = "91cc57573789" -branch_labels: str | Sequence[str] | None = None -depends_on: str | Sequence[str] | None = None - - -def upgrade() -> None: - """Upgrade schema.""" - # ### commands auto generated by Alembic - please adjust! ### - op.add_column( - "refresh_tokens", sa.Column("scopes", sa.String(length=255), nullable=False) - ) - # ### end Alembic commands ### - - -def downgrade() -> None: - """Downgrade schema.""" - # ### commands auto generated by Alembic - please adjust! ### - op.drop_column("refresh_tokens", "scopes") - # ### end Alembic commands ### diff --git a/backend/alembic/versions/597d02678cf0_challenges_cover_image.py b/backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py similarity index 62% rename from backend/alembic/versions/597d02678cf0_challenges_cover_image.py rename to backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py index 5802d7f8..eae018ea 100644 --- a/backend/alembic/versions/597d02678cf0_challenges_cover_image.py +++ b/backend/alembic/versions/e0bee973af24_add_oauth_provider_to_users.py @@ -1,8 +1,8 @@ -"""challenges cover image +"""add oauth provider to users -Revision ID: 597d02678cf0 -Revises: 7b14a96d2c83 -Create Date: 2026-09-27 21:30:55.360689 +Revision ID: e0bee973af24 +Revises: 4f21ac9d7b30 +Create Date: 2026-10-02 13:52:42.044097 """ @@ -13,8 +13,8 @@ from alembic import op # revision identifiers, used by Alembic. -revision: str = "597d02678cf0" -down_revision: str | Sequence[str] | None = "7b14a96d2c83" +revision: str = "e0bee973af24" +down_revision: str | Sequence[str] | None = "b81f3c2a6d40" branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None @@ -23,7 +23,7 @@ def upgrade() -> None: """Upgrade schema.""" # ### commands auto generated by Alembic - please adjust! ### op.add_column( - "challenges", sa.Column("image_path", sa.String(length=512), nullable=True) + "users", sa.Column("oauth_provider", sa.String(length=16), nullable=True) ) # ### end Alembic commands ### @@ -31,5 +31,5 @@ def upgrade() -> None: def downgrade() -> None: """Downgrade schema.""" # ### commands auto generated by Alembic - please adjust! ### - op.drop_column("challenges", "image_path") + op.drop_column("users", "oauth_provider") # ### end Alembic commands ### diff --git a/backend/alembic/versions/f7c2d9a4e1b6_add_oauth_subject_to_users.py b/backend/alembic/versions/f7c2d9a4e1b6_add_oauth_subject_to_users.py new file mode 100644 index 00000000..ec8a1899 --- /dev/null +++ b/backend/alembic/versions/f7c2d9a4e1b6_add_oauth_subject_to_users.py @@ -0,0 +1,30 @@ +"""add oauth subject to users + +Revision ID: f7c2d9a4e1b6 +Revises: e0bee973af24 +""" + +from collections.abc import Sequence + +import sqlalchemy as sa + +from alembic import op + +revision: str = "f7c2d9a4e1b6" +down_revision: str | Sequence[str] | None = "e0bee973af24" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + op.add_column( + "users", sa.Column("oauth_subject", sa.String(length=255), nullable=True) + ) + op.create_unique_constraint( + "users_oauth_identity_key", "users", ["oauth_provider", "oauth_subject"] + ) + + +def downgrade() -> None: + op.drop_constraint("users_oauth_identity_key", "users", type_="unique") + op.drop_column("users", "oauth_subject") diff --git a/backend/app/atividade/image.py b/backend/app/atividade/image.py new file mode 100644 index 00000000..aa0d8e0e --- /dev/null +++ b/backend/app/atividade/image.py @@ -0,0 +1,26 @@ +from fastapi import UploadFile + +from app.core.exceptions.app_errors import BadRequestError +from app.core.storage import save_bytes + +ALLOWED_IMAGE_TYPES = { + "image/jpeg": "jpg", + "image/png": "png", + "image/webp": "webp", +} +MAX_IMAGE_BYTES = 5 * 1024 * 1024 + + +async def save_palestrante_photo(file: UploadFile) -> str: + extension = ALLOWED_IMAGE_TYPES.get(file.content_type or "") + if extension is None: + raise BadRequestError( + f"Unsupported image type: {file.content_type}. " + f"Allowed: {sorted(ALLOWED_IMAGE_TYPES)}" + ) + + contents = await file.read(MAX_IMAGE_BYTES + 1) + if len(contents) > MAX_IMAGE_BYTES: + raise BadRequestError(f"Image too large (max {MAX_IMAGE_BYTES} bytes).") + + return f"/media/{await save_bytes(contents, subdir='palestrantes', extension=extension)}" diff --git a/backend/app/atividade/models.py b/backend/app/atividade/models.py index cb693236..286dedcb 100644 --- a/backend/app/atividade/models.py +++ b/backend/app/atividade/models.py @@ -1,83 +1,95 @@ -from datetime import UTC, datetime -from enum import Enum -from uuid import UUID, uuid4 +from __future__ import annotations -import jwt -from core.models import Base -from presenca import Presenca -from sqlalchemy import DateTime, ForeignKey, LargeBinary, String, UUIDType -from sqlalchemy.orm import Mapped, SQLEnum, mapped_column, relationship +import uuid +from datetime import datetime +from enum import StrEnum +from typing import TYPE_CHECKING -from app.core.config import settings +from sqlalchemy import ( + JSON, + DateTime, + ForeignKey, + Index, + Integer, + String, + UniqueConstraint, +) +from sqlalchemy.orm import Mapped, mapped_column, relationship +from app.core.mixins import TimestampsMixin, UUIDPKMixin +from app.core.models import Base -class StatusAtividade(str, Enum): +if TYPE_CHECKING: + from app.semana.models import Semana + from app.users.models import User + + +class StatusAtividade(StrEnum): PROVISORIA = "provisoria" CONFIRMADA = "confirmada" -class TipoAtividade(str, Enum): +class TipoAtividade(StrEnum): PALESTRA = "palestra" + WORKSHOP = "workshop" ENCERRAMENTO = "encerramento" CONVERSA = "conversa" COFFEE_BREAK = "coffee_break" -class SemanaEvent(Base): - __tablename__ = "semana_event" - - id: Mapped[int] = mapped_column(primary_key=True) - nome: Mapped[str] = mapped_column(String(255)) - ano: Mapped[int] = mapped_column() - atividades: Mapped[list["Atividade"]] = relationship(back_populates="semana") - +class Atividade(Base, UUIDPKMixin, TimestampsMixin): + __tablename__ = "atividades" -class Atividade(Base): - __tablename__ = "atividade" - - id: Mapped[int] = mapped_column(primary_key=True) - semana_event_id: Mapped[int] = mapped_column(ForeignKey("semana_event.id")) - - tipo: Mapped[TipoAtividade] = mapped_column(SQLEnum(TipoAtividade)) - titulo: Mapped[str] = mapped_column(String(255), default="") + semana_id: Mapped[int] = mapped_column( + ForeignKey("semana_event.id", ondelete="CASCADE"), index=True + ) + tipo: Mapped[TipoAtividade] = mapped_column(nullable=False) + titulo: Mapped[str] = mapped_column(String(255), default="", nullable=False) + descricao: Mapped[str | None] = mapped_column(String(5000), nullable=True) + local: Mapped[str | None] = mapped_column(String(255), nullable=True) + palestrantes: Mapped[list[dict[str, str]]] = mapped_column( + JSON, default=list, nullable=False + ) + link_live: Mapped[str | None] = mapped_column(String(500), nullable=True) status: Mapped[StatusAtividade] = mapped_column( - SQLEnum(StatusAtividade), default=StatusAtividade.PROVISORIA + default=StatusAtividade.PROVISORIA, nullable=False ) - comeca_as: Mapped[datetime] = mapped_column(DateTime, unique=True) - termina_as: Mapped[datetime] = mapped_column(DateTime, unique=True) - qr_code: Mapped[bytes | None] = mapped_column(LargeBinary, nullable=True) - uid: Mapped[UUID] = mapped_column(UUIDType, default=uuid4, unique=True) - token: Mapped[str | None] = mapped_column(String(512), default="", nullable=True) - - semana_id: Mapped[int] = mapped_column(ForeignKey("semana_event.id")) - semana: Mapped["SemanaEvent"] = mapped_column(ForeignKey("semana_event")) + comeca_as: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False) + termina_as: Mapped[datetime] = mapped_column( + DateTime(timezone=True), nullable=False + ) + codigo: Mapped[str] = mapped_column(String(4), nullable=False) + pontos: Mapped[int] = mapped_column(Integer, default=0, nullable=False) + horas: Mapped[int] = mapped_column(Integer, default=1, nullable=False) - registro_presenca: Mapped[list["Presenca"]] = relationship( + semana: Mapped[Semana] = relationship(back_populates="atividades") + presencas: Mapped[list[Presenca]] = relationship( back_populates="atividade", cascade="all, delete-orphan" ) - def _generate_signed_token(self) -> str: - payload = { - "uid": str(self.uid), - "type": "qr_presence", - "iat": int(datetime.now(UTC).timestamp()), - } - - token = jwt.encode( - payload, settings.secret_key.get_secret_value(), algorithm="HS256" - ) + __table_args__ = ( + UniqueConstraint("semana_id", "codigo", name="uq_atividade_semana_codigo"), + Index("ix_atividade_semana_schedule", "semana_id", "comeca_as"), + ) - self.token = token - return token - def generate_qr_data(self) -> str: - return self._generate_signed_token() +class Presenca(Base, UUIDPKMixin, TimestampsMixin): + __tablename__ = "presencas" - def generate_qr_code(self): - pass + atividade_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("atividades.id", ondelete="CASCADE"), index=True + ) + user_id: Mapped[uuid.UUID | None] = mapped_column( + ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True + ) + nome: Mapped[str] = mapped_column(String(255), nullable=False) + email: Mapped[str] = mapped_column(String(255), nullable=False) + horas: Mapped[int] = mapped_column(Integer, nullable=False) - def save(self): - pass + atividade: Mapped[Atividade] = relationship(back_populates="presencas") + user: Mapped[User | None] = relationship() - def __str__(self): - return f"{self.titulo} - {self.comeca_as.strftime('%d/%m/%Y %H:%M')}" + __table_args__ = ( + UniqueConstraint("atividade_id", "user_id", name="uq_presenca_atividade_user"), + UniqueConstraint("atividade_id", "email", name="uq_presenca_atividade_email"), + ) diff --git a/backend/app/atividade/presenca.py b/backend/app/atividade/presenca.py index a84b78cf..7098c10f 100644 --- a/backend/app/atividade/presenca.py +++ b/backend/app/atividade/presenca.py @@ -1,25 +1,3 @@ -from core.models import Base -from models import Atividade -from sqlalchemy import DateTime, ForeignKey, String, func -from sqlalchemy.orm import Mapped, mapped_column, relationship +from app.atividade.models import Presenca - -class Presenca(Base): - __tablename__ = "presenca" - - id: Mapped[int] = mapped_column(primary_key=True) - nome: Mapped[str] = mapped_column(String(255), default="") - email: Mapped[str] = mapped_column(String(255), default="") - - atividade_id: Mapped[int] = mapped_column( - ForeignKey("atividade.id"), nullable=False - ) - atividade: Mapped["Atividade"] = relationship(back_populates="registros_presenca") - horario_registro: Mapped[DateTime] = mapped_column( - DateTime(timezone=True), server_default=func.now() - ) - horas: Mapped[int] = mapped_column(default=1) - compartilhar_email: Mapped[bool] = mapped_column(default=False) - - def __str__(self): - return f"{self.nome} ({self.email}) - {self.atividade.titulo}" +__all__ = ["Presenca"] diff --git a/backend/app/atividade/routes.py b/backend/app/atividade/routes.py new file mode 100644 index 00000000..087287f6 --- /dev/null +++ b/backend/app/atividade/routes.py @@ -0,0 +1,212 @@ +from typing import Annotated +from uuid import UUID + +from fastapi import APIRouter, Depends, File, Path, Security, UploadFile +from sqlalchemy.ext.asyncio import AsyncSession + +from app.atividade import schemas, services +from app.atividade.image import save_palestrante_photo +from app.atividade.models import Presenca +from app.auth.dependencies import get_current_admin_user, get_optional_current_user +from app.auth.scopes import Scope +from app.core.database import get_session +from app.core.exceptions.app_errors import NotFoundError +from app.semana.services import get_semana +from app.users.models import User + +router = APIRouter(prefix="/semanas/{semana_id}/atividades", tags=["atividade"]) +attendance_router = APIRouter( + prefix="/semanas/{semana_id}/atividades", tags=["atividade"] +) +admin_router = APIRouter( + prefix="/admin/semanas/{semana_id}/atividades", tags=["admin", "atividade"] +) + + +async def _require_semana(session: AsyncSession, semana_id: int): + semana = await get_semana(session, semana_id) + if semana is None: + raise NotFoundError("Semana not found.") + return semana + + +@router.get("", response_model=list[schemas.AtividadeResponse]) +@router.get( + "/", response_model=list[schemas.AtividadeResponse], include_in_schema=False +) +async def list_atividades( + semana_id: int, session: Annotated[AsyncSession, Depends(get_session)] +): + await _require_semana(session, semana_id) + return await services.list_atividades(session, semana_id, confirmed_only=True) + + +@admin_router.get("", response_model=list[schemas.AtividadeResponse]) +@admin_router.get( + "/", response_model=list[schemas.AtividadeResponse], include_in_schema=False +) +async def list_admin_atividades( + semana_id: int, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + await _require_semana(session, semana_id) + return await services.list_atividades(session, semana_id) + + +@admin_router.post("", response_model=schemas.AtividadeResponse, status_code=201) +async def create_admin_atividade( + semana_id: int, + data: schemas.AtividadeCreate, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + semana = await _require_semana(session, semana_id) + return await services.create_atividade(session, semana, **data.model_dump()) + + +@admin_router.patch("/{atividade_id}", response_model=schemas.AtividadeResponse) +async def update_admin_atividade( + semana_id: int, + atividade_id: UUID, + data: schemas.AtividadeUpdate, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + atividade = await services.get_atividade(session, semana_id, atividade_id) + if atividade is None: + raise NotFoundError("Activity not found.") + return await services.update_atividade( + session, atividade, data.model_dump(exclude_unset=True) + ) + + +@admin_router.put( + "/{atividade_id}/palestrantes/{palestrante_index}/foto", + response_model=schemas.AtividadeResponse, +) +async def upload_palestrante_photo( + semana_id: int, + atividade_id: UUID, + palestrante_index: int, + file: Annotated[UploadFile, File()], + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + atividade = await services.get_atividade(session, semana_id, atividade_id) + if atividade is None: + raise NotFoundError("Activity not found.") + if not 0 <= palestrante_index < len(atividade.palestrantes): + raise NotFoundError("Speaker not found.") + + photo_url = await save_palestrante_photo(file) + speakers = [speaker.copy() for speaker in atividade.palestrantes] + speakers[palestrante_index]["foto"] = photo_url + atividade.palestrantes = speakers + await session.commit() + await session.refresh(atividade) + return atividade + + +@admin_router.delete("/{atividade_id}", status_code=204) +async def delete_admin_atividade( + semana_id: int, + atividade_id: UUID, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + atividade = await services.get_atividade(session, semana_id, atividade_id) + if atividade is None: + raise NotFoundError("Activity not found.") + await session.delete(atividade) + + +@admin_router.post( + "/{atividade_id}/regenerar-codigo", response_model=schemas.AtividadeResponse +) +async def regenerate_admin_atividade_code( + semana_id: int, + atividade_id: UUID, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + atividade = await services.get_atividade(session, semana_id, atividade_id) + if atividade is None: + raise NotFoundError("Activity not found.") + return await services.regenerate_codigo(session, atividade) + + +@admin_router.get( + "/{atividade_id}/presencas", + response_model=list[schemas.AdminPresencaResponse], +) +async def list_admin_presencas( + semana_id: int, + atividade_id: UUID, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + if await services.get_atividade(session, semana_id, atividade_id) is None: + raise NotFoundError("Activity not found.") + return await services.list_presencas(session, atividade_id) + + +@admin_router.post( + "/{atividade_id}/presencas", + response_model=schemas.AdminPresencaResponse, + status_code=201, +) +async def create_admin_presenca( + semana_id: int, + atividade_id: UUID, + data: schemas.AdminPresencaCreate, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + atividade = await services.get_atividade(session, semana_id, atividade_id) + if atividade is None: + raise NotFoundError("Activity not found.") + return await services.register_manual_presence( + session, atividade, data.nome, str(data.email) + ) + + +@admin_router.delete("/{atividade_id}/presencas/{presenca_id}", status_code=204) +async def delete_admin_presenca( + semana_id: int, + atividade_id: UUID, + presenca_id: UUID, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + if await services.get_atividade(session, semana_id, atividade_id) is None: + raise NotFoundError("Activity not found.") + presence = await session.get(Presenca, presenca_id) + if presence is None or presence.atividade_id != atividade_id: + raise NotFoundError("Attendance not found.") + await services.delete_presence(session, presence) + + +@attendance_router.post( + "/registrar/{codigo}", + response_model=schemas.PresencaResponse, +) +async def register_atividade_presence( + semana_id: int, + codigo: Annotated[str, Path(pattern=r"^\d{4}$")], + data: schemas.PresencaRequest, + session: Annotated[AsyncSession, Depends(get_session)], + user: Annotated[User | None, Depends(get_optional_current_user)], +): + await _require_semana(session, semana_id) + atividade = await services.get_atividade_by_codigo(session, semana_id, codigo) + if atividade is None: + raise NotFoundError("Activity not found.") + presence, points = await services.register_presence( + session, atividade, user, data.nome, data.email + ) + return schemas.PresencaResponse( + atividade_id=presence.atividade_id, + pontos_adicionados=points, + horas=presence.horas, + ) diff --git a/backend/app/atividade/schemas.py b/backend/app/atividade/schemas.py new file mode 100644 index 00000000..51c5617f --- /dev/null +++ b/backend/app/atividade/schemas.py @@ -0,0 +1,102 @@ +from datetime import datetime +from uuid import UUID + +from pydantic import ( + BaseModel, + ConfigDict, + EmailStr, + Field, + field_validator, + model_validator, +) + +from app.atividade.models import StatusAtividade, TipoAtividade + + +class AtividadeCreate(BaseModel): + tipo: TipoAtividade + titulo: str = "" + descricao: str | None = None + local: str | None = None + palestrantes: list[dict[str, str]] = Field(default_factory=list) + link_live: str | None = None + comeca_as: datetime + termina_as: datetime + status: StatusAtividade = StatusAtividade.PROVISORIA + pontos: int = Field(default=0, ge=0) + horas: int = Field(default=1, ge=1) + + @model_validator(mode="after") + def validate_schedule(self): + if self.termina_as <= self.comeca_as: + raise ValueError("termina_as must be after comeca_as") + return self + + +class AtividadeUpdate(BaseModel): + tipo: TipoAtividade | None = None + titulo: str | None = None + descricao: str | None = None + local: str | None = None + palestrantes: list[dict[str, str]] | None = None + link_live: str | None = None + comeca_as: datetime | None = None + termina_as: datetime | None = None + status: StatusAtividade | None = None + pontos: int | None = Field(default=None, ge=0) + horas: int | None = Field(default=None, ge=1) + + +class AtividadeResponse(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: UUID + semana_id: int + tipo: TipoAtividade + titulo: str + descricao: str | None + local: str | None + palestrantes: list[dict[str, str]] + link_live: str | None + status: StatusAtividade + comeca_as: datetime + termina_as: datetime + codigo: str + pontos: int + horas: int + + +class PresencaRequest(BaseModel): + nome: str | None = Field(default=None, min_length=1, max_length=255) + email: EmailStr | None = None + + +class PresencaResponse(BaseModel): + atividade_id: UUID + registrada: bool = True + pontos_adicionados: int + horas: int + + +class AdminPresencaCreate(BaseModel): + nome: str | None = Field(default=None, max_length=255) + email: EmailStr + + @field_validator("nome", mode="before") + @classmethod + def empty_name_is_none(cls, value: str | None) -> str | None: + if isinstance(value, str): + value = value.strip() + return value or None + return value + + +class AdminPresencaResponse(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: UUID + atividade_id: UUID + user_id: UUID | None + nome: str + email: EmailStr + horas: int diff --git a/backend/app/atividade/services.py b/backend/app/atividade/services.py new file mode 100644 index 00000000..ee814267 --- /dev/null +++ b/backend/app/atividade/services.py @@ -0,0 +1,225 @@ +import secrets +from datetime import UTC, datetime, timedelta +from uuid import UUID + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.atividade.models import Atividade, Presenca, StatusAtividade +from app.core.exceptions.app_errors import BadRequestError +from app.semana.models import PointEvent, Semana, SemanaParticipant +from app.semana.services import add_points, get_or_create_participant +from app.users.models import User +from app.users.services import get_user_by_email + + +async def list_atividades( + session: AsyncSession, semana_id: int, confirmed_only: bool = False +) -> list[Atividade]: + filters = [Atividade.semana_id == semana_id] + if confirmed_only: + filters.append(Atividade.status == StatusAtividade.CONFIRMADA) + result = await session.scalars( + select(Atividade).where(*filters).order_by(Atividade.comeca_as) + ) + return list(result.all()) + + +async def get_atividade( + session: AsyncSession, semana_id: int, atividade_id: UUID +) -> Atividade | None: + return await session.scalar( + select(Atividade).where( + Atividade.id == atividade_id, Atividade.semana_id == semana_id + ) + ) + + +async def get_atividade_by_codigo( + session: AsyncSession, semana_id: int, codigo: str +) -> Atividade | None: + return await session.scalar( + select(Atividade).where( + Atividade.semana_id == semana_id, Atividade.codigo == codigo + ) + ) + + +def _new_codigo() -> str: + return f"{secrets.randbelow(10_000):04d}" + + +async def _unique_codigo( + session: AsyncSession, semana_id: int, exclude_id: UUID | None = None +) -> str: + for _ in range(10_000): + codigo = _new_codigo() + exists = await session.scalar( + select(Atividade.id).where( + Atividade.semana_id == semana_id, + Atividade.codigo == codigo, + Atividade.id != exclude_id if exclude_id else True, + ) + ) + if exists is None: + return codigo + raise BadRequestError("No activity code is available for this Semana.") + + +async def create_atividade( + session: AsyncSession, semana: Semana, **fields +) -> Atividade: + atividade = Atividade( + semana_id=semana.id, + codigo=await _unique_codigo(session, semana.id), + **fields, + ) + session.add(atividade) + await session.flush() + return atividade + + +async def regenerate_codigo(session: AsyncSession, atividade: Atividade) -> Atividade: + atividade.codigo = await _unique_codigo(session, atividade.semana_id, atividade.id) + await session.flush() + return atividade + + +async def list_presencas(session: AsyncSession, atividade_id: UUID) -> list[Presenca]: + result = await session.scalars( + select(Presenca) + .where(Presenca.atividade_id == atividade_id) + .order_by(Presenca.created_at.desc()) + ) + return list(result.all()) + + +async def register_manual_presence( + session: AsyncSession, atividade: Atividade, nome: str | None, email: str +) -> Presenca: + email = email.strip().lower() + existing = await session.scalar( + select(Presenca).where( + Presenca.atividade_id == atividade.id, Presenca.email == email + ) + ) + if existing is not None: + return existing + + user = await get_user_by_email(session, email) + if user is not None: + nome = user.name + elif not nome: + raise BadRequestError("nome is required for visitors.") + presence = Presenca( + atividade_id=atividade.id, + user_id=user.id if user else None, + nome=nome.strip(), + email=email, + horas=atividade.horas, + ) + session.add(presence) + await session.flush() + + if user is not None and atividade.pontos: + participant = await get_or_create_participant( + session, await session.get(Semana, atividade.semana_id), user + ) + await add_points( + session, + participant, + atividade.pontos, + source_type="atividade", + source_id=atividade.id, + reason=atividade.titulo or "Atividade", + ) + return presence + + +async def delete_presence(session: AsyncSession, presence: Presenca) -> None: + if presence.user_id is not None: + point_event = await session.scalar( + select(PointEvent).where( + PointEvent.semana_participant_id.in_( + select(SemanaParticipant.id).where( + SemanaParticipant.user_id == presence.user_id, + SemanaParticipant.semana_id == presence.atividade.semana_id, + ) + ), + PointEvent.source_type == "atividade", + PointEvent.source_id == presence.atividade_id, + ) + ) + if point_event is not None: + await session.delete(point_event) + await session.delete(presence) + + +async def update_atividade( + session: AsyncSession, atividade: Atividade, fields: dict +) -> Atividade: + values = fields + starts = values.get("comeca_as", atividade.comeca_as) + ends = values.get("termina_as", atividade.termina_as) + if ends <= starts: + raise BadRequestError("termina_as must be after comeca_as") + for key, value in values.items(): + setattr(atividade, key, value) + await session.flush() + return atividade + + +async def register_presence( + session: AsyncSession, + atividade: Atividade, + user: User | None, + nome: str | None, + email: str | None, +) -> tuple[Presenca, int]: + now = datetime.now(UTC) + if atividade.status != StatusAtividade.CONFIRMADA: + raise BadRequestError("Activity is not confirmed.") + if now < atividade.comeca_as or now > atividade.termina_as + timedelta(minutes=30): + raise BadRequestError("Attendance window is closed.") + + if user is not None: + nome, email = user.name, user.email + elif not nome or not email: + raise BadRequestError("nome and email are required for visitors.") + + email = email.strip().lower() + existing = await session.scalar( + select(Presenca).where( + Presenca.atividade_id == atividade.id, + Presenca.email == email, + ) + ) + if existing is not None: + return existing, 0 + + presence = Presenca( + atividade_id=atividade.id, + user_id=user.id if user else None, + nome=nome.strip(), + email=email, + horas=atividade.horas, + ) + session.add(presence) + await session.flush() + + points = 0 + if user is not None: + participant = await get_or_create_participant( + session, await session.get(Semana, atividade.semana_id), user + ) + if atividade.pontos: + await add_points( + session, + participant, + atividade.pontos, + source_type="atividade", + source_id=atividade.id, + reason=atividade.titulo or "Atividade", + ) + points = atividade.pontos + return presence, points diff --git a/backend/app/auth/dependencies.py b/backend/app/auth/dependencies.py index ef82b4b2..0b841b77 100644 --- a/backend/app/auth/dependencies.py +++ b/backend/app/auth/dependencies.py @@ -18,6 +18,38 @@ oauth2_scheme = OAuth2PasswordBearer( tokenUrl="api/v1/auth/login", scopes=SCOPE_DESCRIPTIONS ) +optional_oauth2_scheme = OAuth2PasswordBearer( + tokenUrl="api/v1/auth/login", scopes=SCOPE_DESCRIPTIONS, auto_error=False +) + + +async def get_optional_current_user( + db_session: Annotated[AsyncSession, Depends(get_session)], + token: Annotated[str | None, Depends(optional_oauth2_scheme)], + settings: Annotated[Settings, Depends(get_settings)], +) -> User | None: + if token is None: + return None + try: + payload = jwt.decode( + token, + settings.secret_key.get_secret_value(), + algorithms=[settings.token_algorithm], + ) + user_id = payload.get("sub") + scopes = payload.get("scopes") + token_data = TokenData( + user_id=user_id, + scopes=scopes.split(" ") if isinstance(scopes, str) else [], + ) + if token_data.user_id is None or not token_data.scopes: + raise UnauthorizedError(detail="Could not validate credentials") + user = await get_user_by_id(db_session, token_data.user_id) + except (InvalidTokenError, ValidationError): + raise UnauthorizedError(detail="Could not validate credentials") + if user is None or user.deleted_at is not None: + raise UnauthorizedError(detail="Inexistent or inactive user") + return user async def get_current_user_including_deleted( diff --git a/backend/app/auth/oauth/__init__.py b/backend/app/auth/oauth/__init__.py new file mode 100644 index 00000000..c0e158ca --- /dev/null +++ b/backend/app/auth/oauth/__init__.py @@ -0,0 +1 @@ +"""OAuth login integrations.""" diff --git a/backend/app/auth/oauth/routes.py b/backend/app/auth/oauth/routes.py new file mode 100644 index 00000000..e36a2bd8 --- /dev/null +++ b/backend/app/auth/oauth/routes.py @@ -0,0 +1,263 @@ +from __future__ import annotations + +import logging +import secrets +from typing import Annotated +from urllib.parse import urlencode + +import httpx +from fastapi import APIRouter, Depends, Request +from fastapi.responses import RedirectResponse +from itsdangerous import BadSignature, URLSafeTimedSerializer +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.auth import services as auth_services +from app.auth.scopes import DEFAULT_SCOPES, Scope +from app.core.config import AppEnv, get_settings +from app.core.database import get_session +from app.users.models import User + +logger = logging.getLogger(__name__) +router = APIRouter(prefix="/oauth", tags=["auth"]) +STATE_COOKIE = "oauth_state" + + +def _serializer(): + return URLSafeTimedSerializer( + get_settings().secret_key.get_secret_value(), salt="oauth-state" + ) + + +def _credentials(provider: str): + s = get_settings() + if provider == "google": + return ( + s.google_client_id, + s.google_client_secret.get_secret_value() + if s.google_client_secret + else None, + ) + if provider == "github": + return ( + s.github_client_id, + s.github_client_secret.get_secret_value() + if s.github_client_secret + else None, + ) + return None, None + + +@router.get("/{provider}/login") +async def oauth_login(provider: str): + frontend = str(get_settings().frontend_base_url).rstrip("/") + if provider not in ("google", "github"): + return RedirectResponse( + f"{frontend}/semana/login?error=invalid_provider", status_code=303 + ) + + client_id, _ = _credentials(provider) + if not client_id: + return RedirectResponse( + f"{frontend}/semana/login?error=provider_unavailable", status_code=303 + ) + + state = secrets.token_urlsafe(32) + signed = _serializer().dumps({"state": state, "provider": provider}) + callback = f"{str(get_settings().oauth_redirect_base).rstrip('/')}/api/v1/auth/oauth/{provider}/callback" + if provider == "google": + params = { + "client_id": client_id, + "redirect_uri": callback, + "response_type": "code", + "scope": "openid email profile", + "state": state, + "prompt": "select_account", + } + url = "https://accounts.google.com/o/oauth2/v2/auth?" + urlencode(params) + else: + params = { + "client_id": client_id, + "redirect_uri": callback, + "scope": "read:user user:email", + "state": state, + } + url = "https://github.com/login/oauth/authorize?" + urlencode(params) + + redirect = RedirectResponse(url, status_code=302) + redirect.set_cookie( + STATE_COOKIE, + signed, + httponly=True, + secure=get_settings().app_env == AppEnv.production, + samesite="lax", + max_age=600, + ) + return redirect + + +@router.get("/{provider}/callback") +async def oauth_callback( + provider: str, + request: Request, + db: Annotated[AsyncSession, Depends(get_session)], +): + frontend = str(get_settings().frontend_base_url).rstrip("/") + + def fail(code: str): + r = RedirectResponse(f"{frontend}/semana/login?error={code}", status_code=303) + r.delete_cookie(STATE_COOKIE) + return r + + if provider not in ("google", "github"): + return fail("invalid_provider") + + client_id, client_secret = _credentials(provider) + if not client_id or not client_secret: + return fail("provider_unavailable") + + try: + signed = _serializer().loads(request.cookies.get(STATE_COOKIE, ""), max_age=600) + except BadSignature: + logger.warning("OAuth state cookie has bad or expired signature") + return fail("oauth_state") + + if signed.get("provider") != provider or not secrets.compare_digest( + signed.get("state", ""), request.query_params.get("state", "") + ): + logger.warning("OAuth state verification failed for provider: %s", provider) + return fail("oauth_state") + + code = request.query_params.get("code") + if not code or request.query_params.get("error"): + logger.info( + "OAuth authorization denied or cancelled for provider: %s", provider + ) + return fail("oauth_denied") + + callback = f"{str(get_settings().oauth_redirect_base).rstrip('/')}/api/v1/auth/oauth/{provider}/callback" + try: + async with httpx.AsyncClient( + timeout=12, headers={"Accept": "application/json"} + ) as client: + if provider == "google": + token_res = await client.post( + "https://oauth2.googleapis.com/token", + data={ + "code": code, + "client_id": client_id, + "client_secret": client_secret, + "redirect_uri": callback, + "grant_type": "authorization_code", + }, + ) + token_res.raise_for_status() + id_token = token_res.json()["id_token"] + claims_res = await client.get( + "https://oauth2.googleapis.com/tokeninfo", + params={"id_token": id_token}, + ) + claims_res.raise_for_status() + profile = claims_res.json() + if profile.get("aud") != client_id or profile.get("iss") not in ( + "accounts.google.com", + "https://accounts.google.com", + ): + logger.warning("Google ID token validation mismatch (aud/iss)") + return fail("oauth_invalid_profile") + email = profile.get("email", "") + verified = profile.get("email_verified") in (True, "true") + name = profile.get("name") or email.split("@", 1)[0] + subject = str(profile.get("sub", "")) + else: + token_res = await client.post( + "https://github.com/login/oauth/access_token", + headers={"Accept": "application/json"}, + data={ + "code": code, + "client_id": client_id, + "client_secret": client_secret, + "redirect_uri": callback, + }, + ) + token_res.raise_for_status() + access = token_res.json().get("access_token") + if not access: + return fail("oauth_profile") + headers = { + "Authorization": f"Bearer {access}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + } + user_res = await client.get( + "https://api.github.com/user", headers=headers + ) + emails_res = await client.get( + "https://api.github.com/user/emails", headers=headers + ) + user_res.raise_for_status() + emails_res.raise_for_status() + profile = user_res.json() + chosen = next( + ( + e + for e in emails_res.json() + if e.get("primary") and e.get("verified") + ), + None, + ) + email = chosen.get("email", "") if chosen else "" + verified = bool(chosen) + name = ( + profile.get("name") + or profile.get("login") + or email.split("@", 1)[0] + ) + subject = str(profile.get("id", "")) + except (httpx.HTTPError, KeyError, ValueError) as exc: + logger.warning("OAuth exchange error with provider %s: %s", provider, exc) + return fail("oauth_provider_error") + + email = email.strip().lower() + name = " ".join(str(name).split())[:255] + subject = subject.strip() + if not email or not verified or not name: + return fail("oauth_unverified_email" if not verified else "oauth_profile") + if not subject: + return fail("oauth_profile") + + user = await db.scalar( + select(User) + .where(User.oauth_provider == provider, User.oauth_subject == subject) + .with_for_update() + ) + if user is None: + user = await db.scalar( + select(User).where(func.lower(User.email) == email).with_for_update() + ) + if user is not None: + return fail("email_exists") + + user = User( + email=email, + name=name, + password_hash=None, + oauth_provider=provider, + oauth_subject=subject, + is_verified=True, + is_admin=False, + ) + db.add(user) + await db.flush() + elif user.deleted_at is not None: + return fail("email_exists") + + scopes = list(DEFAULT_SCOPES) + if user.is_admin: + scopes.append(Scope.ADMIN) + + refresh = await auth_services.create_refresh_token(db, user.id, scopes) + redirect = RedirectResponse(f"{frontend}/semana/perfil", status_code=303) + redirect.set_cookie(**auth_services.build_refresh_token_cookie(refresh)) + redirect.delete_cookie(STATE_COOKIE) + return redirect diff --git a/backend/app/auth/routes.py b/backend/app/auth/routes.py index 40780368..ab4d3a55 100644 --- a/backend/app/auth/routes.py +++ b/backend/app/auth/routes.py @@ -8,6 +8,7 @@ from app.auth.dependencies import get_current_user from app.auth.schemas import RequestedScopesBody, Token from app.auth.scopes import DEFAULT_SCOPES, KNOWN_SCOPES, Scope +from app.core.config import AppEnv from app.core.database import get_session from app.core.exceptions.app_errors import ForbiddenError, UnauthorizedError from app.users import services as user_services @@ -111,5 +112,8 @@ async def logout( await services.revoke_refresh_token(db_session, token_str) response.delete_cookie( - key="refresh_token", httponly=True, secure=True, samesite="lax" + key="refresh_token", + httponly=True, + secure=services.get_settings().app_env == AppEnv.production, + samesite="lax", ) diff --git a/backend/app/auth/services.py b/backend/app/auth/services.py index 87c1c284..6b16fa49 100644 --- a/backend/app/auth/services.py +++ b/backend/app/auth/services.py @@ -14,7 +14,7 @@ hash_token, verify_password, ) -from app.core.config import get_settings +from app.core.config import AppEnv, get_settings from app.core.exceptions.app_errors import ForbiddenError, UnauthorizedError from app.users.models import User @@ -32,7 +32,7 @@ async def authenticate(db_session: AsyncSession, email: str, password: str): if user is None: return None - if not verify_password(password, user.password_hash): + if user.password_hash is None or not verify_password(password, user.password_hash): return None return user @@ -124,7 +124,7 @@ def build_refresh_token_cookie(refresh_token: str) -> dict: "key": "refresh_token", "value": refresh_token, "httponly": True, - "secure": True, + "secure": get_settings().app_env == AppEnv.production, "samesite": "lax", "max_age": REFRESH_EXPIRE_TIME_SECONDS, } @@ -141,6 +141,8 @@ async def refresh_access_token( scopes = _narrow_scopes(old.scopes.split(" "), requested_scopes) user = await user_services.get_user_by_id(session, old.user_id) + if requested_scopes is None and user.is_admin and Scope.ADMIN not in scopes: + scopes.append(Scope.ADMIN) not_allowed = set(scopes) - get_grantable_scopes(user) if not_allowed: raise ForbiddenError(detail=f"Scopes not allowed: {sorted(not_allowed)}") diff --git a/backend/app/challenges/admin_routes.py b/backend/app/challenges/admin_routes.py index 2b030fee..5e26ebc6 100644 --- a/backend/app/challenges/admin_routes.py +++ b/backend/app/challenges/admin_routes.py @@ -1,7 +1,7 @@ from typing import Annotated from uuid import UUID -from fastapi import APIRouter, Depends, File, Security, UploadFile +from fastapi import APIRouter, Depends, File, Query, Security, UploadFile from sqlalchemy.ext.asyncio import AsyncSession import app.challenges.services.image as cover_image_service @@ -11,9 +11,12 @@ from app.challenges.models.challenge import ChallengeScoringType from app.challenges.services import challenge as challenge_service from app.challenges.services import challenge_participant as participant_service +from app.challenges.services import input as input_service from app.challenges.services import question as question_service from app.core.database import get_session from app.core.exceptions.app_errors import BadRequestError, NotFoundError +from app.core.pagination import Page, PaginationParams +from app.semana import services as semana_service from app.users.models import User router = APIRouter(tags=["admin", "challenges"]) @@ -24,8 +27,31 @@ # ---------- Challenge ---------- +@router.get("", response_model=Page[challenge_schemas.AdminChallengeResponse]) +@router.get( + "/", + response_model=Page[challenge_schemas.AdminChallengeResponse], + include_in_schema=False, +) +async def list_challenges_admin( + session: Annotated[AsyncSession, Depends(get_session)], + _: AdminUser, + limit: int = Query(default=50, ge=1, le=100), + offset: int = Query(default=0, ge=0), +): + return await challenge_service.list_admin_challenges_paginated( + session, PaginationParams(limit=limit, offset=offset) + ) + + @router.post( - "/", response_model=challenge_schemas.AdminChallengeResponse, status_code=201 + "", response_model=challenge_schemas.AdminChallengeResponse, status_code=201 +) +@router.post( + "/", + response_model=challenge_schemas.AdminChallengeResponse, + include_in_schema=False, + status_code=201, ) async def create_challenge_endpoint( session: Annotated[AsyncSession, Depends(get_session)], @@ -34,20 +60,35 @@ async def create_challenge_endpoint( ): """Cria um challenge com título, tipo e (no caso de challenges do tipo quiz) as perguntas dadas""" - if len(data.questions) != 0 and data.scoring_type == ChallengeScoringType.MANUAL: - raise BadRequestError("Manual challenges cannot have questions.") + if ( + data.semana_id is not None + and await semana_service.get_semana(session, data.semana_id) is None + ): + raise NotFoundError("Semana not found.") challenge = await challenge_service.create_challenge( session, title=data.title, + description=data.description, scoring_type=data.scoring_type, + starts_at=data.starts_at, finishes_at=data.finishes_at, + semana_id=data.semana_id, + points_value=data.points_value, + resource_urls=data.resource_urls, ) if data.questions: await question_service.replace_challenge_questions( session, challenge, data.questions ) + elif data.scoring_type == ChallengeScoringType.INPUT: + await input_service.create_input( + session, + challenge, + prompt=data.prompt or "", + input_answer=data.input_answer, + ) return await get_challenge_admin(session, challenge.id, current_user) @@ -65,19 +106,61 @@ async def update_challenge_endpoint( if challenge is None: raise NotFoundError("Challenge not found.") - if data.questions and challenge.scoring_type == ChallengeScoringType.MANUAL: - raise BadRequestError("Manual challenges cannot have questions.") + scoring_type = data.scoring_type or challenge.scoring_type + if data.questions and scoring_type != ChallengeScoringType.QUIZ: + raise BadRequestError("Only quiz challenges can have questions.") + input_data = await input_service.get_input_by_challenge_id(session, challenge.id) + if scoring_type == ChallengeScoringType.INPUT: + if input_data is None and (data.prompt is None or not data.input_answer): + raise BadRequestError("Input challenges require a prompt and an answer.") + if data.input_answer == "": + raise BadRequestError("Input challenges require an expected answer.") + if ( + data.semana_id is not None + and await semana_service.get_semana(session, data.semana_id) is None + ): + raise NotFoundError("Semana not found.") await challenge_service.update_challenge( session, challenge, title=data.title, + description=data.description, + scoring_type=data.scoring_type, + starts_at=data.starts_at, finishes_at=data.finishes_at, + semana_id=data.semana_id, + points_value=data.points_value, + resource_urls=data.resource_urls, ) - if data.questions is not None: - await question_service.replace_challenge_questions( - session, challenge, data.questions - ) + + if scoring_type == ChallengeScoringType.QUIZ: + if input_data is not None: + await input_service.delete_input(session, input_data) + if data.questions is not None: + await question_service.replace_challenge_questions( + session, challenge, data.questions + ) + elif scoring_type == ChallengeScoringType.INPUT: + await question_service.replace_challenge_questions(session, challenge, []) + if input_data is None: + await input_service.create_input( + session, + challenge, + prompt=data.prompt or "", + input_answer=data.input_answer, + ) + else: + await input_service.update_input( + session, + input_data, + prompt=data.prompt, + input_answer=data.input_answer, + ) + else: + if input_data is not None: + await input_service.delete_input(session, input_data) + await question_service.replace_challenge_questions(session, challenge, []) return await get_challenge_admin(session, challenge.id, current_user) @@ -95,6 +178,26 @@ async def delete_challenge_endpoint( await challenge_service.delete_challenge(session, challenge) +@router.get( + "/participants", + response_model=Page[challenge_schemas.AdminChallengeParticipantResponse], +) +async def list_challenge_participants_admin( + session: Annotated[AsyncSession, Depends(get_session)], + _: AdminUser, + limit: int = Query(default=50, ge=1, le=100), + offset: int = Query(default=0, ge=0), + challenge_id: Annotated[UUID | None, Query()] = None, + participant_query: Annotated[str | None, Query(max_length=200)] = None, +): + return await participant_service.list_admin_challenge_participants_paginated( + session, + PaginationParams(limit=limit, offset=offset), + challenge_id=challenge_id, + participant_query=participant_query, + ) + + @router.get("/{challenge_id}", response_model=challenge_schemas.AdminChallengeResponse) async def get_challenge_admin( session: Annotated[AsyncSession, Depends(get_session)], @@ -125,11 +228,22 @@ async def adjust_participant_score( if participant is None: raise NotFoundError("Challenge participant not found.") - return challenge_schemas.ParticipantScoreResponse( + if participant.semana_participant is not None: + await semana_service.add_points( + session, + participant.semana_participant, + data.amount, + source_type="manual_adjustment", + reason="Admin score adjustment", + ) + + response = challenge_schemas.ParticipantScoreResponse( id=participant.id, challenge_id=participant.challenge_id, score=participant.score, ) + await session.commit() + return response # ---------- Challenge Cover Image ----------- diff --git a/backend/app/challenges/exceptions.py b/backend/app/challenges/exceptions.py index 7a8fae73..84e790f4 100644 --- a/backend/app/challenges/exceptions.py +++ b/backend/app/challenges/exceptions.py @@ -21,3 +21,13 @@ def __init__(self) -> None: title="Challenge closed", detail="This challenge has ended and no longer accepts answers or submissions.", ) + + +class ChallengeNotStartedError(AppError): + def __init__(self) -> None: + super().__init__( + status_code=409, + type="challenge_not_started", + title="Challenge not started", + detail="This challenge has not started yet.", + ) diff --git a/backend/app/challenges/models/__init__.py b/backend/app/challenges/models/__init__.py index 9cc75fb4..17b19b51 100644 --- a/backend/app/challenges/models/__init__.py +++ b/backend/app/challenges/models/__init__.py @@ -1,6 +1,7 @@ from .answer import Answer from .challenge import Challenge from .challenge_participant import ChallengeParticipant +from .input import Input from .question import Question -__all__ = ["Answer", "Challenge", "ChallengeParticipant", "Question"] +__all__ = ["Answer", "Challenge", "ChallengeParticipant", "Input", "Question"] diff --git a/backend/app/challenges/models/challenge.py b/backend/app/challenges/models/challenge.py index 3bfc8381..7f2dc5fe 100644 --- a/backend/app/challenges/models/challenge.py +++ b/backend/app/challenges/models/challenge.py @@ -4,7 +4,7 @@ from enum import StrEnum from typing import TYPE_CHECKING -from sqlalchemy import DateTime, String, text +from sqlalchemy import JSON, DateTime, ForeignKey, String, Text, text from sqlalchemy import Enum as SQLEnum from sqlalchemy.orm import Mapped, mapped_column, relationship @@ -12,11 +12,14 @@ from app.core.models import Base if TYPE_CHECKING: + from app.challenges.models.input import Input from app.challenges.models.question import Question + from app.semana.models import Semana class ChallengeScoringType(StrEnum): QUIZ = "quiz" + INPUT = "input" MANUAL = "manual" @@ -24,12 +27,19 @@ class Challenge(Base, UUIDPKMixin, TimestampsMixin): __tablename__ = "challenges" title: Mapped[str] = mapped_column(String(255)) - + description: Mapped[str] = mapped_column(Text, default="") + points_value: Mapped[int] = mapped_column(default=0) scoring_type: Mapped[ChallengeScoringType] = mapped_column( SQLEnum(ChallengeScoringType, native_enum=False, length=20), default=ChallengeScoringType.QUIZ, nullable=False, ) + starts_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), + default=lambda: datetime.now(UTC), + server_default=text("now()"), + nullable=False, + ) finishes_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), @@ -40,5 +50,14 @@ class Challenge(Base, UUIDPKMixin, TimestampsMixin): ) image_path: Mapped[str | None] = mapped_column(String(512), nullable=True) + resource_urls: Mapped[list[str]] = mapped_column(JSON, default=list) + semana_id: Mapped[int | None] = mapped_column( + ForeignKey("semana_event.id"), nullable=True + ) + + input: Mapped[Input | None] = relationship( + "Input", back_populates="challenge", cascade="all, delete-orphan", uselist=False + ) questions: Mapped[list[Question]] = relationship(back_populates="challenge") + semana: Mapped[Semana | None] = relationship(back_populates="challenges") diff --git a/backend/app/challenges/models/challenge_participant.py b/backend/app/challenges/models/challenge_participant.py index 03a594f2..60ec0aa8 100644 --- a/backend/app/challenges/models/challenge_participant.py +++ b/backend/app/challenges/models/challenge_participant.py @@ -4,7 +4,7 @@ from datetime import datetime from typing import TYPE_CHECKING -from sqlalchemy import DateTime, ForeignKey, UniqueConstraint +from sqlalchemy import DateTime, ForeignKey, String, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column, relationship from app.core.mixins import TimestampsMixin, UUIDPKMixin @@ -14,6 +14,8 @@ from .challenge import Challenge if TYPE_CHECKING: + from app.semana.models import SemanaParticipant + from .answer import Answer @@ -26,8 +28,14 @@ class ChallengeParticipant(Base, UUIDPKMixin, TimestampsMixin): ForeignKey("users.id", ondelete="CASCADE") ) challenge_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("challenges.id")) + semana_participant_id: Mapped[uuid.UUID | None] = mapped_column( + ForeignKey("semana_participants.id"), nullable=True + ) user: Mapped[User] = relationship() challenge: Mapped[Challenge] = relationship() + semana_participant: Mapped[SemanaParticipant | None] = relationship( + back_populates="challenge_attempts" + ) score: Mapped[int] = mapped_column(default=0) answers: Mapped[list[Answer]] = relationship( @@ -37,6 +45,7 @@ class ChallengeParticipant(Base, UUIDPKMixin, TimestampsMixin): submitted_at: Mapped[datetime | None] = mapped_column( DateTime(timezone=True), nullable=True ) + submission: Mapped[str | None] = mapped_column(String(255), nullable=True) __table_args__ = ( UniqueConstraint( diff --git a/backend/app/challenges/models/input.py b/backend/app/challenges/models/input.py new file mode 100644 index 00000000..87306063 --- /dev/null +++ b/backend/app/challenges/models/input.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +import uuid +from typing import TYPE_CHECKING + +from sqlalchemy import ForeignKey, String +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.core.mixins import UUIDPKMixin +from app.core.models import Base + +if TYPE_CHECKING: + from app.challenges.models.challenge import Challenge + + +class Input(Base, UUIDPKMixin): + __tablename__ = "inputs" + + prompt: Mapped[str] = mapped_column(String(5000)) + input_answer: Mapped[str | None] = mapped_column(String(255), nullable=True) + + challenge_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("challenges.id", ondelete="CASCADE"), unique=True + ) + challenge: Mapped[Challenge] = relationship("Challenge", back_populates="input") diff --git a/backend/app/challenges/models/question.py b/backend/app/challenges/models/question.py index a3085c97..a712e6c5 100644 --- a/backend/app/challenges/models/question.py +++ b/backend/app/challenges/models/question.py @@ -18,7 +18,6 @@ class Question(Base, UUIDPKMixin): prompt: Mapped[str] = mapped_column(String(5000)) answer: Mapped[str] = mapped_column(String(255)) - points_value: Mapped[int] = mapped_column(default=0) challenge_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("challenges.id")) challenge: Mapped[Challenge] = relationship(back_populates="questions") diff --git a/backend/app/challenges/routes.py b/backend/app/challenges/routes.py index b3a4ea22..fedd9926 100644 --- a/backend/app/challenges/routes.py +++ b/backend/app/challenges/routes.py @@ -1,3 +1,4 @@ +from datetime import UTC, datetime from typing import Annotated from uuid import UUID @@ -14,6 +15,7 @@ from app.core.database import get_session from app.core.exceptions.app_errors import BadRequestError, NotFoundError from app.core.pagination import Page, PaginationParams +from app.semana import services as semana_service from app.users.models import User router = APIRouter(tags=["challenges"]) @@ -32,6 +34,9 @@ async def join_challenge( challenge = await challenge_service.get_challenge_by_id(session, challenge_id) if challenge is None: raise NotFoundError("Challenge with given ID not found.") + if challenge.semana_id is None: + raise BadRequestError("Challenge must belong to a Semana.") + challenge_service.ensure_challenge_started(challenge.starts_at) current_participant = await participant_service.get_challenge_participant( session, current_user.id, challenge_id, for_update=True @@ -39,23 +44,36 @@ async def join_challenge( if current_participant is not None: raise BadRequestError("You are subscribed to this challenge already.") + semana = await semana_service.get_semana(session, challenge.semana_id) + if semana is None: + raise NotFoundError("Semana not found.") + semana_participant = await semana_service.get_or_create_participant( + session, semana, current_user + ) + semana_participant_id = semana_participant.id + new_participant = await participant_service.create_challenge_participant( - session, current_user.id, challenge_id + session, + current_user.id, + challenge_id, + semana_participant_id=semana_participant_id, ) await session.refresh(new_participant) result = await participant_service.get_challenge_participant_by_id( session, new_participant.id ) - if result is None or result.user.username is None: - raise BadRequestError("Username assignment failed.") + if result is None or result.semana_participant is None: + raise BadRequestError("Nickname assignment failed.") return challenge_schemas.ParticipantResponse( id=result.id, user_id=result.user_id, challenge_id=result.challenge_id, name=result.user.name, - nickname=result.user.username.nickname, + nickname=( + result.semana_participant.nickname if result.semana_participant else "" + ), score=result.score, submitted_at=result.submitted_at, ) @@ -78,12 +96,68 @@ async def save_answer( if participant is None: raise BadRequestError("You are not subscribed to this challenge.") + if participant.submitted_at is not None: + raise BadRequestError("Challenge submission is already complete.") await answer_service.upsert_answer( session, participant.id, data.question_id, data.answer ) +@router.post( + "/{challenge_id}/input", response_model=challenge_schemas.SubmissionResponse +) +async def submit_input( + session: Annotated[AsyncSession, Depends(get_session)], + challenge_id: UUID, + data: challenge_schemas.InputSubmission, + current_user: Annotated[ + User, Security(get_current_user, scopes=[Scope.PROFILE, Scope.EMAIL]) + ], +): + participant = await participant_service.get_challenge_participant( + session, current_user.id, challenge_id, for_update=True + ) + if participant is None: + raise BadRequestError("You are not subscribed to this challenge.") + + challenge = await challenge_service.get_challenge_by_id(session, challenge_id) + if challenge is None: + raise NotFoundError("Challenge not found.") + if challenge.scoring_type != ChallengeScoringType.INPUT: + raise BadRequestError("Challenge does not accept input submissions.") + challenge_service.ensure_challenge_started(challenge.starts_at) + if participant.submitted_at is not None: + return challenge_schemas.SubmissionResponse( + submitted_at=participant.submitted_at, score=participant.score + ) + challenge_service.ensure_challenge_open(challenge.finishes_at) + + participant.submission = data.answer + input_data = challenge.input + is_correct = ( + input_data is not None + and input_data.input_answer is not None + and data.answer.strip().lower() == input_data.input_answer.strip().lower() + ) + participant.score = challenge.points_value if is_correct else 0 + if is_correct: + participant.submitted_at = datetime.now(UTC) + await session.flush() + if is_correct and participant.semana_participant is not None: + await semana_service.add_points( + session, + participant.semana_participant, + participant.score, + source_type="challenge", + source_id=participant.id, + reason=challenge.title, + ) + return challenge_schemas.SubmissionResponse( + submitted_at=participant.submitted_at, score=participant.score + ) + + @router.post("/{challenge_id}/answer/all", status_code=204) async def save_many_answers( session: Annotated[AsyncSession, Depends(get_session)], @@ -110,6 +184,8 @@ async def save_many_answers( if participant is None: raise BadRequestError("You are not subscribed to this challenge.") + if participant.submitted_at is not None: + raise BadRequestError("Challenge submission is already complete.") for answer_body in data: await answer_service.upsert_answer( @@ -145,6 +221,7 @@ async def submit_challenge( raise NotFoundError("Challenge not found") if challenge.scoring_type != ChallengeScoringType.QUIZ: raise BadRequestError("Manual challenges cannot be submitted by participants.") + challenge_service.ensure_challenge_started(challenge.starts_at) # idempotência: se o usuário já submeteu antes, retorna o valor anterior if participant.submitted_at is not None: @@ -153,7 +230,19 @@ async def submit_challenge( ) challenge_service.ensure_challenge_open(challenge.finishes_at) - score = await challenge_service.process_submission(session, participant) + score = await challenge_service.process_submission(session, participant, challenge) + if ( + participant.submitted_at is not None + and participant.semana_participant is not None + ): + await semana_service.add_points( + session, + participant.semana_participant, + score, + source_type="challenge", + source_id=participant.id, + reason=challenge.title, + ) return challenge_schemas.SubmissionResponse( submitted_at=participant.submitted_at, score=score @@ -178,12 +267,12 @@ async def get_challenge( ) = await challenge_service.get_challenge_with_context( session, challenge_id, current_user.id ) + challenge_service.ensure_challenge_open(challenge.finishes_at) question_responses = [ challenge_schemas.QuestionResponse( id=q.id, prompt=q.prompt, - points_value=q.points_value, current_answer=current_answers_by_qid.get(q.id), ) for q in questions @@ -192,12 +281,17 @@ async def get_challenge( return challenge_schemas.ChallengeResponse( id=challenge.id, title=challenge.title, + description=challenge.description, + prompt=challenge.input.prompt if challenge.input is not None else "", scoring_type=challenge.scoring_type, + starts_at=challenge.starts_at, image_path=challenge.image_path, finishes_at=challenge.finishes_at, + resource_urls=challenge.resource_urls, questions=question_responses, is_participant=participant is not None, submitted_at=participant.submitted_at if participant else None, + score=participant.score if participant else None, ) @@ -212,6 +306,10 @@ async def get_ranking( Obtém o ranking (Top 10) de um challenge """ + challenge = await challenge_service.get_challenge_by_id(session, challenge_id) + if challenge is None or challenge.starts_at > datetime.now(UTC): + raise NotFoundError("Challenge not found.") + participants = await participant_service.get_challenge_ranking( session, challenge_id ) @@ -222,12 +320,17 @@ async def get_ranking( user_id=p.user_id, score=p.score, name=p.user.name, - nickname=p.user.username.nickname if p.user.username else "", + nickname=(p.semana_participant.nickname if p.semana_participant else ""), ) for p in participants ] +@router.get( + "", + response_model=Page[challenge_schemas.ChallengePublicResponse], + include_in_schema=False, +) @router.get("/", response_model=Page[challenge_schemas.ChallengePublicResponse]) async def list_challenges( session: Annotated[AsyncSession, Depends(get_session)], diff --git a/backend/app/challenges/schemas.py b/backend/app/challenges/schemas.py index 90d66824..7d6b9569 100644 --- a/backend/app/challenges/schemas.py +++ b/backend/app/challenges/schemas.py @@ -3,7 +3,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator -from app.challenges.models.challenge import ChallengeScoringType +from app.challenges.models.challenge import Challenge, ChallengeScoringType from app.challenges.services.image import build_challenge_image_url @@ -13,16 +13,19 @@ class AnswerBody(BaseModel): class SubmissionResponse(BaseModel): - submitted_at: datetime + submitted_at: datetime | None score: int +class InputSubmission(BaseModel): + answer: str + + class QuestionResponse(BaseModel): model_config = ConfigDict(from_attributes=True) id: UUID prompt: str - points_value: int current_answer: str | None = None @@ -48,25 +51,50 @@ class ParticipantScoreResponse(BaseModel): score: int +class AdminChallengeParticipantResponse(BaseModel): + id: UUID + user_id: UUID + user_name: str + user_email: str + challenge_id: UUID + challenge_title: str + score: int + submitted_at: datetime | None + + class QuestionCreate(BaseModel): prompt: str answer: str - points_value: int = 0 class QuestionUpdate(BaseModel): prompt: str | None = None answer: str | None = None - points_value: int | None = None class ChallengeCreate(BaseModel): title: str + description: str = "" + prompt: str | None = None scoring_type: ChallengeScoringType = ChallengeScoringType.QUIZ + starts_at: datetime | None = None finishes_at: datetime | None = None + semana_id: int | None = None + points_value: int = 0 + input_answer: str | None = None + resource_urls: list[str] = Field(default_factory=list) questions: list[QuestionCreate] = Field(default_factory=list) + @model_validator(mode="after") + def validate_scoring_data(self): + if self.scoring_type == ChallengeScoringType.INPUT: + if self.prompt is None or not self.input_answer: + raise ValueError("Input challenges require a prompt and an answer.") + elif self.scoring_type != ChallengeScoringType.QUIZ and self.questions: + raise ValueError("Only quiz challenges can have questions.") + return self + @field_validator("finishes_at") @classmethod def validate_finishes_at_timezone(cls, value: datetime | None) -> datetime | None: @@ -74,11 +102,26 @@ def validate_finishes_at_timezone(cls, value: datetime | None) -> datetime | Non raise ValueError("finishes_at must include a timezone.") return value + @field_validator("starts_at") + @classmethod + def validate_starts_at_timezone(cls, value: datetime | None) -> datetime | None: + if value is not None and value.utcoffset() is None: + raise ValueError("starts_at must include a timezone.") + return value + class ChallengeUpdate(BaseModel): title: str | None = None + description: str | None = None + scoring_type: ChallengeScoringType | None = None + prompt: str | None = None questions: list[QuestionCreate] | None = None + starts_at: datetime | None = None finishes_at: datetime | None = None + semana_id: int | None = None + points_value: int | None = None + input_answer: str | None = None + resource_urls: list[str] | None = None @field_validator("finishes_at") @classmethod @@ -87,6 +130,13 @@ def validate_finishes_at_timezone(cls, value: datetime | None) -> datetime | Non raise ValueError("finishes_at must include a timezone.") return value + @field_validator("starts_at") + @classmethod + def validate_starts_at_timezone(cls, value: datetime | None) -> datetime | None: + if value is not None and value.utcoffset() is None: + raise ValueError("starts_at must include a timezone.") + return value + class RankingEntry(BaseModel): model_config = ConfigDict(from_attributes=True) @@ -106,7 +156,6 @@ class AdminQuestionResponse(BaseModel): id: UUID prompt: str answer: str - points_value: int class ChallengeImageMixin(BaseModel): @@ -119,6 +168,19 @@ class ChallengeImageMixin(BaseModel): image_path: str | None = Field(default=None, exclude=True) image_url: str | None = None + @model_validator(mode="before") + @classmethod + def _include_input_data(cls, value): + if isinstance(value, Challenge): + data = value.__dict__.copy() + input_data = value.input + data["prompt"] = input_data.prompt if input_data is not None else "" + data["input_answer"] = ( + input_data.input_answer if input_data is not None else None + ) + return data + return value + @model_validator(mode="after") def _fill_image_url(self): if self.image_url is None: @@ -131,11 +193,16 @@ class ChallengeResponse(ChallengeImageMixin): id: UUID title: str + description: str + prompt: str scoring_type: ChallengeScoringType + starts_at: datetime finishes_at: datetime + resource_urls: list[str] = Field(default_factory=list) questions: list[QuestionResponse] = Field(default_factory=list) is_participant: bool = False submitted_at: datetime | None = None + score: int | None = None class ChallengePublicResponse(ChallengeImageMixin): @@ -143,8 +210,12 @@ class ChallengePublicResponse(ChallengeImageMixin): id: UUID title: str + description: str + prompt: str scoring_type: ChallengeScoringType + starts_at: datetime finishes_at: datetime + resource_urls: list[str] = Field(default_factory=list) class AdminChallengeResponse(ChallengeImageMixin): @@ -154,6 +225,13 @@ class AdminChallengeResponse(ChallengeImageMixin): id: UUID title: str + description: str + prompt: str scoring_type: ChallengeScoringType + starts_at: datetime finishes_at: datetime + semana_id: int | None = None + points_value: int = 0 + input_answer: str | None = None + resource_urls: list[str] = Field(default_factory=list) questions: list[AdminQuestionResponse] = Field(default_factory=list) diff --git a/backend/app/challenges/services/answer.py b/backend/app/challenges/services/answer.py index 5d02fe05..7b984f89 100644 --- a/backend/app/challenges/services/answer.py +++ b/backend/app/challenges/services/answer.py @@ -47,7 +47,7 @@ async def upsert_answer( ) -> Answer: result = await session.execute( - select(Question, Challenge.finishes_at) + select(Question, Challenge.starts_at, Challenge.finishes_at) .join(Challenge, Challenge.id == Question.challenge_id) .join(ChallengeParticipant, ChallengeParticipant.challenge_id == Challenge.id) .where( @@ -62,7 +62,8 @@ async def upsert_answer( if question_and_deadline is None: raise NotFoundError("Could not find question with given ID.") - question, finishes_at = question_and_deadline + question, starts_at, finishes_at = question_and_deadline + challenge_service.ensure_challenge_started(starts_at) challenge_service.ensure_challenge_open(finishes_at) is_correct = content.strip().lower() == question.answer.strip().lower() diff --git a/backend/app/challenges/services/challenge.py b/backend/app/challenges/services/challenge.py index 69ce7755..9c01fcca 100644 --- a/backend/app/challenges/services/challenge.py +++ b/backend/app/challenges/services/challenge.py @@ -20,6 +20,11 @@ def ensure_challenge_open(finishes_at: datetime) -> None: raise challenge_exceptions.ChallengeClosedError() +def ensure_challenge_started(starts_at: datetime) -> None: + if starts_at > datetime.now(UTC): + raise challenge_exceptions.ChallengeNotStartedError() + + async def get_challenge_with_context( session: AsyncSession, challenge_id: uuid.UUID, @@ -34,7 +39,8 @@ async def get_challenge_with_context( select(Challenge) .where(Challenge.id == challenge_id) .where(Challenge.deleted_at.is_(None)) - .options(selectinload(Challenge.questions)) + .where(Challenge.starts_at <= datetime.now(UTC)) + .options(selectinload(Challenge.questions), selectinload(Challenge.input)) ) if challenge is None: @@ -62,21 +68,31 @@ async def get_challenge_with_context( async def process_submission( - session: AsyncSession, participant: ChallengeParticipant + session: AsyncSession, participant: ChallengeParticipant, challenge: Challenge ) -> int: - """Processa a pontuação das respostas de challenge que sea do tipo "quiz" """ + """Scores correct quiz answers proportionally against the challenge total.""" - rows = ( - await session.execute( - select(Answer.is_correct, Question.points_value) - .join(Question, Question.id == Answer.question_id) - .where(Answer.participant_id == participant.id, Answer.deleted_at.is_(None)) + correct_count = await session.scalar( + select(func.count(Answer.id)) + .join(Question, Question.id == Answer.question_id) + .where( + Answer.participant_id == participant.id, + Answer.deleted_at.is_(None), + Answer.is_correct.is_(True), ) - ).all() + ) - score = sum(row[1] for row in rows if row[0]) + question_count = await session.scalar( + select(func.count(Question.id)).where(Question.challenge_id == challenge.id) + ) + score = ( + challenge.points_value * (correct_count or 0) // (question_count or 1) + if question_count + else 0 + ) - participant.submitted_at = datetime.now(UTC) + is_complete = bool(question_count) and (correct_count or 0) == question_count + participant.submitted_at = datetime.now(UTC) if is_complete else None participant.score = score await session.flush() @@ -93,7 +109,7 @@ async def get_challenge_by_id( Challenge.id == challenge_id, Challenge.deleted_at.is_(None), ) - .options(selectinload(Challenge.questions)) + .options(selectinload(Challenge.questions), selectinload(Challenge.input)) ) return result.scalar_one_or_none() @@ -102,14 +118,17 @@ async def list_challenges_paginated( session: AsyncSession, pagination: PaginationParams, ) -> Page[challenge_schemas.ChallengePublicResponse]: # ← tipo correto - total = await session.scalar( - select(func.count(Challenge.id)).where(Challenge.deleted_at.is_(None)) + conditions = ( + Challenge.deleted_at.is_(None), + Challenge.starts_at <= datetime.now(UTC), ) + total = await session.scalar(select(func.count(Challenge.id)).where(*conditions)) rows = ( await session.scalars( select(Challenge) - .where(Challenge.deleted_at.is_(None)) + .where(*conditions) + .options(selectinload(Challenge.input)) .order_by(Challenge.created_at.desc(), Challenge.id) .limit(pagination.limit) .offset(pagination.offset) @@ -126,15 +145,56 @@ async def list_challenges_paginated( ) +async def list_admin_challenges_paginated( + session: AsyncSession, + pagination: PaginationParams, +) -> Page[challenge_schemas.AdminChallengeResponse]: + total = await session.scalar( + select(func.count(Challenge.id)).where(Challenge.deleted_at.is_(None)) + ) + rows = ( + await session.scalars( + select(Challenge) + .where(Challenge.deleted_at.is_(None)) + .options(selectinload(Challenge.questions), selectinload(Challenge.input)) + .order_by(Challenge.created_at.desc(), Challenge.id) + .limit(pagination.limit) + .offset(pagination.offset) + ) + ).all() + return Page[challenge_schemas.AdminChallengeResponse]( + items=[ + challenge_schemas.AdminChallengeResponse.model_validate(c) for c in rows + ], + total=total or 0, + limit=pagination.limit, + offset=pagination.offset, + ) + + async def create_challenge( session: AsyncSession, title: str, + description: str = "", scoring_type: ChallengeScoringType = ChallengeScoringType.QUIZ, + starts_at: datetime | None = None, finishes_at: datetime | None = None, + semana_id: int | None = None, + points_value: int = 0, + resource_urls: list[str] | None = None, ) -> Challenge: - challenge = Challenge(title=title, scoring_type=scoring_type) + challenge = Challenge( + title=title, + description=description, + points_value=points_value, + scoring_type=scoring_type, + semana_id=semana_id, + resource_urls=resource_urls or [], + ) if finishes_at is not None: challenge.finishes_at = finishes_at + if starts_at is not None: + challenge.starts_at = starts_at session.add(challenge) await session.flush() return challenge @@ -145,12 +205,30 @@ async def update_challenge( challenge: Challenge, *, title: str | None = None, + description: str | None = None, + scoring_type: ChallengeScoringType | None = None, + starts_at: datetime | None = None, finishes_at: datetime | None = None, + semana_id: int | None = None, + points_value: int | None = None, + resource_urls: list[str] | None = None, ) -> Challenge: if title is not None: challenge.title = title + if description is not None: + challenge.description = description + if scoring_type is not None: + challenge.scoring_type = scoring_type + if points_value is not None: + challenge.points_value = points_value if finishes_at is not None: challenge.finishes_at = finishes_at + if starts_at is not None: + challenge.starts_at = starts_at + if semana_id is not None: + challenge.semana_id = semana_id + if resource_urls is not None: + challenge.resource_urls = resource_urls await session.flush() return challenge diff --git a/backend/app/challenges/services/challenge_participant.py b/backend/app/challenges/services/challenge_participant.py index d6fd6504..712c7d5d 100644 --- a/backend/app/challenges/services/challenge_participant.py +++ b/backend/app/challenges/services/challenge_participant.py @@ -1,13 +1,76 @@ import uuid -from sqlalchemy import desc, select +from sqlalchemy import desc, func, select from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import selectinload +from app.challenges import schemas as challenge_schemas +from app.challenges.models.challenge import Challenge from app.challenges.models.challenge_participant import ChallengeParticipant +from app.core.pagination import Page, PaginationParams from app.users.models import User +async def list_admin_challenge_participants_paginated( + session: AsyncSession, + pagination: PaginationParams, + challenge_id: uuid.UUID | None = None, + participant_query: str | None = None, +) -> Page[challenge_schemas.AdminChallengeParticipantResponse]: + conditions = [ + ChallengeParticipant.deleted_at.is_(None), + Challenge.deleted_at.is_(None), + User.deleted_at.is_(None), + ] + if challenge_id is not None: + conditions.append(ChallengeParticipant.challenge_id == challenge_id) + if participant_query and participant_query.strip(): + search = f"%{participant_query.strip()}%" + conditions.append(User.name.ilike(search) | User.email.ilike(search)) + + total = await session.scalar( + select(func.count(ChallengeParticipant.id)) + .join(Challenge, Challenge.id == ChallengeParticipant.challenge_id) + .join(User, User.id == ChallengeParticipant.user_id) + .where(*conditions) + ) + rows = ( + await session.execute( + select(ChallengeParticipant, User.name, User.email, Challenge.title) + .join(Challenge, Challenge.id == ChallengeParticipant.challenge_id) + .join(User, User.id == ChallengeParticipant.user_id) + .where(*conditions) + .order_by( + Challenge.title.asc(), + ChallengeParticipant.score.desc(), + User.name.asc(), + ChallengeParticipant.id, + ) + .limit(pagination.limit) + .offset(pagination.offset) + ) + ).all() + + return Page[challenge_schemas.AdminChallengeParticipantResponse]( + items=[ + challenge_schemas.AdminChallengeParticipantResponse( + id=participant.id, + user_id=participant.user_id, + user_name=user_name, + user_email=user_email, + challenge_id=participant.challenge_id, + challenge_title=challenge_title, + score=participant.score, + submitted_at=participant.submitted_at, + ) + for participant, user_name, user_email, challenge_title in rows + ], + total=total or 0, + limit=pagination.limit, + offset=pagination.offset, + ) + + async def get_challenge_ranking( session: AsyncSession, challenge_id: uuid.UUID ) -> list[ChallengeParticipant]: @@ -17,7 +80,10 @@ async def get_challenge_ranking( ChallengeParticipant.challenge_id == challenge_id, ChallengeParticipant.deleted_at.is_(None), ) - .options(selectinload(ChallengeParticipant.user).selectinload(User.username)) + .options( + selectinload(ChallengeParticipant.user), + selectinload(ChallengeParticipant.semana_participant), + ) .order_by(desc(ChallengeParticipant.score)) .limit(10) ) @@ -34,7 +100,10 @@ async def get_challenge_participant_by_id( ChallengeParticipant.id == participant_id, ChallengeParticipant.deleted_at.is_(None), ) - .options(selectinload(ChallengeParticipant.user).selectinload(User.username)) + .options( + selectinload(ChallengeParticipant.user), + selectinload(ChallengeParticipant.semana_participant), + ) ) return result.scalar_one_or_none() @@ -53,7 +122,10 @@ async def get_challenge_participant( ChallengeParticipant.challenge_id == challenge_id, ChallengeParticipant.deleted_at.is_(None), ) - .options(selectinload(ChallengeParticipant.user).selectinload(User.username)) + .options( + selectinload(ChallengeParticipant.user), + selectinload(ChallengeParticipant.semana_participant), + ) ) if for_update: @@ -88,11 +160,13 @@ async def create_challenge_participant( user_id: uuid.UUID, challenge_id: uuid.UUID, score: int = 0, + semana_participant_id: uuid.UUID | None = None, ) -> ChallengeParticipant: participant = ChallengeParticipant( user_id=user_id, challenge_id=challenge_id, score=score, + semana_participant_id=semana_participant_id, ) session.add(participant) await session.flush() @@ -124,6 +198,7 @@ async def add_challenge_participant_score( ChallengeParticipant.challenge_id == challenge_id, ChallengeParticipant.deleted_at.is_(None), ) + .options(selectinload(ChallengeParticipant.semana_participant)) .with_for_update() ) if participant is None: diff --git a/backend/app/challenges/services/input.py b/backend/app/challenges/services/input.py new file mode 100644 index 00000000..c93edc7a --- /dev/null +++ b/backend/app/challenges/services/input.py @@ -0,0 +1,56 @@ +import uuid + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.challenges.models.challenge import Challenge +from app.challenges.models.input import Input + + +async def get_input_by_challenge_id( + session: AsyncSession, challenge_id: uuid.UUID +) -> Input | None: + return await session.scalar(select(Input).where(Input.challenge_id == challenge_id)) + + +async def list_inputs(session: AsyncSession) -> list[Input]: + result = await session.scalars(select(Input)) + return list(result.all()) + + +async def create_input( + session: AsyncSession, + challenge: Challenge, + prompt: str, + input_answer: str | None = None, +) -> Input: + input_data = Input( + prompt=prompt, + input_answer=input_answer, + challenge_id=challenge.id, + ) + challenge.input = input_data + session.add(input_data) + await session.flush() + return input_data + + +async def update_input( + session: AsyncSession, + input_data: Input, + *, + prompt: str | None = None, + input_answer: str | None = None, +) -> Input: + if prompt is not None: + input_data.prompt = prompt + if input_answer is not None: + input_data.input_answer = input_answer + + await session.flush() + return input_data + + +async def delete_input(session: AsyncSession, input_data: Input) -> None: + input_data.challenge.input = None + await session.flush() diff --git a/backend/app/challenges/services/question.py b/backend/app/challenges/services/question.py index b8b17ac4..cec7cf3b 100644 --- a/backend/app/challenges/services/question.py +++ b/backend/app/challenges/services/question.py @@ -39,14 +39,12 @@ async def create_question( prompt: str, answer: str, challenge_id: uuid.UUID, - points_value: int = 0, ) -> Question: question = Question( prompt=prompt, answer=answer, challenge_id=challenge_id, - points_value=points_value, ) session.add(question) @@ -67,7 +65,6 @@ async def replace_challenge_questions( Question( prompt=question.prompt, answer=question.answer, - points_value=question.points_value, challenge_id=challenge.id, ) for question in questions @@ -83,15 +80,11 @@ async def update_question( question: Question, prompt: str | None = None, answer: str | None = None, - points_value: int | None = None, ) -> Question: if prompt is not None: question.prompt = prompt if answer is not None: question.answer = answer - if points_value is not None: - question.points_value = points_value - await session.flush() return question diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 4ca2a73f..21f7a6b5 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -83,6 +83,13 @@ class Settings(BaseSettings): description="Identificador do cliente que consome o id_token (claim 'aud')", ) + google_client_id: str | None = None + google_client_secret: SecretStr | None = None + github_client_id: str | None = None + github_client_secret: SecretStr | None = None + oauth_redirect_base: AnyHttpUrl = Field(default="http://localhost:8000") + frontend_base_url: AnyHttpUrl = Field(default="http://localhost:3000") + media_root: Path = Field( # o default aqui assume /backend/app/core/config.py como caminho deste arquivo # se isso mudar, é bom atualizar diff --git a/backend/app/core/rate_limit.py b/backend/app/core/rate_limit.py new file mode 100644 index 00000000..474d1642 --- /dev/null +++ b/backend/app/core/rate_limit.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +import time +from collections import defaultdict +from collections.abc import Callable +from re import fullmatch +from typing import ClassVar + +from fastapi import Request +from fastapi.responses import JSONResponse + +RateLimit = tuple[int, int] + +LIMITS: dict[tuple[str, str], RateLimit] = { + ("POST", "/api/v1/auth/login"): (5, 60), + ("POST", "/api/v1/auth/refresh"): (20, 60), + ("POST", "/api/v1/user"): (3, 60 * 60), +} +ATTENDANCE_PATH = r"/api/v1/semanas/\d+/atividades/registrar/\d{4}" +ATTENDANCE_LIMIT: RateLimit = (10, 60) + + +class RateLimitMiddleware: + # ponytail: process-local limits; use Redis when running multiple workers/instances. + _instances: ClassVar[list[RateLimitMiddleware]] = [] + + def __init__(self, app: Callable): + self.app = app + self.requests: defaultdict[tuple[str, str, str], list[float]] = defaultdict( + list + ) + RateLimitMiddleware._instances.append(self) + + @classmethod + def reset_all(cls) -> None: + for instance in cls._instances: + instance.requests.clear() + + async def __call__(self, scope, receive, send): + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + request = Request(scope, receive) + path = request.url.path.rstrip("/") or "/" + limit = LIMITS.get((request.method, path)) + bucket = path + if request.method == "POST" and fullmatch(ATTENDANCE_PATH, path): + limit = ATTENDANCE_LIMIT + bucket = "/api/v1/semanas/{semana_id}/atividades/registrar" + if limit is None: + await self.app(scope, receive, send) + return + + max_requests, window_seconds = limit + now = time.monotonic() + key = ( + request.client.host if request.client else "unknown", + request.method, + bucket, + ) + timestamps = self.requests[key] + timestamps[:] = [ + timestamp for timestamp in timestamps if now - timestamp < window_seconds + ] + + if len(timestamps) >= max_requests: + retry_after = max(1, int(window_seconds - (now - timestamps[0]))) + response = JSONResponse( + {"detail": "Too many requests. Try again later."}, + status_code=429, + headers={ + "Retry-After": str(retry_after), + "X-RateLimit-Limit": str(max_requests), + "X-RateLimit-Remaining": "0", + }, + ) + await response(scope, receive, send) + return + + timestamps.append(now) + await self.app(scope, receive, send) diff --git a/backend/app/main.py b/backend/app/main.py index 7ca67176..56554d9b 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -1,8 +1,13 @@ from contextlib import asynccontextmanager from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles +from app.atividade.routes import admin_router as atividade_admin_router +from app.atividade.routes import attendance_router as atividade_attendance_router +from app.atividade.routes import router as atividade_router +from app.auth.oauth.routes import router as oauth_router from app.auth.routes import router as auth_router from app.challenges.admin_routes import router as challenge_admin_router from app.challenges.routes import router as challenge_router @@ -10,6 +15,9 @@ from app.core.exceptions.app_errors import AppError from app.core.exceptions.handlers import app_error_handler, exception_handler from app.core.health import router as health_router +from app.core.rate_limit import RateLimitMiddleware +from app.semana.routes import admin_router as semana_admin_router +from app.semana.routes import router as semana_router from app.users.admin_router import router as user_admin_router from app.users.routes import router as user_router @@ -28,6 +36,18 @@ async def lifespan(app: FastAPI): app = FastAPI(title="SymComp API", version="0.1.0", lifespan=lifespan) +_settings = config.get_settings() + +if _settings.cors_origins: + app.add_middleware( + CORSMiddleware, + allow_origins=[str(origin).rstrip("/") for origin in _settings.cors_origins], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + +app.add_middleware(RateLimitMiddleware) # --------------------------------------------------------------------------- # Rotas da API @@ -35,7 +55,13 @@ async def lifespan(app: FastAPI): app.include_router(health_router, prefix="/api/v1") app.include_router(auth_router, prefix="/api/v1/auth") +app.include_router(oauth_router, prefix="/api/v1/auth") app.include_router(user_router, prefix="/api/v1/user") +app.include_router(semana_router, prefix="/api/v1") +app.include_router(semana_admin_router, prefix="/api/v1") +app.include_router(atividade_router, prefix="/api/v1") +app.include_router(atividade_admin_router, prefix="/api/v1") +app.include_router(atividade_attendance_router, prefix="/api/v1") app.include_router(user_admin_router, prefix="/api/v1/admin/users") app.include_router(challenge_router, prefix="/api/v1/challenge") app.include_router(challenge_admin_router, prefix="/api/v1/admin/challenge") @@ -44,7 +70,6 @@ async def lifespan(app: FastAPI): # Arquivos estáticos (imagens de challenges) # --------------------------------------------------------------------------- -_settings = config.get_settings() app.mount( _settings.media_url_prefix, StaticFiles(directory=_settings.media_root, check_dir=False), diff --git a/backend/app/semana/models.py b/backend/app/semana/models.py new file mode 100644 index 00000000..f24bba60 --- /dev/null +++ b/backend/app/semana/models.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +import uuid +from typing import TYPE_CHECKING + +from sqlalchemy import ForeignKey, Integer, String, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.core.mixins import TimestampsMixin, UUIDPKMixin +from app.core.models import Base + +if TYPE_CHECKING: + from app.atividade.models import Atividade + from app.challenges.models.challenge import Challenge + from app.challenges.models.challenge_participant import ChallengeParticipant + from app.users.models import User + + +class Semana(Base): + __tablename__ = "semana_event" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + nome: Mapped[str] = mapped_column(String(255)) + ano: Mapped[int] = mapped_column() + + challenges: Mapped[list[Challenge]] = relationship(back_populates="semana") + atividades: Mapped[list[Atividade]] = relationship( + back_populates="semana", cascade="all, delete-orphan" + ) + participants: Mapped[list[SemanaParticipant]] = relationship( + back_populates="semana", cascade="all, delete-orphan" + ) + + +class SemanaParticipant(Base, UUIDPKMixin, TimestampsMixin): + __tablename__ = "semana_participants" + + semana_id: Mapped[int] = mapped_column( + ForeignKey("semana_event.id", ondelete="CASCADE") + ) + user_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE") + ) + nickname: Mapped[str | None] = mapped_column(String(255), nullable=True) + semana: Mapped[Semana] = relationship(back_populates="participants") + user: Mapped[User] = relationship() + challenge_attempts: Mapped[list[ChallengeParticipant]] = relationship( + back_populates="semana_participant" + ) + point_events: Mapped[list[PointEvent]] = relationship( + back_populates="semana_participant", cascade="all, delete-orphan" + ) + + __table_args__ = ( + UniqueConstraint( + "semana_id", "user_id", name="uq_semana_participant_event_user" + ), + UniqueConstraint( + "semana_id", "nickname", name="uq_semana_participant_nickname" + ), + ) + + +SemanaEvent = Semana + + +class PointEvent(Base, UUIDPKMixin, TimestampsMixin): + __tablename__ = "point_events" + + semana_participant_id: Mapped[uuid.UUID] = mapped_column( + ForeignKey("semana_participants.id", ondelete="CASCADE") + ) + amount: Mapped[int] = mapped_column() + source_type: Mapped[str] = mapped_column(String(32)) + source_id: Mapped[uuid.UUID | None] = mapped_column(nullable=True) + reason: Mapped[str | None] = mapped_column(String(255), nullable=True) + + semana_participant: Mapped[SemanaParticipant] = relationship( + back_populates="point_events" + ) + + __table_args__ = ( + UniqueConstraint( + "semana_participant_id", + "source_type", + "source_id", + name="uq_point_event_source", + ), + ) diff --git a/backend/app/semana/nicknames.py b/backend/app/semana/nicknames.py new file mode 100644 index 00000000..0737c68b --- /dev/null +++ b/backend/app/semana/nicknames.py @@ -0,0 +1,42 @@ +import csv +import secrets +from functools import lru_cache +from pathlib import Path + +from sqlalchemy import exists, select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.semana.models import SemanaParticipant + +NICKNAME_FILE = Path(__file__).parents[2] / "scripts" / "data" / "usernames.csv" +MAX_GENERATION_ATTEMPTS = 20 + + +@lru_cache(maxsize=1) +def nickname_bases() -> tuple[str, ...]: + with NICKNAME_FILE.open(encoding="utf-8", newline="") as file: + bases = tuple( + row["nickname"].strip() + for row in csv.DictReader(file) + if row.get("nickname", "").strip() + ) + if not bases: + raise RuntimeError(f"No nickname bases found in {NICKNAME_FILE}") + return bases + + +async def generate_nickname(session: AsyncSession, semana_id: int) -> str: + for _ in range(MAX_GENERATION_ATTEMPTS): + candidate = f"{secrets.choice(nickname_bases())}{secrets.randbelow(10000):04d}" + taken = await session.scalar( + select( + exists().where( + SemanaParticipant.semana_id == semana_id, + SemanaParticipant.nickname == candidate, + ) + ) + ) + if not taken: + return candidate + + raise RuntimeError("Could not generate a unique Semana nickname.") diff --git a/backend/app/semana/routes.py b/backend/app/semana/routes.py new file mode 100644 index 00000000..78d05c66 --- /dev/null +++ b/backend/app/semana/routes.py @@ -0,0 +1,162 @@ +from typing import Annotated +from uuid import UUID + +from fastapi import APIRouter, Depends, Security +from sqlalchemy.ext.asyncio import AsyncSession + +from app.auth.dependencies import get_current_admin_user, get_current_user +from app.auth.scopes import Scope +from app.core.database import get_session +from app.core.exceptions.app_errors import BadRequestError, NotFoundError +from app.semana import schemas, services +from app.users.models import User + +router = APIRouter(prefix="/semanas", tags=["semana"]) +admin_router = APIRouter(prefix="/admin/semanas", tags=["admin", "semana"]) + + +@admin_router.get("", response_model=list[schemas.AdminSemanaResponse]) +@admin_router.get( + "/", response_model=list[schemas.AdminSemanaResponse], include_in_schema=False +) +async def list_admin_semanas( + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + semanas = await services.list_semanas(session, include_admin_relations=True) + return [ + schemas.AdminSemanaResponse( + id=semana.id, + nome=semana.nome, + ano=semana.ano, + challenge_count=len(semana.challenges), + participant_count=len(semana.participants), + ) + for semana in semanas + ] + + +@admin_router.post("", response_model=schemas.AdminSemanaResponse, status_code=201) +@admin_router.post( + "/", + response_model=schemas.AdminSemanaResponse, + include_in_schema=False, + status_code=201, +) +async def create_admin_semana( + data: schemas.AdminSemanaCreate, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + semana = await services.create_semana(session, data.nome, data.ano) + await session.commit() + return schemas.AdminSemanaResponse.model_validate(semana) + + +@admin_router.patch("/{semana_id}", response_model=schemas.AdminSemanaResponse) +async def update_admin_semana( + semana_id: int, + data: schemas.AdminSemanaUpdate, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + semana = await services.get_semana(session, semana_id) + if semana is None: + raise NotFoundError("Semana not found.") + await services.update_semana(session, semana, nome=data.nome, ano=data.ano) + await session.commit() + return schemas.AdminSemanaResponse.model_validate(semana) + + +@admin_router.delete("/{semana_id}", status_code=204) +async def delete_admin_semana( + semana_id: int, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + semana = await services.get_semana(session, semana_id) + if semana is None: + raise NotFoundError("Semana not found.") + if semana.challenges or semana.participants: + raise BadRequestError("Cannot delete a Semana with challenges or participants.") + await session.delete(semana) + await session.commit() + + +@router.get("", response_model=list[schemas.SemanaResponse]) +@router.get("/", response_model=list[schemas.SemanaResponse], include_in_schema=False) +async def list_semanas(session: Annotated[AsyncSession, Depends(get_session)]): + return await services.list_semanas(session) + + +@router.get("/participacao", response_model=schemas.ParticipationResponse) +async def get_my_participation( + session: Annotated[AsyncSession, Depends(get_session)], + current_user: Annotated[ + User, Security(get_current_user, scopes=[Scope.PROFILE, Scope.EMAIL]) + ], +): + return await services.get_user_participation(session, current_user.id) + + +@router.post( + "/{semana_id}/join", + response_model=schemas.SemanaParticipantResponse, +) +async def join_semana( + semana_id: int, + session: Annotated[AsyncSession, Depends(get_session)], + current_user: Annotated[ + User, Security(get_current_user, scopes=[Scope.PROFILE, Scope.EMAIL]) + ], +): + semana = await services.get_semana(session, semana_id) + if semana is None: + raise NotFoundError("Semana not found.") + participant = await services.get_or_create_participant( + session, semana, current_user + ) + return schemas.SemanaParticipantResponse( + id=participant.id, + semana_id=participant.semana_id, + user_id=participant.user_id, + nickname=participant.nickname, + ) + + +@router.get("/{semana_id}/ranking", response_model=list[schemas.SemanaRankingEntry]) +async def get_semana_ranking( + semana_id: int, + session: Annotated[AsyncSession, Depends(get_session)], +): + if await services.get_semana(session, semana_id) is None: + raise NotFoundError("Semana not found.") + return [ + schemas.SemanaRankingEntry( + participant_id=row[0], nickname=row[1], points=row[2] + ) + for row in await services.list_ranking(session, semana_id) + ] + + +@admin_router.post( + "/{semana_id}/participants/{participant_id}/points", + response_model=schemas.PointEventResponse, +) +async def award_points( + semana_id: int, + participant_id: UUID, + data: schemas.PointAdjustment, + session: Annotated[AsyncSession, Depends(get_session)], + _: Annotated[User, Security(get_current_admin_user, scopes=[Scope.ADMIN])], +): + participant = await services.get_participant(session, semana_id, participant_id) + if participant is None: + raise NotFoundError("Semana participant not found.") + return await services.add_points( + session, + participant, + data.amount, + source_type="manual", + reason=data.reason, + ) diff --git a/backend/app/semana/schemas.py b/backend/app/semana/schemas.py new file mode 100644 index 00000000..faa2c0ab --- /dev/null +++ b/backend/app/semana/schemas.py @@ -0,0 +1,73 @@ +from datetime import datetime +from uuid import UUID + +from pydantic import BaseModel, ConfigDict + + +class SemanaParticipantResponse(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: UUID + semana_id: int + user_id: UUID + nickname: str + + +class SemanaRankingEntry(BaseModel): + participant_id: UUID + nickname: str + points: int + + +class SemanaResponse(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: int + nome: str + ano: int + + +class AdminSemanaCreate(BaseModel): + nome: str + ano: int + + +class AdminSemanaUpdate(BaseModel): + nome: str | None = None + ano: int | None = None + + +class AdminSemanaResponse(SemanaResponse): + challenge_count: int = 0 + participant_count: int = 0 + + +class PointEventResponse(BaseModel): + model_config = ConfigDict(from_attributes=True) + + id: UUID + amount: int + source_type: str + source_id: UUID | None + reason: str | None + created_at: datetime + + +class PointAdjustment(BaseModel): + amount: int + reason: str + + +class ParticipationWeek(BaseModel): + semana_id: int + nome: str + ano: int + nickname: str | None + pontos: int + horas: int + + +class ParticipationResponse(BaseModel): + pontos: int + horas: int + semanas: list[ParticipationWeek] diff --git a/backend/app/semana/services.py b/backend/app/semana/services.py new file mode 100644 index 00000000..00fbd8e3 --- /dev/null +++ b/backend/app/semana/services.py @@ -0,0 +1,185 @@ +from sqlalchemy import func, select +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm import selectinload + +from app.atividade.models import Atividade, Presenca +from app.semana.models import PointEvent, Semana, SemanaParticipant +from app.semana.nicknames import generate_nickname +from app.users.models import User + + +async def get_semana(session: AsyncSession, semana_id: int) -> Semana | None: + return await session.get(Semana, semana_id) + + +async def list_semanas( + session: AsyncSession, *, include_admin_relations: bool = False +) -> list[Semana]: + statement = select(Semana).order_by(Semana.ano.desc()) + if include_admin_relations: + statement = statement.options( + selectinload(Semana.challenges), + selectinload(Semana.participants), + ) + return list((await session.scalars(statement)).all()) + + +async def create_semana(session: AsyncSession, nome: str, ano: int) -> Semana: + semana = Semana(nome=nome, ano=ano) + session.add(semana) + await session.flush() + return semana + + +async def update_semana( + session: AsyncSession, + semana: Semana, + *, + nome: str | None = None, + ano: int | None = None, +) -> Semana: + if nome is not None: + semana.nome = nome + if ano is not None: + semana.ano = ano + await session.flush() + return semana + + +async def get_or_create_participant( + session: AsyncSession, semana: Semana, user: User +) -> SemanaParticipant: + participant = await session.scalar( + select(SemanaParticipant).where( + SemanaParticipant.semana_id == semana.id, + SemanaParticipant.user_id == user.id, + ) + ) + if participant is not None: + if participant.nickname is None: + participant.nickname = await generate_nickname(session, semana.id) + await session.flush() + return participant + + participant = SemanaParticipant( + semana_id=semana.id, + user_id=user.id, + nickname=await generate_nickname(session, semana.id), + ) + session.add(participant) + await session.flush() + return participant + + +async def add_points( + session: AsyncSession, + participant: SemanaParticipant, + amount: int, + *, + source_type: str, + source_id=None, + reason: str | None = None, +) -> PointEvent: + event = PointEvent( + semana_participant_id=participant.id, + amount=amount, + source_type=source_type, + source_id=source_id, + reason=reason, + ) + session.add(event) + await session.flush() + return event + + +async def list_ranking(session: AsyncSession, semana_id: int): + rows = await session.execute( + select( + SemanaParticipant.id, + SemanaParticipant.nickname, + func.coalesce(func.sum(PointEvent.amount), 0).label("points"), + ) + .outerjoin(PointEvent) + .where(SemanaParticipant.semana_id == semana_id) + .group_by( + SemanaParticipant.id, + SemanaParticipant.nickname, + ) + .order_by(func.coalesce(func.sum(PointEvent.amount), 0).desc()) + ) + return rows.all() + + +async def get_user_participation(session: AsyncSession, user_id): + points_rows = await session.execute( + select( + Semana.id, + Semana.nome, + Semana.ano, + SemanaParticipant.nickname, + func.coalesce(func.sum(PointEvent.amount), 0).label("pontos"), + ) + .join(SemanaParticipant, SemanaParticipant.semana_id == Semana.id) + .outerjoin(PointEvent, PointEvent.semana_participant_id == SemanaParticipant.id) + .where( + SemanaParticipant.user_id == user_id, + SemanaParticipant.deleted_at.is_(None), + PointEvent.deleted_at.is_(None) | (PointEvent.id.is_(None)), + ) + .group_by( + Semana.id, + Semana.nome, + Semana.ano, + SemanaParticipant.nickname, + ) + ) + hours_rows = await session.execute( + select( + Atividade.semana_id, + func.coalesce(func.sum(Presenca.horas), 0).label("horas"), + ) + .join(Presenca, Presenca.atividade_id == Atividade.id) + .where( + Presenca.user_id == user_id, + Presenca.deleted_at.is_(None), + Atividade.deleted_at.is_(None), + ) + .group_by(Atividade.semana_id) + ) + points = {row.id: row for row in points_rows} + hours = {row.semana_id: row.horas for row in hours_rows} + semana_ids = set(points) | set(hours) + weeks = [] + for semana_id in semana_ids: + point_row = points.get(semana_id) + weeks.append( + { + "semana_id": semana_id, + "nome": point_row.nome + if point_row + else (await get_semana(session, semana_id)).nome, + "ano": point_row.ano + if point_row + else (await get_semana(session, semana_id)).ano, + "nickname": point_row.nickname if point_row else None, + "pontos": int(point_row.pontos) if point_row else 0, + "horas": int(hours.get(semana_id, 0)), + } + ) + weeks.sort(key=lambda week: week["ano"], reverse=True) + return { + "pontos": sum(week["pontos"] for week in weeks), + "horas": sum(week["horas"] for week in weeks), + "semanas": weeks, + } + + +async def get_participant( + session: AsyncSession, semana_id: int, participant_id +) -> SemanaParticipant | None: + return await session.scalar( + select(SemanaParticipant).where( + SemanaParticipant.id == participant_id, + SemanaParticipant.semana_id == semana_id, + ) + ) diff --git a/backend/app/tests/atividade/integration/test_manual_presence.py b/backend/app/tests/atividade/integration/test_manual_presence.py new file mode 100644 index 00000000..893227b1 --- /dev/null +++ b/backend/app/tests/atividade/integration/test_manual_presence.py @@ -0,0 +1,51 @@ +from datetime import UTC, datetime, timedelta + +from app.atividade.models import Atividade, TipoAtividade +from app.auth.dependencies import get_current_admin_user +from app.main import app +from app.semana.models import SemanaEvent, SemanaParticipant + + +async def test_admin_registers_subscribed_user_without_name( + db_client, db_session, user_factory +): + admin = await user_factory(email="attendance-admin@example.com") + admin.is_admin = True + admin.is_verified = True + + attendee = await user_factory(email="attendance-user@example.com", name="Attendee") + week = SemanaEvent(nome="Attendance test", ano=2040) + db_session.add(week) + await db_session.flush() + + db_session.add( + SemanaParticipant( + semana_id=week.id, + user_id=attendee.id, + nickname="attendee2040", + ) + ) + starts_at = datetime.now(UTC) + timedelta(days=1) + activity = Atividade( + semana_id=week.id, + tipo=TipoAtividade.PALESTRA, + titulo="Attendance test activity", + comeca_as=starts_at, + termina_as=starts_at + timedelta(hours=1), + codigo="T040", + pontos=0, + horas=1, + ) + db_session.add(activity) + await db_session.flush() + + app.dependency_overrides[get_current_admin_user] = lambda: admin + response = await db_client.post( + f"/api/v1/admin/semanas/{week.id}/atividades/{activity.id}/presencas", + json={"nome": "", "email": attendee.email}, + ) + + assert response.status_code == 201, response.text + assert response.json()["nome"] == attendee.name + assert response.json()["email"] == attendee.email + assert response.json()["user_id"] == str(attendee.id) diff --git a/backend/app/tests/auth/integration/test_auth_routes.py b/backend/app/tests/auth/integration/test_auth_routes.py index 85a6c4ff..66fca4d7 100644 --- a/backend/app/tests/auth/integration/test_auth_routes.py +++ b/backend/app/tests/auth/integration/test_auth_routes.py @@ -112,40 +112,12 @@ async def test_me_returns_current_user(db_client: AsyncClient, user_factory): body = response.json() assert body["email"] == user.email assert body["name"] == "Me User" - assert body["username"]["id"] == str(user.username_id) - assert body["username"]["nickname"] + assert "username" not in body @pytest.mark.asyncio -async def test_me_returns_username_and_mother_details( - db_client: AsyncClient, user_factory, db_session -): - from app.users.username.models import Username, UsernameMother - +async def test_me_does_not_return_semana_username(db_client: AsyncClient, user_factory): user = await user_factory(email="me-username@example.com", name="Me Username") - first_mother = UsernameMother( - first_name="Ada", - last_name="Lovelace", - full_name="Ada Lovelace", - description="Mathematician", - ) - last_mother = UsernameMother( - first_name="Grace", - last_name="Hopper", - full_name="Grace Hopper", - description="Computer scientist", - ) - db_session.add_all([first_mother, last_mother]) - await db_session.flush() - username = Username( - nickname="AdaHopper", - first_mother_id=first_mother.id, - last_mother_id=last_mother.id, - ) - db_session.add(username) - await db_session.flush() - user.username_id = username.id - await db_session.flush() token = auth_services.create_access_token(user.id, [Scope.PROFILE, Scope.EMAIL]) response = await db_client.get( @@ -154,24 +126,7 @@ async def test_me_returns_username_and_mother_details( ) assert response.status_code == 200 - assert response.json()["username"] == { - "id": str(username.id), - "nickname": "AdaHopper", - "first_mother": { - "id": str(first_mother.id), - "first_name": "Ada", - "last_name": "Lovelace", - "full_name": "Ada Lovelace", - "description": "Mathematician", - }, - "last_mother": { - "id": str(last_mother.id), - "first_name": "Grace", - "last_name": "Hopper", - "full_name": "Grace Hopper", - "description": "Computer scientist", - }, - } + assert "username" not in response.json() @pytest.mark.asyncio @@ -369,6 +324,7 @@ async def test_refresh_old_token_rejected_after_rotation( assert first.status_code == 200 # 2º refresh com o MESMO cookie antigo — deve falhar + db_client.cookies.clear() db_client.cookies.set("refresh_token", old_token) second = await db_client.post("/api/v1/auth/refresh") assert second.status_code == 401 diff --git a/backend/app/tests/auth/integration/test_oauth_routes.py b/backend/app/tests/auth/integration/test_oauth_routes.py new file mode 100644 index 00000000..9b697dcc --- /dev/null +++ b/backend/app/tests/auth/integration/test_oauth_routes.py @@ -0,0 +1,243 @@ +from unittest.mock import MagicMock, patch + +import pytest +from httpx2 import AsyncClient +from itsdangerous import URLSafeTimedSerializer +from pydantic import SecretStr +from sqlalchemy import select + +from app.core.config import Settings +from app.users.models import User + + +def _make_state_cookie(settings: Settings, provider: str, state: str) -> str: + serializer = URLSafeTimedSerializer( + settings.secret_key.get_secret_value(), salt="oauth-state" + ) + return serializer.dumps({"state": state, "provider": provider}) + + +@pytest.mark.asyncio +async def test_oauth_login_redirects_to_google( + db_client: AsyncClient, test_settings: Settings +): + test_settings.google_client_id = "test-google-id" + test_settings.google_client_secret = SecretStr("test-google-secret") + + response = await db_client.get( + "/api/v1/auth/oauth/google/login", follow_redirects=False + ) + + assert response.status_code == 302 + location = response.headers.get("Location", "") + assert location.startswith("https://accounts.google.com/o/oauth2/v2/auth?") + assert "client_id=test-google-id" in location + assert "response_type=code" in location + assert "scope=openid+email+profile" in location + assert response.cookies.get("oauth_state") is not None + + +@pytest.mark.asyncio +async def test_oauth_login_unavailable_when_missing_credentials( + db_client: AsyncClient, test_settings: Settings +): + test_settings.google_client_id = None + test_settings.google_client_secret = None + + response = await db_client.get( + "/api/v1/auth/oauth/google/login", follow_redirects=False + ) + + assert response.status_code == 303 + location = response.headers.get("Location", "") + assert "error=provider_unavailable" in location + + +@pytest.mark.asyncio +async def test_oauth_login_invalid_provider( + db_client: AsyncClient, test_settings: Settings +): + response = await db_client.get( + "/api/v1/auth/oauth/facebook/login", follow_redirects=False + ) + + assert response.status_code == 303 + location = response.headers.get("Location", "") + assert "error=invalid_provider" in location + + +@pytest.mark.asyncio +async def test_oauth_callback_invalid_state( + db_client: AsyncClient, test_settings: Settings +): + test_settings.google_client_id = "test-google-id" + test_settings.google_client_secret = SecretStr("test-google-secret") + + db_client.cookies.set("oauth_state", "bad-signature") + response = await db_client.get( + "/api/v1/auth/oauth/google/callback", + params={"code": "123", "state": "invalid-state"}, + follow_redirects=False, + ) + + assert response.status_code == 303 + assert "error=oauth_state" in response.headers.get("Location", "") + + +@pytest.mark.asyncio +async def test_oauth_callback_denied(db_client: AsyncClient, test_settings: Settings): + test_settings.google_client_id = "test-google-id" + test_settings.google_client_secret = SecretStr("test-google-secret") + + state = "secure-random-state" + cookie_val = _make_state_cookie(test_settings, "google", state) + + db_client.cookies.set("oauth_state", cookie_val) + response = await db_client.get( + "/api/v1/auth/oauth/google/callback", + params={"error": "access_denied", "state": state}, + follow_redirects=False, + ) + + assert response.status_code == 303 + assert "error=oauth_denied" in response.headers.get("Location", "") + + +@pytest.mark.asyncio +async def test_oauth_callback_google_creates_and_reauthenticates_user( + db_client: AsyncClient, db_session, test_settings: Settings +): + test_settings.google_client_id = "test-google-id" + test_settings.google_client_secret = SecretStr("test-google-secret") + + state = "random-oauth-state-1234" + cookie_val = _make_state_cookie(test_settings, "google", state) + + mock_token_resp = MagicMock() + mock_token_resp.json.return_value = {"id_token": "fake-google-jwt"} + mock_token_resp.raise_for_status.return_value = None + + mock_claims_resp = MagicMock() + mock_claims_resp.json.return_value = { + "aud": "test-google-id", + "iss": "https://accounts.google.com", + "email": "oauth.user@example.com", + "email_verified": True, + "name": "OAuth User", + "sub": "google-user-id", + } + mock_claims_resp.raise_for_status.return_value = None + + db_client.cookies.set("oauth_state", cookie_val) + with ( + patch("httpx.AsyncClient.post", return_value=mock_token_resp), + patch("httpx.AsyncClient.get", return_value=mock_claims_resp), + ): + response = await db_client.get( + "/api/v1/auth/oauth/google/callback", + params={"code": "valid-auth-code", "state": state}, + follow_redirects=False, + ) + + assert response.status_code == 303 + assert response.headers.get("Location", "").endswith("/semana/perfil") + assert response.cookies.get("refresh_token") is not None + + user = await db_session.scalar( + select(User).where(User.email == "oauth.user@example.com") + ) + assert user is not None + assert user.name == "OAuth User" + assert user.oauth_provider == "google" + assert user.oauth_subject == "google-user-id" + assert user.is_verified is True + assert user.password_hash is None + + repeat_state = "returning-google-state" + db_client.cookies.set( + "oauth_state", _make_state_cookie(test_settings, "google", repeat_state) + ) + with ( + patch("httpx.AsyncClient.post", return_value=mock_token_resp), + patch("httpx.AsyncClient.get", return_value=mock_claims_resp), + ): + response = await db_client.get( + "/api/v1/auth/oauth/google/callback", + params={"code": "returning-auth-code", "state": repeat_state}, + follow_redirects=False, + ) + + assert response.status_code == 303 + assert response.headers.get("Location", "").endswith("/semana/perfil") + returning_user = await db_session.scalar( + select(User).where(User.oauth_subject == "google-user-id") + ) + assert returning_user is not None + assert returning_user.id == user.id + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("oauth_provider", "oauth_subject", "deleted"), + [ + (None, None, False), + ("github", "github-user-id", False), + ("google", "google-user-id", True), + ], +) +async def test_oauth_callback_blocks_existing_email( + db_client: AsyncClient, + db_session, + deleted_user_factory, + user_factory, + test_settings: Settings, + oauth_provider: str | None, + oauth_subject: str | None, + deleted: bool, +): + if deleted: + user = await deleted_user_factory(email="existing-pwd@example.com") + else: + user = await user_factory(email="existing-pwd@example.com") + user.oauth_provider = oauth_provider + user.oauth_subject = oauth_subject + await db_session.flush() + + test_settings.google_client_id = "test-google-id" + test_settings.google_client_secret = SecretStr("test-google-secret") + + state = "state-conflict" + cookie_val = _make_state_cookie(test_settings, "google", state) + + mock_token_resp = MagicMock() + mock_token_resp.json.return_value = {"id_token": "fake-jwt"} + mock_token_resp.raise_for_status.return_value = None + + mock_claims_resp = MagicMock() + mock_claims_resp.json.return_value = { + "aud": "test-google-id", + "iss": "https://accounts.google.com", + "email": "existing-pwd@example.com", + "email_verified": True, + "name": "Imposter", + "sub": "google-user-id", + } + mock_claims_resp.raise_for_status.return_value = None + + db_client.cookies.set("oauth_state", cookie_val) + with ( + patch("httpx.AsyncClient.post", return_value=mock_token_resp), + patch("httpx.AsyncClient.get", return_value=mock_claims_resp), + ): + response = await db_client.get( + "/api/v1/auth/oauth/google/callback", + params={"code": "code", "state": state}, + follow_redirects=False, + ) + + assert response.status_code == 303 + assert "error=email_exists" in response.headers.get("Location", "") + assert user.oauth_provider == oauth_provider + assert user.oauth_subject == oauth_subject + assert user.password_hash is not None + assert (user.deleted_at is not None) is deleted diff --git a/backend/app/tests/auth/unit/test_auth_services.py b/backend/app/tests/auth/unit/test_auth_services.py index bdb4ca30..2dfec107 100644 --- a/backend/app/tests/auth/unit/test_auth_services.py +++ b/backend/app/tests/auth/unit/test_auth_services.py @@ -327,6 +327,23 @@ async def test_refresh_access_token_uses_original_scopes_when_not_specified( assert set(payload["scopes"].split(" ")) == {"openid", "email"} +@pytest.mark.asyncio +async def test_refresh_access_token_adds_admin_scope_after_promotion( + db_session: AsyncSession, user_factory, jwt_settings: Settings +): + user = await user_factory(email="refresh-admin@example.com") + user.is_admin = True + await db_session.flush() + token = await auth_services.create_refresh_token( + db_session, user.id, list(DEFAULT_SCOPES) + ) + + new_access = await auth_services.refresh_access_token(db_session, token) + + payload = _decode_access(new_access.access_token, jwt_settings) + assert Scope.ADMIN in payload["scopes"].split(" ") + + # =========================================================================== # revoke_refresh_token # =========================================================================== @@ -374,6 +391,6 @@ def test_build_refresh_token_cookie_shape(jwt_settings: Settings): assert cookie["key"] == "refresh_token" assert cookie["value"] == "my-token" assert cookie["httponly"] is True - assert cookie["secure"] is True + assert cookie["secure"] is False assert cookie["samesite"] == "lax" assert cookie["max_age"] == jwt_settings.refresh_token_expire_days * 24 * 60 * 60 diff --git a/backend/app/tests/base/test_rate_limit.py b/backend/app/tests/base/test_rate_limit.py new file mode 100644 index 00000000..f635bad3 --- /dev/null +++ b/backend/app/tests/base/test_rate_limit.py @@ -0,0 +1,76 @@ +import asyncio + +from app.core.rate_limit import RateLimitMiddleware + + +def test_rate_limit_blocks_after_limit(): + calls = 0 + + async def app(scope, receive, send): + nonlocal calls + calls += 1 + + limiter = RateLimitMiddleware(app) + scope = { + "type": "http", + "method": "POST", + "path": "/api/v1/auth/login", + "raw_path": b"/api/v1/auth/login", + "query_string": b"", + "headers": [], + "client": ("127.0.0.1", 1234), + "server": ("test", 80), + "scheme": "http", + "http_version": "1.1", + } + + sent: list[dict] = [] + + async def send(message): + sent.append(message) + + async def run(): + for _ in range(5): + await limiter(scope, None, send) + await limiter(scope, None, send) + + asyncio.run(run()) + + assert calls == 5 + assert next(message for message in sent if "status" in message)["status"] == 429 + + +def test_rate_limit_blocks_attendance_code_guessing_across_codes(): + calls = 0 + + async def app(scope, receive, send): + nonlocal calls + calls += 1 + + limiter = RateLimitMiddleware(app) + sent: list[dict] = [] + + async def send(message): + sent.append(message) + + async def run(): + for code in range(10): + scope = { + "type": "http", + "method": "POST", + "path": f"/api/v1/semanas/1/atividades/registrar/{code:04}", + "raw_path": b"", + "query_string": b"", + "headers": [], + "client": ("127.0.0.1", 1234), + "server": ("test", 80), + "scheme": "http", + "http_version": "1.1", + } + await limiter(scope, None, send) + await limiter(scope, None, send) + + asyncio.run(run()) + + assert calls == 10 + assert next(message for message in sent if "status" in message)["status"] == 429 diff --git a/backend/app/tests/challenges/conftest.py b/backend/app/tests/challenges/conftest.py index 37d29a09..336ce840 100644 --- a/backend/app/tests/challenges/conftest.py +++ b/backend/app/tests/challenges/conftest.py @@ -12,8 +12,8 @@ from app.auth.dependencies import get_current_admin_user, get_current_user from app.challenges.models.challenge import Challenge, ChallengeScoringType from app.challenges.models.question import Question +from app.semana.models import SemanaEvent from app.users.models import User -from app.users.username import services as username_service # --------------------------------------------------------------------------- # Factories @@ -38,29 +38,26 @@ def _make_user(*, is_admin: bool = False) -> User: @pytest.fixture -async def user(db_session: AsyncSession, username_catalog) -> User: +async def user(db_session: AsyncSession) -> User: u = _make_user() db_session.add(u) await db_session.flush() - await username_service.assign_username(u.id, db_session) return u @pytest.fixture -async def other_user(db_session: AsyncSession, username_catalog) -> User: +async def other_user(db_session: AsyncSession) -> User: u = _make_user() db_session.add(u) await db_session.flush() - await username_service.assign_username(u.id, db_session) return u @pytest.fixture -async def admin(db_session: AsyncSession, username_catalog) -> User: +async def admin(db_session: AsyncSession) -> User: u = _make_user(is_admin=True) db_session.add(u) await db_session.flush() - await username_service.assign_username(u.id, db_session) return u @@ -92,16 +89,33 @@ def _switch(user: User) -> AsyncClient: @pytest.fixture -async def challenge(db_session: AsyncSession) -> Challenge: - c = Challenge(title="Quiz Teste", scoring_type=ChallengeScoringType.QUIZ) +async def semana(db_session: AsyncSession) -> SemanaEvent: + event = SemanaEvent(nome="Semana Teste", ano=2026) + db_session.add(event) + await db_session.flush() + return event + + +@pytest.fixture +async def challenge(db_session: AsyncSession, semana: SemanaEvent) -> Challenge: + c = Challenge( + title="Quiz Teste", + scoring_type=ChallengeScoringType.QUIZ, + points_value=225, + semana_id=semana.id, + ) db_session.add(c) await db_session.flush() return c @pytest.fixture -async def manual_challenge(db_session: AsyncSession) -> Challenge: - c = Challenge(title="Manual Teste", scoring_type=ChallengeScoringType.MANUAL) +async def manual_challenge(db_session: AsyncSession, semana: SemanaEvent) -> Challenge: + c = Challenge( + title="Manual Teste", + scoring_type=ChallengeScoringType.MANUAL, + semana_id=semana.id, + ) db_session.add(c) await db_session.flush() return c @@ -113,19 +127,16 @@ async def questions(db_session: AsyncSession, challenge: Challenge) -> list[Ques Question( prompt="2+2?", answer="4", - points_value=100, challenge_id=challenge.id, ), Question( prompt="3*3?", answer="9", - points_value=50, challenge_id=challenge.id, ), Question( prompt="Capital do Brasil?", answer="Brasília", - points_value=75, challenge_id=challenge.id, ), ] diff --git a/backend/app/tests/challenges/integration/test_admin_routes.py b/backend/app/tests/challenges/integration/test_admin_routes.py index 3af93883..5a0820e6 100644 --- a/backend/app/tests/challenges/integration/test_admin_routes.py +++ b/backend/app/tests/challenges/integration/test_admin_routes.py @@ -9,6 +9,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.challenges.models.challenge_participant import ChallengeParticipant +from app.challenges.models.input import Input from app.challenges.models.question import Question @@ -22,12 +23,21 @@ async def test_admin_can_create_challenge(client: AsyncClient, as_user, admin): c = as_user(admin) r = await c.post( "/api/v1/admin/challenge/", - json={"title": "Novo", "scoring_type": "quiz"}, + json={ + "title": "Novo", + "description": "Descrição inicial", + "scoring_type": "quiz", + }, ) assert r.status_code == 201, r.text body = r.json() assert body["title"] == "Novo" + assert body["description"] == "Descrição inicial" assert body["scoring_type"] == "quiz" + default_start = datetime.fromisoformat(body["starts_at"]) + assert default_start.tzinfo is not None + assert timedelta(seconds=-1) <= default_start - datetime.now(UTC) + assert default_start - datetime.now(UTC) <= timedelta(seconds=1) default_deadline = datetime.fromisoformat(body["finishes_at"]) assert default_deadline.tzinfo is not None assert timedelta(hours=23, minutes=59) <= default_deadline - datetime.now(UTC) @@ -35,6 +45,34 @@ async def test_admin_can_create_challenge(client: AsyncClient, as_user, admin): assert body["questions"] == [] +async def test_admin_can_set_challenge_start(client: AsyncClient, as_user, admin): + c = as_user(admin) + starts_at = datetime.now(UTC) + timedelta(days=2) + created = await c.post( + "/api/v1/admin/challenge/", + json={"title": "Início agendado", "starts_at": starts_at.isoformat()}, + ) + + assert created.status_code == 201, created.text + challenge_id = created.json()["id"] + assert datetime.fromisoformat(created.json()["starts_at"]) == starts_at + + updated_starts_at = starts_at + timedelta(days=1) + updated = await c.patch( + f"/api/v1/admin/challenge/{challenge_id}", + json={"starts_at": updated_starts_at.isoformat()}, + ) + + assert updated.status_code == 200, updated.text + assert datetime.fromisoformat(updated.json()["starts_at"]) == updated_starts_at + + admin_detail = await c.get(f"/api/v1/admin/challenge/{challenge_id}") + assert admin_detail.status_code == 200 + admin_list = await c.get("/api/v1/admin/challenge", params={"limit": 100}) + assert admin_list.status_code == 200 + assert challenge_id in {item["id"] for item in admin_list.json()["items"]} + + async def test_admin_can_create_challenge_with_questions( client: AsyncClient, as_user, admin ): @@ -43,8 +81,9 @@ async def test_admin_can_create_challenge_with_questions( "/api/v1/admin/challenge/", json={ "title": "Quiz com perguntas", + "points_value": 60, "questions": [ - {"prompt": "2+2?", "answer": "4", "points_value": 10}, + {"prompt": "2+2?", "answer": "4"}, {"prompt": "3+3?", "answer": "6"}, ], }, @@ -54,8 +93,129 @@ async def test_admin_can_create_challenge_with_questions( created_questions = r.json()["questions"] assert len(created_questions) == 2 assert created_questions[0]["prompt"] == "2+2?" - assert created_questions[0]["points_value"] == 10 - assert created_questions[1]["points_value"] == 0 + assert r.json()["points_value"] == 60 + + +async def test_admin_can_list_participants_ordered_by_challenge_and_score( + client: AsyncClient, + as_user, + admin, + user, + other_user, + challenge, + manual_challenge, + db_session: AsyncSession, +): + challenge.title = "Alpha Challenge" + manual_challenge.title = "Beta Challenge" + db_session.add_all( + [ + ChallengeParticipant(user_id=user.id, challenge_id=challenge.id, score=10), + ChallengeParticipant( + user_id=other_user.id, challenge_id=challenge.id, score=25 + ), + ChallengeParticipant( + user_id=user.id, challenge_id=manual_challenge.id, score=100 + ), + ] + ) + await db_session.flush() + + response = await as_user(admin).get("/api/v1/admin/challenge/participants") + + assert response.status_code == 200, response.text + body = response.json() + assert [item["challenge_title"] for item in body["items"]] == [ + "Alpha Challenge", + "Alpha Challenge", + "Beta Challenge", + ] + assert [item["score"] for item in body["items"]] == [25, 10, 100] + assert body["items"][0]["user_id"] == str(other_user.id) + assert body["items"][0]["user_name"] == other_user.name + assert body["items"][0]["user_email"] == other_user.email + assert body["items"][0]["challenge_id"] == str(challenge.id) + assert body["total"] == 3 + + filtered_response = await as_user(admin).get( + "/api/v1/admin/challenge/participants", + params={ + "challenge_id": str(challenge.id), + "participant_query": other_user.email, + }, + ) + + assert filtered_response.status_code == 200, filtered_response.text + filtered_body = filtered_response.json() + assert filtered_body["total"] == 1 + assert filtered_body["items"][0]["user_id"] == str(other_user.id) + + +async def test_admin_can_create_input_challenge( + client: AsyncClient, as_user, admin, db_session: AsyncSession +): + c = as_user(admin) + r = await c.post( + "/api/v1/admin/challenge/", + json={ + "title": "Resposta livre", + "scoring_type": "input", + "prompt": "Qual é a resposta?", + "points_value": 20, + "input_answer": "42", + }, + ) + + assert r.status_code == 201, r.text + body = r.json() + assert body["prompt"] == "Qual é a resposta?" + assert body["points_value"] == 20 + assert body["input_answer"] == "42" + input_data = await db_session.scalar( + select(Input).where(Input.challenge_id == body["id"]) + ) + assert input_data is not None + + +async def test_admin_rejects_input_challenge_without_answer( + client: AsyncClient, as_user, admin +): + c = as_user(admin) + r = await c.post( + "/api/v1/admin/challenge/", + json={"title": "Resposta livre", "scoring_type": "input", "prompt": "Q?"}, + ) + + assert r.status_code == 422 + + +async def test_admin_can_update_input_challenge(client: AsyncClient, as_user, admin): + c = as_user(admin) + created = await c.post( + "/api/v1/admin/challenge/", + json={ + "title": "Resposta livre", + "scoring_type": "input", + "prompt": "Q?", + "input_answer": "42", + }, + ) + challenge_id = created.json()["id"] + + r = await c.patch( + f"/api/v1/admin/challenge/{challenge_id}", + json={ + "description": "Descrição atualizada", + "prompt": "Nova pergunta", + "points_value": 35, + }, + ) + + assert r.status_code == 200, r.text + assert r.json()["prompt"] == "Nova pergunta" + assert r.json()["description"] == "Descrição atualizada" + assert r.json()["points_value"] == 35 + assert r.json()["input_answer"] == "42" async def test_admin_can_set_challenge_deadline(client: AsyncClient, as_user, admin): @@ -135,11 +295,7 @@ async def test_admin_patch_replaces_questions_and_hard_deletes_old_ones( r = await c.patch( f"/api/v1/admin/challenge/{challenge.id}", - json={ - "questions": [ - {"prompt": "New prompt", "answer": "New answer", "points_value": 25} - ] - }, + json={"questions": [{"prompt": "New prompt", "answer": "New answer"}]}, ) assert r.status_code == 200, r.text @@ -148,7 +304,6 @@ async def test_admin_patch_replaces_questions_and_hard_deletes_old_ones( assert len(body["questions"]) == 1 assert body["questions"][0]["prompt"] == "New prompt" assert body["questions"][0]["answer"] == "New answer" - assert body["questions"][0]["points_value"] == 25 remaining_old_ids = set( ( await db_session.scalars( @@ -215,6 +370,13 @@ async def test_admin_can_add_and_subtract_participant_score( "challenge_id": str(challenge.id), "score": 55, } + added_participants = await c.get("/api/v1/admin/challenge/participants") + listed_after_add = next( + item + for item in added_participants.json()["items"] + if item["id"] == str(participant.id) + ) + assert listed_after_add["score"] == 55 subtract_response = await c.patch( f"/api/v1/admin/challenge/{challenge.id}/participants/{participant.id}/score", @@ -222,6 +384,13 @@ async def test_admin_can_add_and_subtract_participant_score( ) assert subtract_response.status_code == 200, subtract_response.text assert subtract_response.json()["score"] == -15 + subtracted_participants = await c.get("/api/v1/admin/challenge/participants") + listed_after_subtract = next( + item + for item in subtracted_participants.json()["items"] + if item["id"] == str(participant.id) + ) + assert listed_after_subtract["score"] == -15 async def test_admin_score_adjustment_requires_matching_challenge( diff --git a/backend/app/tests/challenges/integration/test_list_and_ranking.py b/backend/app/tests/challenges/integration/test_list_and_ranking.py index 660f2639..fbdde713 100644 --- a/backend/app/tests/challenges/integration/test_list_and_ranking.py +++ b/backend/app/tests/challenges/integration/test_list_and_ranking.py @@ -3,12 +3,14 @@ from __future__ import annotations import uuid +from datetime import UTC, datetime, timedelta from httpx import AsyncClient from sqlalchemy.ext.asyncio import AsyncSession from app.challenges.models.challenge import Challenge, ChallengeScoringType from app.challenges.models.challenge_participant import ChallengeParticipant +from app.semana.models import SemanaParticipant async def test_list_challenges_paginated( @@ -16,11 +18,27 @@ async def test_list_challenges_paginated( ): for i in range(5): db_session.add(Challenge(title=f"C{i}", scoring_type=ChallengeScoringType.QUIZ)) + future_challenge = Challenge( + title="Future challenge", + scoring_type=ChallengeScoringType.QUIZ, + starts_at=datetime.now(UTC) + timedelta(days=1), + ) + db_session.add(future_challenge) await db_session.flush() c = as_user(user) - r = await c.get("api/v1/challenge/", params={"limit": 2, "offset": 0}) + anonymous_list = await client.get( + "/api/v1/challenge", params={"limit": 100, "offset": 0} + ) + assert anonymous_list.status_code == 200 + assert anonymous_list.json()["total"] == 5 + assert all( + item["id"] != str(future_challenge.id) + for item in anonymous_list.json()["items"] + ) + + r = await c.get("api/v1/challenge", params={"limit": 2, "offset": 0}) assert r.status_code == 200 body = r.json() assert body["total"] == 5 @@ -32,6 +50,20 @@ async def test_list_challenges_paginated( assert len(r.json()["items"]) == 1 +async def test_future_challenge_is_hidden_from_public_detail_and_ranking( + client: AsyncClient, as_user, user, challenge, db_session: AsyncSession +): + challenge.starts_at = datetime.now(UTC) + timedelta(days=1) + await db_session.flush() + + c = as_user(user) + detail = await c.get(f"/api/v1/challenge/{challenge.id}") + ranking = await c.get(f"/api/v1/challenge/{challenge.id}/ranking") + + assert detail.status_code == 404 + assert ranking.status_code == 404 + + async def test_list_rejects_bad_pagination(client: AsyncClient, as_user, user): c = as_user(user) r = await c.get("api/v1/challenge/", params={"limit": 0}) @@ -47,13 +79,11 @@ async def test_ranking_orders_by_score_desc( user, challenge, db_session: AsyncSession, - username_catalog, + semana, ): from app.users.models import User - ranking_username = next( - username for username in username_catalog if username.id != user.username_id - ) + ranking_nickname = "AdaLovelace4821" # 15 participantes com scores variados for i in range(15): @@ -67,9 +97,24 @@ async def test_ranking_orders_by_score_desc( db_session.add(u) await db_session.flush() if i == 14: - u.username_id = ranking_username.id + semana_participant = SemanaParticipant( + user_id=u.id, + semana_id=semana.id, + nickname=ranking_nickname, + ) + db_session.add(semana_participant) + await db_session.flush() + else: + semana_participant = None db_session.add( - ChallengeParticipant(user_id=u.id, challenge_id=challenge.id, score=i * 10) + ChallengeParticipant( + user_id=u.id, + challenge_id=challenge.id, + score=i * 10, + semana_participant_id=( + semana_participant.id if semana_participant is not None else None + ), + ) ) await db_session.flush() @@ -81,4 +126,4 @@ async def test_ranking_orders_by_score_desc( scores = [p["score"] for p in ranking] assert scores == sorted(scores, reverse=True) assert scores[0] == 140 - assert ranking[0]["nickname"] == ranking_username.nickname + assert ranking[0]["nickname"] == ranking_nickname diff --git a/backend/app/tests/challenges/integration/test_manual_challenges.py b/backend/app/tests/challenges/integration/test_manual_challenges.py index 808a8ca9..163ffd28 100644 --- a/backend/app/tests/challenges/integration/test_manual_challenges.py +++ b/backend/app/tests/challenges/integration/test_manual_challenges.py @@ -10,7 +10,6 @@ async def test_manual_challenge_cannot_be_submitted( as_user, user, manual_challenge, - username_catalog, ): c = as_user(user) r = await c.post(f"api/v1/challenge/{manual_challenge.id}/join") @@ -26,6 +25,6 @@ async def test_manual_challenge_cannot_receive_questions( c = as_user(admin) r = await c.patch( f"api/v1/admin/challenge/{manual_challenge.id}", - json={"questions": [{"prompt": "?", "answer": "!", "points_value": 10}]}, + json={"questions": [{"prompt": "?", "answer": "!"}]}, ) assert r.status_code == 400 diff --git a/backend/app/tests/challenges/integration/test_quiz_lifecycle.py b/backend/app/tests/challenges/integration/test_quiz_lifecycle.py index 99de8396..b01897ff 100644 --- a/backend/app/tests/challenges/integration/test_quiz_lifecycle.py +++ b/backend/app/tests/challenges/integration/test_quiz_lifecycle.py @@ -2,9 +2,116 @@ from __future__ import annotations +import re from datetime import UTC, datetime, timedelta from httpx import AsyncClient +from sqlalchemy import func, select + +from app.challenges.models.challenge import ChallengeScoringType +from app.challenges.models.challenge_participant import ChallengeParticipant +from app.challenges.models.input import Input +from app.semana.models import PointEvent, SemanaEvent, SemanaParticipant + + +async def test_input_challenge_scores_using_challenge_points( + client: AsyncClient, as_user, user, challenge, db_session +): + challenge.scoring_type = ChallengeScoringType.INPUT + challenge.points_value = 40 + challenge.input = Input(prompt="Answer?", input_answer="correct") + await db_session.flush() + + c = as_user(user) + joined = await c.post(f"api/v1/challenge/{challenge.id}/join") + assert joined.status_code == 200, joined.text + + response = await c.post( + f"api/v1/challenge/{challenge.id}/input", json={"answer": "incorrect"} + ) + + assert response.status_code == 200, response.text + assert response.json() == {"submitted_at": None, "score": 0} + + challenge_state = await c.get(f"api/v1/challenge/{challenge.id}") + assert challenge_state.status_code == 200, challenge_state.text + assert challenge_state.json()["submitted_at"] is None + assert "input_answer" not in challenge_state.json() + + participant = await db_session.scalar( + select(ChallengeParticipant).where( + ChallengeParticipant.user_id == user.id, + ChallengeParticipant.challenge_id == challenge.id, + ) + ) + assert participant is not None + assert ( + await db_session.scalar( + select(func.count(PointEvent.id)).where( + PointEvent.source_type == "challenge", + PointEvent.source_id == participant.id, + ) + ) + == 0 + ) + + correct_response = await c.post( + f"api/v1/challenge/{challenge.id}/input", json={"answer": "correct"} + ) + assert correct_response.status_code == 200, correct_response.text + assert correct_response.json()["score"] == 40 + assert correct_response.json()["submitted_at"] is not None + + challenge_state = await c.get(f"api/v1/challenge/{challenge.id}") + assert ( + challenge_state.json()["submitted_at"] + == correct_response.json()["submitted_at"] + ) + assert challenge_state.json()["score"] == 40 + + repeated_response = await c.post( + f"api/v1/challenge/{challenge.id}/input", json={"answer": "incorrect"} + ) + assert repeated_response.status_code == 200, repeated_response.text + assert repeated_response.json() == correct_response.json() + assert ( + await db_session.scalar( + select(func.count(PointEvent.id)).where( + PointEvent.source_type == "challenge", + PointEvent.source_id == participant.id, + ) + ) + == 1 + ) + + challenge.finishes_at = datetime.now(UTC) - timedelta(seconds=1) + await db_session.flush() + expired_retry = await c.post( + f"api/v1/challenge/{challenge.id}/input", json={"answer": "incorrect"} + ) + assert expired_retry.status_code == 200 + assert expired_retry.json() == correct_response.json() + + +async def test_input_submission_is_rejected_after_challenge_expires( + client: AsyncClient, as_user, user, challenge, db_session +): + challenge.scoring_type = ChallengeScoringType.INPUT + challenge.input = Input(prompt="Answer?", input_answer="correct") + await db_session.flush() + + c = as_user(user) + joined = await c.post(f"api/v1/challenge/{challenge.id}/join") + assert joined.status_code == 200, joined.text + + challenge.finishes_at = datetime.now(UTC) - timedelta(seconds=1) + await db_session.flush() + + response = await c.post( + f"api/v1/challenge/{challenge.id}/input", json={"answer": "incorrect"} + ) + + assert response.status_code == 409 async def test_full_quiz_lifecycle( @@ -13,7 +120,7 @@ async def test_full_quiz_lifecycle( user, challenge, questions, - username_catalog, + db_session, ): c = as_user(user) @@ -59,24 +166,134 @@ async def test_full_quiz_lifecycle( assert answers_by_qid[str(questions[1].id)] == "9" assert answers_by_qid[str(questions[2].id)] == "Rio" - # 5. Submit + # 5. Submit with one incorrect answer; retry remains available. r = await c.post(f"api/v1/challenge/{challenge.id}/submit") assert r.status_code == 200, r.text body = r.json() - assert body["score"] == 150 # 100 + 50 + assert body["score"] == 150 + assert body["submitted_at"] is None + + participant = await db_session.scalar( + select(ChallengeParticipant).where( + ChallengeParticipant.user_id == user.id, + ChallengeParticipant.challenge_id == challenge.id, + ) + ) + assert participant is not None + assert ( + await db_session.scalar( + select(func.count(PointEvent.id)).where( + PointEvent.source_type == "challenge", + PointEvent.source_id == participant.id, + ) + ) + == 0 + ) + + retry = await c.post( + f"api/v1/challenge/{challenge.id}/answer", + json={"question_id": str(questions[2].id), "answer": "Brasília"}, + ) + assert retry.status_code == 204 + + completed = await c.post(f"api/v1/challenge/{challenge.id}/submit") + assert completed.status_code == 200, completed.text + body = completed.json() + assert body["score"] == 225 assert body["submitted_at"] is not None + completed_details = await c.get(f"api/v1/challenge/{challenge.id}") + assert completed_details.json()["submitted_at"] == body["submitted_at"] + assert completed_details.json()["score"] == 225 + + blocked_edit = await c.post( + f"api/v1/challenge/{challenge.id}/answer", + json={"question_id": str(questions[2].id), "answer": "Rio"}, + ) + assert blocked_edit.status_code == 400 + # 6. Submit de novo → idempotente r2 = await c.post(f"api/v1/challenge/{challenge.id}/submit") assert r2.status_code == 200 assert r2.json() == body + assert ( + await db_session.scalar( + select(func.count(PointEvent.id)).where( + PointEvent.source_type == "challenge", + PointEvent.source_id == participant.id, + ) + ) + == 1 + ) # 7. Ranking r = await c.get(f"api/v1/challenge/{challenge.id}/ranking") assert r.status_code == 200 ranking = r.json() assert len(ranking) == 1 - assert ranking[0]["score"] == 150 + assert ranking[0]["score"] == 225 + + +async def test_quiz_submission_is_rejected_after_challenge_expires( + client: AsyncClient, as_user, user, challenge, db_session +): + c = as_user(user) + joined = await c.post(f"api/v1/challenge/{challenge.id}/join") + assert joined.status_code == 200, joined.text + + challenge.finishes_at = datetime.now(UTC) - timedelta(seconds=1) + await db_session.flush() + + response = await c.post(f"api/v1/challenge/{challenge.id}/submit") + + assert response.status_code == 409 + + +async def test_future_quiz_rejects_join_answer_and_submission( + client: AsyncClient, + as_user, + user, + challenge, + questions, + db_session, +): + challenge.starts_at = datetime.now(UTC) + timedelta(days=1) + participant = ChallengeParticipant(user_id=user.id, challenge_id=challenge.id) + db_session.add(participant) + await db_session.flush() + + c = as_user(user) + joined = await c.post(f"api/v1/challenge/{challenge.id}/join") + answer = await c.post( + f"api/v1/challenge/{challenge.id}/answer", + json={"question_id": str(questions[0].id), "answer": "4"}, + ) + answers = await c.post( + f"api/v1/challenge/{challenge.id}/answer/all", + json=[{"question_id": str(questions[0].id), "answer": "4"}], + ) + submission = await c.post(f"api/v1/challenge/{challenge.id}/submit") + + assert joined.status_code == 409 + assert answer.status_code == 409 + assert answers.status_code == 409 + assert submission.status_code == 409 + + +async def test_future_input_rejects_submission( + client: AsyncClient, as_user, user, challenge, db_session +): + challenge.starts_at = datetime.now(UTC) + timedelta(days=1) + challenge.scoring_type = ChallengeScoringType.INPUT + challenge.input = Input(prompt="Answer?", input_answer="correct") + db_session.add(ChallengeParticipant(user_id=user.id, challenge_id=challenge.id)) + await db_session.flush() + + response = await as_user(user).post( + f"api/v1/challenge/{challenge.id}/input", json={"answer": "correct"} + ) + + assert response.status_code == 409 async def test_answering_without_joining_returns_400( @@ -90,13 +307,12 @@ async def test_answering_without_joining_returns_400( assert r.status_code == 400 -async def test_username_is_reused_across_challenge_joins( +async def test_nickname_is_reused_across_challenge_joins( client: AsyncClient, as_user, user, challenge, manual_challenge, - username_catalog, ): c = as_user(user) @@ -105,12 +321,38 @@ async def test_username_is_reused_across_challenge_joins( assert first_join.status_code == 200, first_join.text assert second_join.status_code == 200, second_join.text - assert first_join.json()["nickname"] in { - username.nickname for username in username_catalog - } + assert len(first_join.json()["nickname"]) > 0 + assert re.fullmatch(r"[A-Za-z]+\d{4}", first_join.json()["nickname"]) assert second_join.json()["nickname"] == first_join.json()["nickname"] +async def test_profile_returns_the_nickname_for_each_week( + client: AsyncClient, as_user, user, challenge, db_session +): + c = as_user(user) + joined = await c.post(f"api/v1/challenge/{challenge.id}/join") + assert joined.status_code == 200, joined.text + + other_week = SemanaEvent(nome="Outra Semana", ano=2025) + db_session.add(other_week) + await db_session.flush() + db_session.add( + SemanaParticipant( + semana_id=other_week.id, + user_id=user.id, + nickname="OutraPessoa2025", + ) + ) + await db_session.flush() + + response = await c.get("/api/v1/semanas/participacao") + + assert response.status_code == 200, response.text + weeks = {week["semana_id"]: week for week in response.json()["semanas"]} + assert weeks[challenge.semana_id]["nickname"] == joined.json()["nickname"] + assert weeks[other_week.id]["nickname"] == "OutraPessoa2025" + + async def test_submitting_without_joining_returns_400( client: AsyncClient, as_user, user, challenge ): @@ -125,14 +367,11 @@ async def test_submitting_question_from_other_challenge_returns_404( user, challenge, manual_challenge, - username_catalog, db_session, ): from app.challenges.models.question import Question - q = Question( - prompt="?", answer="?", points_value=10, challenge_id=manual_challenge.id - ) + q = Question(prompt="?", answer="?", challenge_id=manual_challenge.id) db_session.add(q) await db_session.flush() @@ -147,7 +386,7 @@ async def test_submitting_question_from_other_challenge_returns_404( async def test_bulk_save_answers( - client: AsyncClient, as_user, user, challenge, questions, username_catalog + client: AsyncClient, as_user, user, challenge, questions ): c = as_user(user) await c.post(f"api/v1/challenge/{challenge.id}/join") @@ -169,7 +408,6 @@ async def test_expired_challenge_rejects_single_and_bulk_answers( user, challenge, questions, - username_catalog, db_session, ): c = as_user(user) @@ -200,7 +438,6 @@ async def test_expired_challenge_rejects_new_submission( as_user, user, challenge, - username_catalog, db_session, ): c = as_user(user) @@ -222,13 +459,23 @@ async def test_existing_submission_remains_idempotent_after_deadline( as_user, user, challenge, - username_catalog, + questions, db_session, ): c = as_user(user) - await c.post(f"api/v1/challenge/{challenge.id}/join") + joined = await c.post(f"api/v1/challenge/{challenge.id}/join") + assert joined.status_code == 200, joined.text + saved_answers = await c.post( + f"api/v1/challenge/{challenge.id}/answer/all", + json=[ + {"question_id": str(question.id), "answer": question.answer} + for question in questions + ], + ) + assert saved_answers.status_code == 204 first_response = await c.post(f"api/v1/challenge/{challenge.id}/submit") assert first_response.status_code == 200 + assert first_response.json()["submitted_at"] is not None challenge.finishes_at = datetime.now(UTC) - timedelta(seconds=1) await db_session.flush() diff --git a/backend/app/tests/challenges/integration/test_soft_delete_leaks.py b/backend/app/tests/challenges/integration/test_soft_delete_leaks.py index e31bee00..caf29656 100644 --- a/backend/app/tests/challenges/integration/test_soft_delete_leaks.py +++ b/backend/app/tests/challenges/integration/test_soft_delete_leaks.py @@ -17,7 +17,6 @@ async def test_deleted_answer_does_not_appear_in_get_challenge( user, challenge, questions, - username_catalog, db_session: AsyncSession, ): c = as_user(user) @@ -55,7 +54,6 @@ async def test_deleted_answer_not_counted_on_submit( user, challenge, questions, - username_catalog, db_session: AsyncSession, ): c = as_user(user) @@ -90,4 +88,4 @@ async def test_deleted_answer_not_counted_on_submit( await db_session.flush() r = await c.post(f"api/v1/challenge/{challenge.id}/submit") - assert r.json()["score"] == 100, "resposta deletada somou pontos" + assert r.json()["score"] == 75, "resposta deletada somou pontos" diff --git a/backend/app/tests/challenges/unit/test_answer_upsert.py b/backend/app/tests/challenges/unit/test_answer_upsert.py index d3fcc262..130bfce7 100644 --- a/backend/app/tests/challenges/unit/test_answer_upsert.py +++ b/backend/app/tests/challenges/unit/test_answer_upsert.py @@ -66,9 +66,7 @@ async def test_upsert_rejects_question_from_other_challenge( """Pergunta não pertence ao challenge do participante → NotFoundError.""" from app.challenges.models.question import Question - foreign_q = Question( - prompt="?", answer="?", points_value=10, challenge_id=manual_challenge.id - ) + foreign_q = Question(prompt="?", answer="?", challenge_id=manual_challenge.id) db_session.add(foreign_q) await db_session.flush() diff --git a/backend/app/tests/challenges/unit/test_scoring.py b/backend/app/tests/challenges/unit/test_scoring.py index d2276ede..3ad8d713 100644 --- a/backend/app/tests/challenges/unit/test_scoring.py +++ b/backend/app/tests/challenges/unit/test_scoring.py @@ -23,6 +23,7 @@ async def _make_participant( async def test_process_submission_sums_only_correct_answers( db_session: AsyncSession, user, challenge, questions ): + challenge.points_value = 225 participant = await _make_participant(db_session, user.id, challenge.id) # Duas corretas, uma errada @@ -50,11 +51,13 @@ async def test_process_submission_sums_only_correct_answers( ) await db_session.flush() - score = await challenge_service.process_submission(db_session, participant) + score = await challenge_service.process_submission( + db_session, participant, challenge + ) - assert score == 150 # 100 + 50 + assert score == 150 assert participant.score == 150 - assert participant.submitted_at is not None + assert participant.submitted_at is None async def test_process_submission_ignores_deleted_answers( @@ -62,6 +65,7 @@ async def test_process_submission_ignores_deleted_answers( ): from datetime import UTC, datetime + challenge.points_value = 225 participant = await _make_participant(db_session, user.id, challenge.id) correct = Answer( @@ -80,15 +84,19 @@ async def test_process_submission_ignores_deleted_answers( db_session.add_all([correct, deleted_correct]) await db_session.flush() - score = await challenge_service.process_submission(db_session, participant) + score = await challenge_service.process_submission( + db_session, participant, challenge + ) - assert score == 100 + assert score == 75 async def test_process_submission_zero_when_no_answers( db_session: AsyncSession, user, challenge ): participant = await _make_participant(db_session, user.id, challenge.id) - score = await challenge_service.process_submission(db_session, participant) + score = await challenge_service.process_submission( + db_session, participant, challenge + ) assert score == 0 assert participant.score == 0 diff --git a/backend/app/tests/conftest.py b/backend/app/tests/conftest.py index 96970791..2c482d8a 100644 --- a/backend/app/tests/conftest.py +++ b/backend/app/tests/conftest.py @@ -1,4 +1,3 @@ -import uuid from datetime import UTC, datetime from shutil import rmtree @@ -9,10 +8,17 @@ from app.core.config import Settings, get_settings from app.core.database import get_session +from app.core.rate_limit import RateLimitMiddleware from app.main import app from app.users import services as user_services from app.users.schemas import UserCreate -from app.users.username.models import Username, UsernameMother + + +@pytest.fixture(autouse=True) +def reset_rate_limits(): + RateLimitMiddleware.reset_all() + yield + RateLimitMiddleware.reset_all() @pytest.fixture @@ -27,11 +33,28 @@ def jwt_settings(test_settings: Settings) -> Settings: return test_settings +@pytest.fixture(autouse=True) +def reset_rate_limit_state(): + middleware = app.middleware_stack + if middleware is None: + middleware = app.build_middleware_stack() + app.middleware_stack = middleware + + while middleware is not None: + if isinstance(middleware, RateLimitMiddleware): + middleware.requests.clear() + break + middleware = getattr(middleware, "app", None) + + @pytest_asyncio.fixture async def db_session(test_settings: Settings): engine = create_async_engine(str(test_settings.database_url)) TestingSessionLocal = async_sessionmaker( - bind=engine, class_=AsyncSession, expire_on_commit=False + bind=engine, + class_=AsyncSession, + expire_on_commit=False, + join_transaction_mode="create_savepoint", ) async with engine.connect() as connection: transaction = await connection.begin() @@ -72,7 +95,7 @@ def override_get_settings(): @pytest.fixture -def user_factory(db_session: AsyncSession, username_catalog): +def user_factory(db_session: AsyncSession): async def _make( email: str = "factory-user@example.com", name: str = "Factory User", @@ -100,38 +123,6 @@ async def _make( return _make -def _make_username_mother() -> UsernameMother: - return UsernameMother( - first_name="Maria", - last_name="Silva", - full_name=f"Maria Silva {uuid.uuid4().hex[:6]}", - description="Mãe de teste", - ) - - -def _make_username( - first_mother: UsernameMother, last_mother: UsernameMother -) -> Username: - return Username( - nickname=f"nick-{uuid.uuid4().hex[:10]}", - first_mother_id=first_mother.id, - last_mother_id=last_mother.id, - ) - - -@pytest.fixture -async def username_catalog(db_session: AsyncSession) -> list[Username]: - first_mother = _make_username_mother() - last_mother = _make_username_mother() - db_session.add_all([first_mother, last_mother]) - await db_session.flush() - - usernames = [_make_username(first_mother, last_mother) for _ in range(5)] - db_session.add_all(usernames) - await db_session.flush() - return usernames - - @pytest.fixture(autouse=True) def cleanup_generated_challenge_images(): settings = get_settings() diff --git a/backend/app/tests/semana/unit/test_seed_semana_data.py b/backend/app/tests/semana/unit/test_seed_semana_data.py new file mode 100644 index 00000000..03a76062 --- /dev/null +++ b/backend/app/tests/semana/unit/test_seed_semana_data.py @@ -0,0 +1,442 @@ +import csv +from contextlib import asynccontextmanager +from datetime import UTC, datetime +from types import SimpleNamespace +from zoneinfo import ZoneInfo + +import pytest + +from app.core.config import AppEnv, Settings +from app.semana.models import Semana +from scripts import seed_semana_data + +TSV_COLUMNS = [ + "Título da atividade", + "Descrição da atividade", + "Tipo de Atividade", + "Horas", + "Pontos", + "Localização", + "Horário Começo", + "Horário Término", + "Nomes dos palestrantes", + "Arquivos de Imagem", + "Descrições dos palestrantes", +] +VALID_ROW = { + "Título da atividade": "Test activity", + "Descrição da atividade": "Test description", + "Tipo de Atividade": "Palestra", + "Horas": "1", + "Pontos": "100", + "Localização": "Auditório", + "Horário Começo": "06/10/2026 13:00:00", + "Horário Término": "06/10/2026 14:00:00", + "Nomes dos palestrantes": "Test Speaker", + "Arquivos de Imagem": "speaker.jpg", + "Descrições dos palestrantes": "Test biography", +} + + +def write_schedule( + monkeypatch, tmp_path, rows, *, image_files=("speaker.jpg",), columns=None +): + image_dir = tmp_path / "imagens_palestrantes" + image_dir.mkdir(exist_ok=True) + for image_name in image_files: + image_path = image_dir / image_name + image_path.parent.mkdir(parents=True, exist_ok=True) + image_path.write_bytes(b"test image") + + schedule_path = tmp_path / "palestras.tsv" + fieldnames = columns or TSV_COLUMNS + with schedule_path.open("w", encoding="utf-8", newline="") as file: + writer = csv.DictWriter(file, fieldnames=fieldnames, delimiter="\t") + writer.writeheader() + writer.writerows(rows) + + monkeypatch.setattr(seed_semana_data, "SCHEDULE_FILE", schedule_path) + monkeypatch.setattr(seed_semana_data, "SPEAKER_IMAGES_DIR", image_dir) + + +def image_signature_matches_extension(path): + header = path.read_bytes()[:12] + suffix = path.suffix.lower() + if suffix in {".jpg", ".jpeg"}: + return header.startswith(b"\xff\xd8\xff") + if suffix == ".png": + return header.startswith(b"\x89PNG\r\n\x1a\n") + if suffix == ".webp": + return header.startswith(b"RIFF") and header[8:12] == b"WEBP" + return False + + +def test_load_schedule_reads_activities_and_speaker_photos(): + schedule = seed_semana_data.load_schedule() + + assert len(schedule) == 17 + speakers = [speaker for item in schedule for speaker in item["speakers"]] + assert len(speakers) == 20 + assert all( + speaker["nome"].strip() and speaker["sobre"].strip() for speaker in speakers + ) + assert all(speaker["image_path"].is_file() for speaker in speakers) + assert all( + speaker["image_path"].suffix.lower() + in seed_semana_data.SUPPORTED_IMAGE_EXTENSIONS + for speaker in speakers + ) + assert all( + 0 < speaker["image_path"].stat().st_size <= seed_semana_data.MAX_IMAGE_BYTES + for speaker in speakers + ) + image_paths = [speaker["image_path"].resolve() for speaker in speakers] + assert all(image_signature_matches_extension(path) for path in image_paths) + assert len(image_paths) == len(set(image_paths)) + referenced_images = set(image_paths) + supported_files = { + path.resolve() + for path in seed_semana_data.SPEAKER_IMAGES_DIR.iterdir() + if path.is_file() + and path.suffix.lower() in seed_semana_data.SUPPORTED_IMAGE_EXTENSIONS + } + assert referenced_images == supported_files + + tako_activity = next( + item for item in schedule if item["titulo"].startswith("Como a Tako") + ) + tako_images = { + speaker["nome"]: speaker["image_path"].name + for speaker in tako_activity["speakers"] + } + assert tako_images == { + "Bruno Cerejo": "bruno-cerejo.jpeg", + "André Spanguero": "andre-spanguero.jpg", + } + + +def test_schedule_rows_are_unique_valid_and_non_overlapping_by_location(): + schedule = seed_semana_data.load_schedule() + titles = [item["titulo"] for item in schedule] + + assert all(title and len(title) <= 255 for title in titles) + assert len(titles) == len(set(titles)) + for item in schedule: + assert item["comeca_as"].tzinfo == ZoneInfo("America/Sao_Paulo") + assert item["comeca_as"].year == item["termina_as"].year == 2026 + assert item["comeca_as"].month == item["termina_as"].month == 10 + assert 5 <= item["comeca_as"].day <= 9 + assert item["termina_as"] > item["comeca_as"] + assert item["horas"] >= 1 + assert item["pontos"] >= 0 + assert item["descricao"] is None or len(item["descricao"]) <= 5000 + assert item["local"] is None or len(item["local"]) <= 255 + + for index, first in enumerate(schedule): + for second in schedule[index + 1 :]: + if first["local"] and first["local"] == second["local"]: + assert ( + first["termina_as"] <= second["comeca_as"] + or second["termina_as"] <= first["comeca_as"] + ), (first["titulo"], second["titulo"]) + + +@pytest.mark.parametrize( + ("overrides", "images", "message"), + [ + ( + { + "Nomes dos palestrantes": "Speaker One|Speaker Two", + "Descrições dos palestrantes": "Bio one|Bio two", + }, + ("speaker.jpg",), + "Speaker columns have different counts", + ), + ({"Arquivos de Imagem": ""}, (), "Speaker image is missing"), + ( + {"Descrições dos palestrantes": ""}, + ("speaker.jpg",), + "Speaker bio is missing", + ), + ({"Nomes dos palestrantes": ""}, ("speaker.jpg",), "Speaker name is missing"), + ( + {"Arquivos de Imagem": "speaker.heic"}, + ("speaker.heic",), + "Unsupported speaker image type", + ), + ({"Arquivos de Imagem": "missing.jpg"}, (), "Speaker image not found"), + ({"Arquivos de Imagem": "../speaker.jpg"}, (), "Invalid speaker image path"), + ], +) +def test_load_schedule_rejects_invalid_speaker_data( + monkeypatch, tmp_path, overrides, images, message +): + row = {**VALID_ROW, **overrides} + write_schedule(monkeypatch, tmp_path, [row], image_files=images) + + with pytest.raises((ValueError, FileNotFoundError), match=message): + seed_semana_data.load_schedule() + + +@pytest.mark.parametrize( + ("overrides", "message"), + [ + ({"Tipo de Atividade": "Coffee break"}, "Invalid title or activity type"), + ({"Horário Término": "06/10/2026 13:00:00"}, "Invalid schedule"), + ({"Horário Começo": "06/10/2025 13:00:00"}, "outside the 2026 event"), + ({"Horas": "0"}, "Invalid hours or points"), + ({"Pontos": "-1"}, "Invalid hours or points"), + ({"Pontos": "one hundred"}, "Invalid date or numeric value"), + ({"Título da atividade": "T" * 256}, "Activity title is too long"), + ({"Descrição da atividade": "D" * 5001}, "Description is too long"), + ({"Localização": "L" * 256}, "Location is too long"), + ], +) +def test_load_schedule_rejects_invalid_activity_fields( + monkeypatch, tmp_path, overrides, message +): + write_schedule(monkeypatch, tmp_path, [{**VALID_ROW, **overrides}]) + + with pytest.raises(ValueError, match=message): + seed_semana_data.load_schedule() + + +def test_load_schedule_rejects_duplicate_titles(monkeypatch, tmp_path): + write_schedule(monkeypatch, tmp_path, [VALID_ROW, VALID_ROW]) + + with pytest.raises(ValueError, match="Duplicate activity title"): + seed_semana_data.load_schedule() + + +def test_load_schedule_rejects_missing_columns(monkeypatch, tmp_path): + columns = TSV_COLUMNS[:-1] + row = {key: value for key, value in VALID_ROW.items() if key in columns} + write_schedule(monkeypatch, tmp_path, [row], columns=columns) + + with pytest.raises(ValueError, match="Unexpected columns"): + seed_semana_data.load_schedule() + + +def test_load_schedule_rejects_duplicate_columns(monkeypatch, tmp_path): + columns = [*TSV_COLUMNS, "Título da atividade"] + write_schedule(monkeypatch, tmp_path, [VALID_ROW], columns=columns) + + with pytest.raises(ValueError, match="Duplicate columns"): + seed_semana_data.load_schedule() + + +@pytest.mark.parametrize("row_width", [len(TSV_COLUMNS) - 1, len(TSV_COLUMNS) + 1]) +def test_load_schedule_rejects_malformed_row_width(monkeypatch, tmp_path, row_width): + image_dir = tmp_path / "imagens_palestrantes" + image_dir.mkdir() + (image_dir / "speaker.jpg").write_bytes(b"test image") + schedule_path = tmp_path / "palestras.tsv" + values = [VALID_ROW[column] for column in TSV_COLUMNS] + values = values[:row_width] if row_width < len(values) else [*values, "unexpected"] + with schedule_path.open("w", encoding="utf-8", newline="") as file: + file.write("\t".join(TSV_COLUMNS) + "\n") + file.write("\t".join(values) + "\n") + + monkeypatch.setattr(seed_semana_data, "SCHEDULE_FILE", schedule_path) + monkeypatch.setattr(seed_semana_data, "SPEAKER_IMAGES_DIR", image_dir) + + with pytest.raises(ValueError, match="Invalid number of columns"): + seed_semana_data.load_schedule() + + +def test_load_schedule_rejects_oversized_image(monkeypatch, tmp_path): + write_schedule(monkeypatch, tmp_path, [VALID_ROW]) + image_path = seed_semana_data.SPEAKER_IMAGES_DIR / "speaker.jpg" + image_path.write_bytes(b"x" * (seed_semana_data.MAX_IMAGE_BYTES + 1)) + + with pytest.raises(ValueError, match="invalid size"): + seed_semana_data.load_schedule() + + +def test_load_schedule_rejects_empty_file(monkeypatch, tmp_path): + write_schedule(monkeypatch, tmp_path, []) + + with pytest.raises(ValueError, match="No activities found"): + seed_semana_data.load_schedule() + + +@pytest.mark.asyncio +async def test_main_runs_in_production_and_is_additive_on_repeated_runs( + monkeypatch, tmp_path +): + event_state = {"event": Semana(id=2026, nome="Edited event name", ano=2026)} + manually_edited = SimpleNamespace(titulo="Existing activity", descricao="Edited") + activities = [manually_edited] + created = [] + saved_images = [] + image_path = tmp_path / "speaker.jpg" + image_path.write_bytes(b"test image") + seed_item = { + "titulo": "New activity", + "tipo": seed_semana_data.TipoAtividade.PALESTRA, + "descricao": "Initial description", + "local": "Auditorium", + "comeca_as": datetime(2026, 10, 6, 10, tzinfo=UTC), + "termina_as": datetime(2026, 10, 6, 11, tzinfo=UTC), + "pontos": 100, + "horas": 1, + "speakers": [{"nome": "Speaker", "sobre": "Bio", "image_path": image_path}], + } + existing_seed_item = { + **seed_item, + "titulo": "Existing activity", + "descricao": "Do not overwrite this", + } + + class FakeSession: + def add(self, value): + event_state["event"] = value + + async def flush(self): + pass + + async def scalar(self, _statement): + return event_state["event"] + + async def scalars(self, _statement): + return SimpleNamespace(all=lambda: list(activities)) + + session = FakeSession() + + @asynccontextmanager + async def fake_session_scope(_settings): + yield session + + async def fake_save_bytes(contents, *, subdir, extension): + saved_images.append((contents, subdir, extension)) + return "palestrantes/speaker.jpg" + + async def fake_create_atividade(_session, _event, **fields): + activity = SimpleNamespace( + titulo=fields["titulo"], + descricao=fields["descricao"], + palestrantes=fields["palestrantes"], + ) + activities.append(activity) + created.append(activity) + return activity + + monkeypatch.setattr( + seed_semana_data, "get_settings", lambda: Settings(app_env=AppEnv.production) + ) + monkeypatch.setattr( + seed_semana_data, + "load_schedule", + lambda: [existing_seed_item, seed_item], + ) + monkeypatch.setattr(seed_semana_data, "session_scope", fake_session_scope) + monkeypatch.setattr(seed_semana_data, "save_bytes", fake_save_bytes) + monkeypatch.setattr(seed_semana_data, "create_atividade", fake_create_atividade) + + await seed_semana_data.main() + await seed_semana_data.main() + + assert len(created) == 1 + assert manually_edited.descricao == "Edited" + assert len(activities) == 2 + assert event_state["event"].nome == "Edited event name" + assert event_state["event"].ano == 2026 + assert created[0].palestrantes == [ + { + "nome": "Speaker", + "sobre": "Bio", + "foto": "/media/palestrantes/speaker.jpg", + } + ] + assert saved_images == [(b"test image", "palestrantes", "jpg")] + + +@pytest.mark.asyncio +async def test_main_deletes_saved_media_when_activity_creation_fails( + monkeypatch, tmp_path +): + event = Semana(id=2026, nome="Semana da Computação", ano=2026) + image_path = tmp_path / "speaker.jpg" + image_path.write_bytes(b"test image") + item = { + "titulo": "Activity", + "descricao": "Description", + "tipo": seed_semana_data.TipoAtividade.PALESTRA, + "local": "Auditorium", + "comeca_as": datetime(2026, 10, 6, 10, tzinfo=UTC), + "termina_as": datetime(2026, 10, 6, 11, tzinfo=UTC), + "pontos": 100, + "horas": 1, + "speakers": [{"nome": "Speaker", "sobre": "Bio", "image_path": image_path}], + } + session = SimpleNamespace( + scalar=lambda _statement: None, + scalars=lambda _statement: None, + ) + + async def scalar(_statement): + return event + + async def scalars(_statement): + return SimpleNamespace(all=list) + + session.scalar = scalar + session.scalars = scalars + deleted_media = [] + + @asynccontextmanager + async def fake_session_scope(_settings): + yield session + + async def fake_save_bytes(_contents, *, subdir, extension): + return f"{subdir}/new.{extension}" + + async def fail_create_atividade(_session, _event, **_fields): + raise RuntimeError("database write failed") + + monkeypatch.setattr( + seed_semana_data, "get_settings", lambda: Settings(app_env=AppEnv.production) + ) + monkeypatch.setattr(seed_semana_data, "load_schedule", lambda: [item]) + monkeypatch.setattr(seed_semana_data, "session_scope", fake_session_scope) + monkeypatch.setattr(seed_semana_data, "save_bytes", fake_save_bytes) + monkeypatch.setattr(seed_semana_data, "create_atividade", fail_create_atividade) + monkeypatch.setattr(seed_semana_data, "delete_file", deleted_media.append) + + with pytest.raises(RuntimeError, match="database write failed"): + await seed_semana_data.main() + + assert deleted_media == ["palestrantes/new.jpg"] + + +@pytest.mark.asyncio +async def test_main_creates_missing_event_in_production(monkeypatch): + event_state = {"event": None} + + class FakeSession: + def add(self, value): + event_state["event"] = value + + async def flush(self): + pass + + async def scalar(self, _statement): + return event_state["event"] + + async def scalars(self, _statement): + return SimpleNamespace(all=list) + + @asynccontextmanager + async def fake_session_scope(_settings): + yield FakeSession() + + monkeypatch.setattr( + seed_semana_data, "get_settings", lambda: Settings(app_env=AppEnv.production) + ) + monkeypatch.setattr(seed_semana_data, "load_schedule", list) + monkeypatch.setattr(seed_semana_data, "session_scope", fake_session_scope) + + await seed_semana_data.main() + + assert event_state["event"].nome == "Semana da Computação 2026" + assert event_state["event"].ano == 2026 diff --git a/backend/app/tests/users/integration/test_user_routes.py b/backend/app/tests/users/integration/test_user_routes.py new file mode 100644 index 00000000..c2dfc802 --- /dev/null +++ b/backend/app/tests/users/integration/test_user_routes.py @@ -0,0 +1,188 @@ +"""Testes dos endpoints de usuário autenticado (/api/v1/user/me).""" + +from __future__ import annotations + +import pytest +from sqlalchemy.ext.asyncio import AsyncSession + +from app.auth import services as auth_services +from app.auth.scopes import Scope +from app.auth.security import verify_password + +URL = "/api/v1/user/me" + + +def _auth(user, scopes=(Scope.PROFILE, Scope.EMAIL)) -> dict[str, str]: + token = auth_services.create_access_token(user.id, list(scopes)) + return {"Authorization": f"Bearer {token}"} + + +# --------------------------------------------------------------------------- +# Proteção +# --------------------------------------------------------------------------- + + +async def test_update_name_without_authorization_returns_401(db_client): + r = await db_client.patch(URL, json={"name": "Novo Nome"}) + assert r.status_code == 401 + + +async def test_update_name_without_profile_scope_returns_401( + db_client, regular_user, db_session: AsyncSession +): + original_name = regular_user.name + + r = await db_client.patch( + URL, json={"name": "Novo Nome"}, headers=_auth(regular_user, [Scope.EMAIL]) + ) + + assert r.status_code == 401 + await db_session.refresh(regular_user) + assert regular_user.name == original_name + + +async def test_update_name_without_email_scope_returns_401( + db_client, regular_user, db_session: AsyncSession +): + original_name = regular_user.name + + r = await db_client.patch( + URL, json={"name": "Novo Nome"}, headers=_auth(regular_user, [Scope.PROFILE]) + ) + + assert r.status_code == 401 + await db_session.refresh(regular_user) + assert regular_user.name == original_name + + +async def test_update_name_of_deleted_user_returns_401(db_client, deleted_user_factory): + deleted = await deleted_user_factory() + + r = await db_client.patch(URL, json={"name": "Novo Nome"}, headers=_auth(deleted)) + + assert r.status_code == 401 + + +# --------------------------------------------------------------------------- +# Sucesso +# --------------------------------------------------------------------------- + + +async def test_user_can_update_own_name( + db_client, regular_user, db_session: AsyncSession +): + r = await db_client.patch( + URL, json={"name": "Ada Lovelace"}, headers=_auth(regular_user) + ) + + assert r.status_code == 200, r.text + body = r.json() + assert body["name"] == "Ada Lovelace" + assert body["id"] == str(regular_user.id) + assert body["email"] == regular_user.email + assert "password" not in body and "password_hash" not in body + + await db_session.refresh(regular_user) + assert regular_user.name == "Ada Lovelace" + + +async def test_updated_name_is_returned_by_me_endpoint(db_client, regular_user): + headers = _auth(regular_user) + + await db_client.patch(URL, json={"name": "Grace Hopper"}, headers=headers) + r = await db_client.get("/api/v1/auth/me", headers=headers) + + assert r.status_code == 200, r.text + assert r.json()["name"] == "Grace Hopper" + + +async def test_update_name_strips_surrounding_whitespace(db_client, regular_user): + r = await db_client.patch( + URL, json={"name": " Linus Torvalds "}, headers=_auth(regular_user) + ) + + assert r.status_code == 200, r.text + assert r.json()["name"] == "Linus Torvalds" + + +async def test_update_name_accepts_max_length(db_client, regular_user): + name = "a" * 255 + + r = await db_client.patch(URL, json={"name": name}, headers=_auth(regular_user)) + + assert r.status_code == 200, r.text + assert r.json()["name"] == name + + +async def test_update_name_does_not_change_other_fields( + db_client, regular_user, db_session: AsyncSession +): + email = regular_user.email + password_hash = regular_user.password_hash + + r = await db_client.patch( + URL, json={"name": "Outro Nome"}, headers=_auth(regular_user) + ) + + assert r.status_code == 200, r.text + await db_session.refresh(regular_user) + assert regular_user.email == email + assert regular_user.password_hash == password_hash + assert verify_password("password123", regular_user.password_hash) + assert regular_user.is_admin is False + assert regular_user.is_verified is False + + +# --------------------------------------------------------------------------- +# Validação +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "payload", + [ + {}, + {"name": None}, + {"name": ""}, + {"name": " "}, + {"name": "a" * 256}, + {"name": 123}, + ], +) +async def test_update_name_rejects_invalid_name( + db_client, regular_user, db_session: AsyncSession, payload +): + original_name = regular_user.name + + r = await db_client.patch(URL, json=payload, headers=_auth(regular_user)) + + assert r.status_code == 422 + await db_session.refresh(regular_user) + assert regular_user.name == original_name + + +@pytest.mark.parametrize( + "extra", + [ + {"email": "hacker@example.com"}, + {"password": "brand-new-pass"}, + {"is_admin": True}, + {"is_verified": True}, + ], +) +async def test_update_name_rejects_other_fields( + db_client, regular_user, db_session: AsyncSession, extra +): + email = regular_user.email + original_name = regular_user.name + + r = await db_client.patch( + URL, json={"name": "Novo Nome", **extra}, headers=_auth(regular_user) + ) + + assert r.status_code == 422 + await db_session.refresh(regular_user) + assert regular_user.email == email + assert regular_user.name == original_name + assert regular_user.is_admin is False + assert regular_user.is_verified is False diff --git a/backend/app/tests/users/unit/test_user_services.py b/backend/app/tests/users/unit/test_user_services.py index 1f811b50..52b92220 100644 --- a/backend/app/tests/users/unit/test_user_services.py +++ b/backend/app/tests/users/unit/test_user_services.py @@ -51,7 +51,7 @@ def test_verify_password_is_case_sensitive(): @pytest.mark.asyncio -async def test_create_user_service(db_session: AsyncSession, username_catalog): +async def test_create_user_service(db_session: AsyncSession): user_in = UserCreate( email="service_test@example.com", name="Service User", password="password123" ) @@ -63,7 +63,7 @@ async def test_create_user_service(db_session: AsyncSession, username_catalog): @pytest.mark.asyncio -async def test_get_user_by_id(db_session: AsyncSession, username_catalog): +async def test_get_user_by_id(db_session: AsyncSession): user_in = UserCreate( email="get_id@example.com", name="Get By ID", password="password123" ) @@ -75,7 +75,7 @@ async def test_get_user_by_id(db_session: AsyncSession, username_catalog): @pytest.mark.asyncio -async def test_get_user_by_email(db_session: AsyncSession, username_catalog): +async def test_get_user_by_email(db_session: AsyncSession): user_in = UserCreate( email="get_email@example.com", name="Get By Email", password="password123" ) @@ -89,7 +89,7 @@ async def test_get_user_by_email(db_session: AsyncSession, username_catalog): @pytest.mark.asyncio -async def test_update_user_service(db_session: AsyncSession, username_catalog): +async def test_update_user_service(db_session: AsyncSession): user_in = UserCreate( email="update@example.com", name="Old Name", password="password123" ) @@ -102,7 +102,7 @@ async def test_update_user_service(db_session: AsyncSession, username_catalog): @pytest.mark.asyncio -async def test_soft_delete_user_service(db_session: AsyncSession, username_catalog): +async def test_soft_delete_user_service(db_session: AsyncSession): user_in = UserCreate( email="delete@example.com", name="Delete Me", password="password123" ) @@ -115,9 +115,7 @@ async def test_soft_delete_user_service(db_session: AsyncSession, username_catal @pytest.mark.asyncio -async def test_create_user_with_existing_active_email_raises( - db_session: AsyncSession, username_catalog -): +async def test_create_user_with_existing_active_email_raises(db_session: AsyncSession): user_in = UserCreate( email="duplicate@example.com", name="First", password="password123" ) @@ -131,9 +129,7 @@ async def test_create_user_with_existing_active_email_raises( @pytest.mark.asyncio -async def test_delete_already_deleted_user_raises( - db_session: AsyncSession, username_catalog -): +async def test_delete_already_deleted_user_raises(db_session: AsyncSession): user_in = UserCreate( email="double_delete@example.com", name="Delete Twice", password="password123" ) @@ -146,9 +142,7 @@ async def test_delete_already_deleted_user_raises( @pytest.mark.asyncio -async def test_create_user_reactivates_soft_deleted_account( - db_session: AsyncSession, username_catalog -): +async def test_create_user_reactivates_soft_deleted_account(db_session: AsyncSession): # Cria, soft-deleta e depois recria com o mesmo e-mail: deve reativar a # conta antiga (mesmo id) em vez de criar um registro novo. user_in = UserCreate( diff --git a/backend/app/tests/users/username/unit/test_assignment.py b/backend/app/tests/users/username/unit/test_assignment.py deleted file mode 100644 index ad874958..00000000 --- a/backend/app/tests/users/username/unit/test_assignment.py +++ /dev/null @@ -1,108 +0,0 @@ -"""Testes de `assign_username`.""" - -from __future__ import annotations - -import pytest -from sqlalchemy.exc import IntegrityError -from sqlalchemy.ext.asyncio import AsyncSession - -from app.core.exceptions.app_errors import NotFoundError -from app.users.exceptions import NoAvailableUsername -from app.users.username import services as username_service - - -async def test_assigns_first_available_username( - db_session: AsyncSession, user_factory, username_catalog -): - user = await user_factory(email="username-first@example.com") - username = await username_service.assign_username(user.id, db_session) - - assert username.nickname in { - catalog_username.nickname for catalog_username in username_catalog - } - assert user.username_id == username.id - - -async def test_returns_existing_username_if_already_assigned( - db_session: AsyncSession, user_factory, username_catalog -): - user = await user_factory(email="username-existing@example.com") - user.username_id = username_catalog[0].id - await db_session.flush() - - username = await username_service.assign_username(user.id, db_session) - - assert username.id == username_catalog[0].id - - -async def test_username_cannot_be_assigned_to_multiple_users( - db_session: AsyncSession, username_catalog -): - import uuid - - from app.users.models import User - - user = User( - id=uuid.uuid4(), - email="username-owner@example.com", - name="Username Owner", - password_hash="x", - ) - other_user = User( - id=uuid.uuid4(), - email="username-other@example.com", - name="Username Other", - password_hash="x", - ) - db_session.add_all([user, other_user]) - await db_session.flush() - user.username_id = username_catalog[0].id - await db_session.flush() - - with pytest.raises(IntegrityError): - async with db_session.begin_nested(): - other_user.username_id = username_catalog[0].id - await db_session.flush() - - -async def test_raises_when_no_username_available( - db_session: AsyncSession, username_catalog -): - import uuid - - from app.users.models import User - - user = User( - id=uuid.uuid4(), - email="username-catalog-exhausted@example.com", - name="Catalog Exhausted", - password_hash="x", - ) - db_session.add(user) - await db_session.flush() - - # Assigns every catalog entry to a different user. - for i, u in enumerate(username_catalog): - dummy = User( - id=uuid.uuid4(), - email=f"dummy-{i}@t.local", - name=f"Dummy {i}", - password_hash="x", - is_verified=True, - ) - db_session.add(dummy) - await db_session.flush() - dummy.username_id = u.id - await db_session.flush() - - with pytest.raises(NoAvailableUsername): - await username_service.assign_username(user.id, db_session) - - -async def test_raises_when_user_does_not_exist( - db_session: AsyncSession, username_catalog -): - import uuid - - with pytest.raises(NotFoundError): - await username_service.assign_username(uuid.uuid4(), db_session) diff --git a/backend/app/tests/users/username/unit/test_seed.py b/backend/app/tests/users/username/unit/test_seed.py deleted file mode 100644 index b208c8fe..00000000 --- a/backend/app/tests/users/username/unit/test_seed.py +++ /dev/null @@ -1,208 +0,0 @@ -"""Testes do seed do catálogo de usernames.""" - -from __future__ import annotations - -import pytest -from sqlalchemy import func, select -from sqlalchemy.ext.asyncio import AsyncSession - -from app.users.username.models import Username, UsernameMother -from app.users.username.seed import ( - read_csv, - seed_from_csv_files, - seed_from_rows, -) - -# --------------------------------------------------------------------------- -# Dados base -# --------------------------------------------------------------------------- - - -MOTHERS = [ - {"first_name": "Maria", "last_name": "Silva", "description": "professora"}, - {"first_name": "Ana", "last_name": "Souza", "description": "astronauta"}, -] - -USERNAMES = [ - { - "nickname": "MariSilva", - "first_mome_full_name": "Maria Silva", - "last_mome_full_name": "Ana Souza", - }, - { - "nickname": "AnaSouza", - "first_mome_full_name": "Ana Souza", - "last_mome_full_name": "Maria Silva", - }, -] - - -async def _count(session: AsyncSession, model) -> int: - return await session.scalar(select(func.count()).select_from(model)) or 0 - - -# --------------------------------------------------------------------------- -# seed_from_rows -# --------------------------------------------------------------------------- - - -async def test_seed_inserts_all_rows(db_session): - n_mothers, n_usernames = await seed_from_rows(db_session, MOTHERS, USERNAMES) - - assert n_mothers == 2 - assert n_usernames == 2 - assert await _count(db_session, UsernameMother) == 2 - assert await _count(db_session, Username) == 2 - - -async def test_seed_is_idempotent(db_session): - first = await seed_from_rows(db_session, MOTHERS, USERNAMES) - second = await seed_from_rows(db_session, MOTHERS, USERNAMES) - - assert first == (2, 2) - assert second == (0, 0) # nada novo na segunda rodada - assert await _count(db_session, UsernameMother) == 2 - assert await _count(db_session, Username) == 2 - - -async def test_seed_partially_idempotent(db_session): - """Rodar com um catálogo parcialmente novo só insere o que falta.""" - await seed_from_rows(db_session, MOTHERS, USERNAMES) - - extended_mothers = MOTHERS + [ - {"first_name": "Joana", "last_name": "Lima", "description": "x"} - ] - extended_usernames = USERNAMES + [ - { - "nickname": "JoanaLima", - "first_mome_full_name": "Joana Lima", - "last_mome_full_name": "Maria Silva", - } - ] - - n_mothers, n_usernames = await seed_from_rows( - db_session, extended_mothers, extended_usernames - ) - - assert n_mothers == 1 - assert n_usernames == 1 - assert await _count(db_session, UsernameMother) == 3 - assert await _count(db_session, Username) == 3 - - -async def test_seed_raises_on_missing_mother(db_session): - """Falha ANTES de qualquer INSERT — nada é gravado.""" - bad_usernames = [ - { - "nickname": "X", - "first_mome_full_name": "Ninguém Silva", - "last_mome_full_name": "Maria Silva", - } - ] - - with pytest.raises(RuntimeError, match="mothers inexistentes"): - await seed_from_rows(db_session, MOTHERS, bad_usernames) - - assert await _count(db_session, UsernameMother) == 0 - assert await _count(db_session, Username) == 0 - - -async def test_seed_handles_empty_input(db_session): - """CSV vazio não deve estourar (insert com [] quebra no SQLAlchemy).""" - result = await seed_from_rows(db_session, [], []) - assert result == (0, 0) - assert await _count(db_session, UsernameMother) == 0 - assert await _count(db_session, Username) == 0 - - -async def test_seed_with_mothers_but_no_usernames(db_session): - result = await seed_from_rows(db_session, MOTHERS, []) - assert result == (2, 0) - assert await _count(db_session, UsernameMother) == 2 - assert await _count(db_session, Username) == 0 - - -async def test_seed_strips_whitespace(db_session): - mothers = [ - {"first_name": " Maria ", "last_name": " Silva ", "description": " x "} - ] - usernames = [ - { - "nickname": " nick ", - "first_mome_full_name": " Maria Silva ", - "last_mome_full_name": " Maria Silva ", - } - ] - - await seed_from_rows(db_session, mothers, usernames) - - m = await db_session.scalar(select(UsernameMother)) - assert m.first_name == "Maria" - assert m.last_name == "Silva" - assert m.full_name == "Maria Silva" - - u = await db_session.scalar(select(Username)) - assert u.nickname == "nick" - - -async def test_seed_dedupes_repeated_mothers(db_session): - """Mother duplicada no CSV só é inserida uma vez.""" - duplicated = MOTHERS + [MOTHERS[0]] # Maria Silva aparece 2x - - n_mothers, _ = await seed_from_rows(db_session, duplicated, USERNAMES) - - assert n_mothers == 2 - assert await _count(db_session, UsernameMother) == 2 - - -# --------------------------------------------------------------------------- -# read_csv / seed_from_csv_files -# --------------------------------------------------------------------------- - - -def test_read_csv(tmp_path): - path = tmp_path / "x.csv" - path.write_text("a,b\n1,2\n3,4\n", encoding="utf-8") - - assert read_csv(path) == [{"a": "1", "b": "2"}, {"a": "3", "b": "4"}] - - -async def test_seed_from_csv_files_end_to_end(db_session, tmp_path): - mothers_csv = tmp_path / "mothers.csv" - mothers_csv.write_text( - "first_name,last_name,description\nMaria,Silva,prof\nAna,Souza,astro\n", - encoding="utf-8", - ) - usernames_csv = tmp_path / "usernames.csv" - usernames_csv.write_text( - "nickname,first_mome_full_name,last_mome_full_name\n" - "MariSilva,Maria Silva,Ana Souza\n", - encoding="utf-8", - ) - - n_mothers, n_usernames = await seed_from_csv_files( - db_session, mothers_csv, usernames_csv - ) - - assert (n_mothers, n_usernames) == (2, 1) - - -async def test_seed_from_csv_files_fails_on_inconsistent_csv(db_session, tmp_path): - """CSV de usernames referencia mother que não existe no CSV de mothers.""" - mothers_csv = tmp_path / "mothers.csv" - mothers_csv.write_text( - "first_name,last_name,description\nMaria,Silva,prof\n", - encoding="utf-8", - ) - usernames_csv = tmp_path / "usernames.csv" - usernames_csv.write_text( - "nickname,first_mome_full_name,last_mome_full_name\nX,Joana Lima,Maria Silva\n", - encoding="utf-8", - ) - - with pytest.raises(RuntimeError, match="mothers inexistentes"): - await seed_from_csv_files(db_session, mothers_csv, usernames_csv) - - # Nada foi inserido - assert await _count(db_session, UsernameMother) == 0 - assert await _count(db_session, Username) == 0 diff --git a/backend/app/users/admin_router.py b/backend/app/users/admin_router.py index bbca33c5..a0751416 100644 --- a/backend/app/users/admin_router.py +++ b/backend/app/users/admin_router.py @@ -33,7 +33,13 @@ async def _get_user_or_404( return user -@router.post("/", response_model=UserRead, status_code=status.HTTP_201_CREATED) +@router.post("", response_model=UserRead, status_code=status.HTTP_201_CREATED) +@router.post( + "/", + response_model=UserRead, + include_in_schema=False, + status_code=status.HTTP_201_CREATED, +) async def create_user( session: Annotated[AsyncSession, Depends(get_session)], user_in: AdminUserCreate, @@ -45,7 +51,8 @@ async def create_user( return user -@router.get("/", response_model=Page[UserRead]) +@router.get("", response_model=Page[UserRead]) +@router.get("/", response_model=Page[UserRead], include_in_schema=False) async def list_users( session: Annotated[AsyncSession, Depends(get_session)], pagination: Annotated[PaginationParams, Depends()], diff --git a/backend/app/users/exceptions.py b/backend/app/users/exceptions.py index ed278958..566a1ad7 100644 --- a/backend/app/users/exceptions.py +++ b/backend/app/users/exceptions.py @@ -21,23 +21,3 @@ def __init__(self, email, headers: dict[str, str] | None = None): detail=f"User with email {email!r} already exists.", headers=headers, ) - - -class NoAvailableUsername(AppError): - def __init__(self) -> None: - super().__init__( - status_code=409, - type="no_available_username", - title="No available username", - detail="No usernames available for the user.", - ) - - -class CouldNotAssignUsernameError(AppError): - def __init__(self) -> None: - super().__init__( - status_code=500, - type="could_not_assign_username", - title="Could not assign username", - detail="Could not assign a username. Try again later.", - ) diff --git a/backend/app/users/models.py b/backend/app/users/models.py index 7ab30cdc..31452b18 100644 --- a/backend/app/users/models.py +++ b/backend/app/users/models.py @@ -1,17 +1,11 @@ from __future__ import annotations -import uuid -from typing import TYPE_CHECKING - -from sqlalchemy import Boolean, ForeignKey, String -from sqlalchemy.orm import Mapped, mapped_column, relationship +from sqlalchemy import Boolean, String, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column from app.core.mixins import TimestampsMixin, UUIDPKMixin from app.core.models import Base -if TYPE_CHECKING: - from app.users.username.models import Username - class User(Base, UUIDPKMixin, TimestampsMixin): """Conta de um participante da semana (login, perfil básico). @@ -24,6 +18,12 @@ class User(Base, UUIDPKMixin, TimestampsMixin): a partir do nome da classe ("User" -> "users"). """ + __table_args__ = ( + UniqueConstraint( + "oauth_provider", "oauth_subject", name="users_oauth_identity_key" + ), + ) + email: Mapped[str] = mapped_column( String(255), unique=True, index=True, nullable=False ) @@ -33,18 +33,15 @@ class User(Base, UUIDPKMixin, TimestampsMixin): # podem não ter senha própria. password_hash: Mapped[str | None] = mapped_column(String(255), nullable=True) + oauth_provider: Mapped[str | None] = mapped_column(String(16), nullable=True) + oauth_subject: Mapped[str | None] = mapped_column(String(255), nullable=True) + is_admin: Mapped[bool] = mapped_column( Boolean, nullable=False, default=False, server_default="false" ) is_verified: Mapped[bool] = mapped_column( Boolean, nullable=False, default=False, server_default="false" ) - username_id: Mapped[uuid.UUID | None] = mapped_column( - ForeignKey("usernames.id"), unique=True, nullable=True - ) - username: Mapped[Username | None] = relationship( - "Username", back_populates="user", lazy="selectin" - ) def __repr__(self) -> str: return f"" diff --git a/backend/app/users/routes.py b/backend/app/users/routes.py index d2286ea5..ab700632 100644 --- a/backend/app/users/routes.py +++ b/backend/app/users/routes.py @@ -1,19 +1,42 @@ from typing import Annotated -from fastapi import APIRouter, Depends, status +from fastapi import APIRouter, Depends, Security, status from sqlalchemy.ext.asyncio import AsyncSession +from app.auth.dependencies import get_current_user +from app.auth.scopes import Scope from app.core.database import get_session +from app.core.exceptions.app_errors import UnauthorizedError from app.users import services -from app.users.schemas import UserCreate +from app.users.models import User +from app.users.schemas import UserCreate, UserMe, UserNameUpdate, UserUpdate router = APIRouter(tags=["user"]) -@router.post("/", status_code=status.HTTP_201_CREATED) +@router.post("", status_code=status.HTTP_201_CREATED) +@router.post("/", status_code=status.HTTP_201_CREATED, include_in_schema=False) async def signup_with_password( db_session: Annotated[AsyncSession, Depends(get_session)], user_info: UserCreate ): user = await services.create_user(db_session, user_info) return user + + +@router.patch("/me", response_model=UserMe) +async def update_my_name( + db_session: Annotated[AsyncSession, Depends(get_session)], + current_user: Annotated[ + User, Security(get_current_user, scopes=[Scope.PROFILE, Scope.EMAIL]) + ], + user_in: UserNameUpdate, +): + """Altera o nome do usuário autenticado. O e-mail não pode ser alterado aqui.""" + await services.update_user(db_session, current_user, UserUpdate(name=user_in.name)) + await db_session.commit() + + user = await services.get_user_profile_by_id(db_session, current_user.id) + if user is None: + raise UnauthorizedError(detail="Inexistent or inactive user") + return user diff --git a/backend/app/users/schemas.py b/backend/app/users/schemas.py index 6e2ae037..9061db45 100644 --- a/backend/app/users/schemas.py +++ b/backend/app/users/schemas.py @@ -30,6 +30,15 @@ class UserUpdate(BaseModel): password: Password | None = None +class UserNameUpdate(BaseModel): + # alteração do próprio nome pelo usuário autenticado: nome obrigatório e + # nenhum outro campo aceito (e-mail, senha e privilégios não podem ser + # alterados por esta via) + model_config = ConfigDict(extra="forbid") + + name: Name + + class AdminUserCreate(UserCreate): # criação feita por um admin: pode definir os privilégios já na criação is_admin: bool = False @@ -55,24 +64,5 @@ class UserRead(UserBase): deleted_at: datetime | None = None -class UsernameMotherRead(BaseModel): - model_config = ConfigDict(from_attributes=True) - - id: uuid.UUID - first_name: str - last_name: str - full_name: str - description: str - - -class UsernameRead(BaseModel): - model_config = ConfigDict(from_attributes=True) - - id: uuid.UUID - nickname: str - first_mother: UsernameMotherRead - last_mother: UsernameMotherRead - - class UserMe(UserRead): - username: UsernameRead | None = None + pass diff --git a/backend/app/users/services.py b/backend/app/users/services.py index ae095a4f..fce2733e 100644 --- a/backend/app/users/services.py +++ b/backend/app/users/services.py @@ -4,7 +4,6 @@ from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy.orm import selectinload from app.auth.security import hash_password from app.core.pagination import Page, PaginationParams @@ -16,8 +15,6 @@ UserRead, UserUpdate, ) -from app.users.username import services as username_services -from app.users.username.models import Username # --- buscas "normais": ignoram usuários soft-deletados --- @@ -34,10 +31,6 @@ async def get_user_profile_by_id( result = await session.execute( select(User) .where(User.id == user_id, User.deleted_at.is_(None)) - .options( - selectinload(User.username).selectinload(Username.first_mother), - selectinload(User.username).selectinload(Username.last_mother), - ) .execution_options(populate_existing=True) ) return result.scalar_one_or_none() @@ -103,7 +96,6 @@ async def create_user(session: AsyncSession, user_in: UserCreate) -> User: deleted_user.is_verified = False await session.flush() - await username_services.assign_username(deleted_user.id, session) await session.refresh(deleted_user) return deleted_user @@ -116,7 +108,6 @@ async def create_user(session: AsyncSession, user_in: UserCreate) -> User: session.add(user) await session.flush() - await username_services.assign_username(user.id, session) await session.refresh(user) return user @@ -125,8 +116,8 @@ async def create_user(session: AsyncSession, user_in: UserCreate) -> User: async def admin_create_user(session: AsyncSession, user_in: AdminUserCreate) -> User: """Cria um usuário como admin, podendo definir `is_admin` e `is_verified`. - Reaproveita `create_user` (mesmas regras de e-mail duplicado, reativação de - conta deletada e atribuição de username) e aplica os privilégios em seguida. + Reaproveita `create_user` (mesmas regras de e-mail duplicado e reativação de + conta deletada) e aplica os privilégios em seguida. Não faz commit. """ diff --git a/backend/app/users/username/__init__.py b/backend/app/users/username/__init__.py deleted file mode 100644 index be123a4b..00000000 --- a/backend/app/users/username/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""User-owned username catalog and assignment logic.""" diff --git a/backend/app/users/username/models.py b/backend/app/users/username/models.py deleted file mode 100644 index 711fe6c6..00000000 --- a/backend/app/users/username/models.py +++ /dev/null @@ -1,39 +0,0 @@ -from __future__ import annotations - -import uuid -from typing import TYPE_CHECKING - -from sqlalchemy import ForeignKey, String, Text -from sqlalchemy.orm import Mapped, mapped_column, relationship - -from app.core.mixins import UUIDPKMixin -from app.core.models import Base - -if TYPE_CHECKING: - from app.users.models import User - - -class UsernameMother(Base, UUIDPKMixin): - __tablename__ = "username_mothers" - - first_name: Mapped[str] = mapped_column(String(100), nullable=False) - last_name: Mapped[str] = mapped_column(String(100), nullable=False) - full_name: Mapped[str] = mapped_column(String(201), nullable=False, unique=True) - description: Mapped[str] = mapped_column(Text, nullable=False) - - -class Username(Base, UUIDPKMixin): - __tablename__ = "usernames" - - nickname: Mapped[str] = mapped_column(String(255), nullable=False, unique=True) - - first_mother_id: Mapped[uuid.UUID] = mapped_column( - ForeignKey("username_mothers.id"), nullable=False - ) - last_mother_id: Mapped[uuid.UUID] = mapped_column( - ForeignKey("username_mothers.id"), nullable=False - ) - - first_mother: Mapped[UsernameMother] = relationship(foreign_keys=[first_mother_id]) - last_mother: Mapped[UsernameMother] = relationship(foreign_keys=[last_mother_id]) - user: Mapped[User | None] = relationship("User", back_populates="username") diff --git a/backend/app/users/username/seed.py b/backend/app/users/username/seed.py deleted file mode 100644 index ffcddd11..00000000 --- a/backend/app/users/username/seed.py +++ /dev/null @@ -1,120 +0,0 @@ -"""Seed the username catalog from CSV files or tabular data.""" - -from __future__ import annotations - -import csv -from pathlib import Path -from uuid import UUID, uuid4 - -from sqlalchemy import select -from sqlalchemy.dialects.postgresql import insert -from sqlalchemy.ext.asyncio import AsyncSession - -from app.users.username.models import Username, UsernameMother - - -def read_csv(path: Path) -> list[dict]: - with path.open(encoding="utf-8") as file: - return list(csv.DictReader(file)) - - -def _mother_full_name(row: dict) -> str: - return f"{row['first_name'].strip()} {row['last_name'].strip()}" - - -def _to_mother_values(row: dict) -> dict: - first = row["first_name"].strip() - last = row["last_name"].strip() - return { - "id": uuid4(), - "first_name": first, - "last_name": last, - "full_name": f"{first} {last}", - "description": row["description"].strip(), - } - - -def _to_username_values(row: dict, mother_ids: dict[str, UUID]) -> dict: - return { - "id": uuid4(), - "nickname": row["nickname"].strip(), - "first_mother_id": mother_ids[row["first_mome_full_name"].strip()], - "last_mother_id": mother_ids[row["last_mome_full_name"].strip()], - } - - -def _validate_refs(username_rows: list[dict], mother_names: set[str]) -> None: - missing: list[tuple[str, str, str]] = [] - for row in username_rows: - first = row["first_mome_full_name"].strip() - last = row["last_mome_full_name"].strip() - if first not in mother_names or last not in mother_names: - missing.append((row["nickname"].strip(), first, last)) - - if missing: - raise RuntimeError( - f"{len(missing)} usernames referenciam mothers inexistentes. " - f"Exemplos: {missing[:5]}" - ) - - -async def _insert_mothers( - session: AsyncSession, mother_rows: list[dict] -) -> tuple[dict[str, UUID], int]: - if not mother_rows: - return {}, 0 - - statement = ( - insert(UsernameMother) - .values([_to_mother_values(row) for row in mother_rows]) - .on_conflict_do_nothing(index_elements=["full_name"]) - .returning(UsernameMother.id) - ) - result = await session.execute(statement) - inserted_count = len(result.scalars().all()) - mothers = await session.scalars(select(UsernameMother)) - mother_ids = {mother.full_name: mother.id for mother in mothers} - return mother_ids, inserted_count - - -async def _insert_usernames( - session: AsyncSession, - username_rows: list[dict], - mother_ids: dict[str, UUID], -) -> int: - if not username_rows: - return 0 - - statement = ( - insert(Username) - .values([_to_username_values(row, mother_ids) for row in username_rows]) - .on_conflict_do_nothing(index_elements=["nickname"]) - .returning(Username.id) - ) - result = await session.execute(statement) - return len(result.scalars().all()) - - -async def seed_from_rows( - session: AsyncSession, - mother_rows: list[dict], - username_rows: list[dict], -) -> tuple[int, int]: - async with session.begin_nested(): - mother_names = {_mother_full_name(row) for row in mother_rows} - _validate_refs(username_rows, mother_names) - mother_ids, inserted_mothers = await _insert_mothers(session, mother_rows) - inserted_usernames = await _insert_usernames(session, username_rows, mother_ids) - return inserted_mothers, inserted_usernames - - -async def seed_from_csv_files( - session: AsyncSession, - mothers_path: Path, - usernames_path: Path, -) -> tuple[int, int]: - return await seed_from_rows( - session, - read_csv(mothers_path), - read_csv(usernames_path), - ) diff --git a/backend/app/users/username/services.py b/backend/app/users/username/services.py deleted file mode 100644 index 6b62dff7..00000000 --- a/backend/app/users/username/services.py +++ /dev/null @@ -1,52 +0,0 @@ -import uuid - -from sqlalchemy import exists, select -from sqlalchemy.exc import IntegrityError -from sqlalchemy.ext.asyncio import AsyncSession -from sqlalchemy.orm import selectinload - -from app.core.exceptions.app_errors import NotFoundError -from app.users.exceptions import CouldNotAssignUsernameError, NoAvailableUsername -from app.users.models import User -from app.users.username.models import Username - -MAX_RETRIES = 5 - - -async def assign_username(user_id: uuid.UUID, session: AsyncSession) -> Username: - user = await session.scalar( - select(User) - .where(User.id == user_id, User.deleted_at.is_(None)) - .options(selectinload(User.username)) - .execution_options(populate_existing=True) - .with_for_update() - ) - if user is None: - raise NotFoundError("User not found.") - if user.username is not None: - return user.username - - for _ in range(MAX_RETRIES): - available = await session.scalar( - select(Username) - .where( - ~exists().where(User.username_id == Username.id), - ) - .order_by(Username.id) - .with_for_update(skip_locked=True) - .limit(1) - ) - if available is None: - raise NoAvailableUsername() - - try: - async with session.begin_nested(): - user.username = available - await session.flush() - except IntegrityError: - user.username = None - continue - - return available - - raise CouldNotAssignUsernameError() diff --git a/backend/entrypoint.sh b/backend/entrypoint.sh index 46831189..2d2aeaa0 100644 --- a/backend/entrypoint.sh +++ b/backend/entrypoint.sh @@ -1,5 +1,9 @@ #!/bin/sh set -e +if [ "$APP_ENV" = "dev" ] && command -v uv >/dev/null 2>&1; then + uv sync --frozen --link-mode=copy +fi + alembic upgrade head -exec "$@" \ No newline at end of file +exec "$@" diff --git a/backend/pyproject.toml b/backend/pyproject.toml index f712292c..67e21509 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -10,6 +10,8 @@ dependencies = [ "fastapi[standard]>=0.141.1", "pwdlib[argon2]>=0.2.0", "PyJWT>=2.13.0", + "httpx>=0.28.1", + "itsdangerous>=2.2.0", "sqlalchemy>=2.0.51", ] diff --git a/backend/scripts/data/imagens_palestrantes/andre-spanguero.jpg b/backend/scripts/data/imagens_palestrantes/andre-spanguero.jpg new file mode 100644 index 00000000..f8ec66b3 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/andre-spanguero.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/bruno-cerejo.jpeg b/backend/scripts/data/imagens_palestrantes/bruno-cerejo.jpeg new file mode 100644 index 00000000..db646cf4 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/bruno-cerejo.jpeg differ diff --git a/backend/scripts/data/imagens_palestrantes/carlos-marques.jpg b/backend/scripts/data/imagens_palestrantes/carlos-marques.jpg new file mode 100644 index 00000000..ddb91724 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/carlos-marques.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/daniel-batista.jpeg b/backend/scripts/data/imagens_palestrantes/daniel-batista.jpeg new file mode 100644 index 00000000..5d07abc8 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/daniel-batista.jpeg differ diff --git a/backend/scripts/data/imagens_palestrantes/entanglion.jpeg b/backend/scripts/data/imagens_palestrantes/entanglion.jpeg new file mode 100644 index 00000000..fc444405 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/entanglion.jpeg differ diff --git a/backend/scripts/data/imagens_palestrantes/fabio-cozman.jpg b/backend/scripts/data/imagens_palestrantes/fabio-cozman.jpg new file mode 100644 index 00000000..eef0569d Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/fabio-cozman.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/flusp.jpg b/backend/scripts/data/imagens_palestrantes/flusp.jpg new file mode 100644 index 00000000..080be0cc Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/flusp.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/guilherme-mota.jpg b/backend/scripts/data/imagens_palestrantes/guilherme-mota.jpg new file mode 100644 index 00000000..0619beca Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/guilherme-mota.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/helena-maia.jpg b/backend/scripts/data/imagens_palestrantes/helena-maia.jpg new file mode 100644 index 00000000..410e69da Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/helena-maia.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/idian-capozzoli.jpg b/backend/scripts/data/imagens_palestrantes/idian-capozzoli.jpg new file mode 100644 index 00000000..6afd76fd Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/idian-capozzoli.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/laura-damaceno.jpg b/backend/scripts/data/imagens_palestrantes/laura-damaceno.jpg new file mode 100644 index 00000000..f16396b1 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/laura-damaceno.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/luiza-soezima.jpg b/backend/scripts/data/imagens_palestrantes/luiza-soezima.jpg new file mode 100644 index 00000000..344297d8 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/luiza-soezima.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/natalia-naomi.jpg b/backend/scripts/data/imagens_palestrantes/natalia-naomi.jpg new file mode 100644 index 00000000..3239bec6 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/natalia-naomi.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/nina-hirata.png b/backend/scripts/data/imagens_palestrantes/nina-hirata.png new file mode 100644 index 00000000..5f2b237c Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/nina-hirata.png differ diff --git a/backend/scripts/data/imagens_palestrantes/paulo-silveira.jpg b/backend/scripts/data/imagens_palestrantes/paulo-silveira.jpg new file mode 100644 index 00000000..23422b21 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/paulo-silveira.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/pedro-merino.jpg b/backend/scripts/data/imagens_palestrantes/pedro-merino.jpg new file mode 100644 index 00000000..a54db753 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/pedro-merino.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/renata-wasserman.jpg b/backend/scripts/data/imagens_palestrantes/renata-wasserman.jpg new file mode 100644 index 00000000..e41c1d60 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/renata-wasserman.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/roberto-hirata.jpeg b/backend/scripts/data/imagens_palestrantes/roberto-hirata.jpeg new file mode 100644 index 00000000..fb502cc0 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/roberto-hirata.jpeg differ diff --git a/backend/scripts/data/imagens_palestrantes/ronaldo-hashimoto.jpg b/backend/scripts/data/imagens_palestrantes/ronaldo-hashimoto.jpg new file mode 100644 index 00000000..80172d74 Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/ronaldo-hashimoto.jpg differ diff --git a/backend/scripts/data/imagens_palestrantes/yoshiharu-kohayakawa.jpg b/backend/scripts/data/imagens_palestrantes/yoshiharu-kohayakawa.jpg new file mode 100644 index 00000000..142fb1ac Binary files /dev/null and b/backend/scripts/data/imagens_palestrantes/yoshiharu-kohayakawa.jpg differ diff --git a/backend/scripts/data/mothers.csv b/backend/scripts/data/mothers.csv deleted file mode 100755 index 5775d128..00000000 --- a/backend/scripts/data/mothers.csv +++ /dev/null @@ -1,30 +0,0 @@ -first_name,last_name,description -Ana Cristina,Viera de Melo,"Professora titular no IME-USP, atua em Engenharia de Software, Métodos Formais e Linguagens de Programação. Suas pesquisas incluem automação de regras para programação orientada a objetos e validação de transformações de programas orientados a objetos utilizando o Alloy Analyzer. Contribui para o desenvolvimento de ambientes formais de desenvolvimento de programas." -Cristina,Fernandes,"Professora associada no IME-USP, com doutorado pelo Georgia Institute of Technology. Suas pesquisas envolvem Algoritmos, Otimização Combinatória e Teoria dos Grafos. É membro do grupo de pesquisa em Ciência da Computação Teórica, Combinatória e Otimização Combinatória." -Kelly,Braghetto,"Professora assistente no IME-USP, especializada em Bancos de Dados, Gerenciamento de Fluxo de Trabalho e Métodos Formais. Suas pesquisas incluem modelagem formal e análise de fluxos de trabalho, avaliação de desempenho e integração de dados. Contribui para o desenvolvimento de plataformas de cidades inteligentes escaláveis." -Leliane,Nunes de Barros,"Professora livre-docente no IME-USP, com foco em Inteligência Artificial e Planejamento Automatizado. Suas pesquisas incluem Processos de Decisão de Markov Sensíveis ao Risco e planejamento simbólico para políticas fortemente cíclicas. Contribui para o desenvolvimento de políticas ótimas em processos de decisão com restrições de custo." -Nami,Kobayashi,"Professora aposentada do IME-USP, especializada em Linguagens Formais e Autômatos. Suas pesquisas abordam relações racionais, expressões regulares e funções subsequenciais. Contribuiu significativamente para o ensino e desenvolvimento de teorias formais na computação." -Nina Sumiko,Tomita Hirata,"Professora livre-docente no IME-USP, com doutorado em Ciência da Computação pela USP. Sua pesquisa concentra-se em aprendizado de máquina, reconhecimento de padrões e processamento de imagens, com aplicações em áreas como análise de imagens médicas, reconhecimento de escrita manual e segmentação de documentos." -Renata,Wassermann,"Professora associada no IME-USP, com doutorado pela Universidade de Amsterdã. Suas pesquisas envolvem Inteligência Artificial, Lógica e Representação de Conhecimento. É membro do grupo de pesquisa em Lógica, Inteligência Artificial e Métodos Formais (LIAMF) e pesquisadora no Centro de Inteligência Artificial (C4AI)." -Yoshiko,Wakabayashi,"Professora titular no IME-USP, com doutorado pela Universidade de Augsburg. Suas pesquisas incluem otimização combinatória, teoria dos grafos, algoritmos e combinatória poliedral. Foi premiada com a Ordem Nacional do Mérito Científico e eleita membro da Academia Brasileira de Ciências." -Ada,Lovelace,"Matemática e escritora britânica, considerada a primeira programadora de computadores. Trabalhou com Charles Babbage no projeto da máquina analítica e escreveu notas que descreviam um algoritmo para calcular números de Bernoulli, sendo reconhecida como a primeira pessoa a conceber um algoritmo destinado a ser processado por uma máquina." -Grace,Hopper,"Almirante da Marinha dos EUA e cientista da computação, desenvolveu o primeiro compilador para um computador eletrônico e foi pioneira na criação da linguagem COBOL. Popularizou o termo 'debugging' no contexto de programação." -Radia,Perlman,"Conhecida como a 'mãe da internet', desenvolveu o algoritmo Spanning Tree Protocol (STP), fundamental para a operação das redes Ethernet modernas, permitindo a comunicação eficiente entre dispositivos em redes locais." -Frances,Allen,"Pioneira na otimização de compiladores, desenvolveu técnicas que melhoraram a eficiência dos programas de computador. Foi a primeira mulher a receber o Prêmio Turing, considerado o 'Nobel da computação'." -Barbara,Liskov,"Cientista da computação, desenvolveu o princípio da substituição de Liskov. O ""L"" de SOLID se refere a ela. Liderou o projeto do Argus, um dos primeiros sistemas a implementar transações distribuídas e recuperação automática." -Marissa,Mayer,"Primeira engenheira de software do Google, contribuiu para o desenvolvimento da interface de usuário do Google Search. Posteriormente, foi CEO do Yahoo, liderando a empresa em um período de transformação digital." -Dorothy,Vaughan,"Matemática e programadora da NASA, foi uma das primeiras mulheres afro-americanas a trabalhar como programadora em computadores eletrônicos. Foi pioneira na programação em COBOL." -Sister Mary Kenneth,Keller,Primeira mulher a obter um doutorado em ciência da computação nos Estados Unidos. Contribuiu para a introdução da computação no ensino superior e foi defensora do uso de computadores na educação. -Annie,Easley,"Matemática e cientista da computação, trabalhou na NASA desenvolvendo software para foguetes e sistemas de controle de voo. Foi uma das primeiras mulheres afro-americanas a trabalhar como cientista na NASA." -Margaret,Hamilton,"Engenheira de software na missão Apollo da NASA, desenvolveu o software de controle de voo que foi crucial para o sucesso das missões lunares. Ela é creditada por ter cunhado o termo 'engenharia de software'." -Lynn,Conway,"Cientista da computação, trabalhou no desenvolvimento de computadores eletrônicos e hardware. Foi pioneira na arquitetura de computadores e na programação de sistemas operacionais." -Daphne,Koller,"Cientista da computação israelense-americana, professora na Universidade de Stanford e cofundadora do Coursera, plataforma de educação online. Suas pesquisas incluem aprendizado de máquina, modelos gráficos probabilísticos e suas aplicações em biomedicina. Fundadora e CEO da insitro, empresa que utiliza aprendizado de máquina para descoberta de medicamentos." -Timnit,Gebru,"Pesquisadora em inteligência artificial, ética algorítmica e mineração de dados. Cofundadora do Black in AI, uma iniciativa que promove a inclusão de profissionais negros na área de IA. Fundadora do Distributed Artificial Intelligence Research Institute (DAIR), focado em desenvolver IA ética e acessível. Sua pesquisa destaca os vieses e impactos ambientais de modelos de linguagem em larga escala, defendendo uma abordagem mais equitativa e transparente no desenvolvimento de IA." -Chieko,Asakawa,"Pesquisadora no campo da acessibilidade digital, desenvolveu tecnologias inovadoras como o IBM Home Page Reader, um sistema de navegação na web por voz para deficientes visuais. Seu trabalho contínuo explora como a inteligência artificial pode aumentar a independência de pessoas com deficiências, promovendo uma sociedade mais inclusiva." -Mary Jane,Irwin,"Especialista em arquitetura de computadores, com foco em sistemas embarcados e computação móvel. Sua pesquisa aborda o design de sistemas computacionais com consciência de energia e confiabilidade, além de explorar tecnologias emergentes em sistemas computacionais." -Anita,Borg,"Pioneira na promoção da participação feminina em tecnologia, cofundadora da Grace Hopper Celebration, a maior conferência de mulheres na computação. Fundadora do Instituted for Women and Technology, que mais tarde se tornou o Anita Borg Institute, dedicado a apoiar mulheres na tecnologia." -Reshma,Saujani,"Fundadora do Girls Who Code, uma organização sem fins lucrativos que visa fechar a lacuna de gênero na tecnologia, oferecendo educação em ciência da computação para meninas. Seu trabalho tem sido fundamental para aumentar a participação feminina na área de tecnologia." -Jennifer,Klawe,"Presidente do Harvey Mudd College, com contribuições significativas em matemática e ciência da computação. Seu trabalho inclui análise funcional, matemática discreta, ciência da computação teórica e interação humano-computador. É defensora da inclusão de mulheres e minorias sub-representadas em STEM." -Shafi,Goldwasser,"Premiada com o Prêmio Turing em 2012 por suas contribuições fundamentais à criptografia. Desenvolveu os fundamentos teóricos da criptografia moderna, incluindo provas interativas de conhecimento zero e criptografia probabilística, com aplicações em segurança e privacidade." -Fei-Fei,Li,"Pesquisadora em inteligência artificial, conhecida por seu trabalho no desenvolvimento do ImageNet, um banco de dados visual que impulsionou o avanço do aprendizado profundo. Cofundadora do AI4ALL, uma iniciativa para aumentar a diversidade na IA. Atualmente, lidera a World Labs, focada em inteligência artificial espacial." -Mary,Sieckenius,"Pesquisadora em ciência da computação, com foco em áreas como aprendizado de máquina, processamento de linguagem natural e ética em IA. Seu trabalho contribui para o desenvolvimento de tecnologias de IA mais justas e acessíveis." diff --git a/backend/scripts/data/palestras.tsv b/backend/scripts/data/palestras.tsv new file mode 100644 index 00000000..d9647667 --- /dev/null +++ b/backend/scripts/data/palestras.tsv @@ -0,0 +1,18 @@ +Título da atividade Descrição da atividade Tipo de Atividade Horas Pontos Localização Horário Começo Horário Término Nomes dos palestrantes Arquivos de Imagem Descrições dos palestrantes +Você não é pago para escrever código Nunca fomos medidos por linhas de código escritas. Não vai ser com a IA que isso vai mudar. O código sempre foi um byproduct de uma solução. O foco é no entendimento do problema e sua respectiva quebra em questões menores, que podem ser programadas. Comandar o computador continua e continuará chave. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 06/10/2026 13:40:00 06/10/2026 14:40:00 Paulo Silveira paulo-silveira.jpg Paulo Silveira é bacharel e mestre em Ciência da Computação. Cofundador da Alura e do grupo Alun, onde trabalha como líder de visão, coloborando com PM3, StartSe e FIAP. Paulo é host do principal podcast de tecnologia brasileiro, o Hipsters Ponto Tech, é investidor anjo em 41 startups e empreendedor Endeavor. +A construção da carreira em tecnologia na visão de uma jovem engenheira de software Nesta palestra vou contar os bastidores da minha trajetória em engenharia de software, do estágio até a posição atual de engenheira pleno no iFood. Quero compartilhar as lições que aprendi ao longo do caminho e o que eu faria diferente se tivesse que começar de novo: como enxergo oportunidades, o que pesa numa entrevista do outro lado da mesa e como aproveitar de verdade a fase de estágio pra construir a carreira que você quer. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 08/10/2026 15:10:00 08/10/2026 16:10:00 Natália Naomi Sumida natalia-naomi.jpg Engenheira de software no iFood, com mais de 4 anos de experiência na área de TI. Formada como Técnica em Informática pelo COTUCA e atualmente graduanda em Engenharia de Software pela PUC-Campinas. Me interesso pela intersecção entre engenharia, dados e produto, com foco em Busca, e gosto de compartilhar experiências que aprendi ao longo da minha trajetória. +Como treinar modelos de Machine Learning quando o mundo real não coopera O treinamento efetivo de modelos de Machine Learning e, em especial de redes neurais modernas, costuma exigir um volume massivo de dados rotulados. Embora a geração de dados seja abundante hoje, o mundo real impõe barreiras severas na prática. Nesta palestra, abordaremos três cenários críticos: quando não temos acesso aos dados (privacidade), quando os dados não possuem rótulos (custo de anotação) e quando os eventos não se repetem o suficiente (escassez). Para cada uma dessas situações, discutiremos as estratégias e arquiteturas criativas usadas na prática para alcançar um treinamento de alto desempenho. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 07/10/2026 15:10:00 07/10/2026 16:10:00 Nina S. T. Hirata nina-hirata.png Professora, IME/USP +Podemos confiar na IA? Como avaliar sistemas de Gen AI? Sistemas de IA generativa introduzem um desafio diferente dos modelos tradicionais: nem sempre existe uma única resposta correta. Então, como saber se uma aplicação de GenAI está realmente funcionando? Nesta palestra, vamos explorar estratégias para avaliar sistemas de GenAI ao longo de seu ciclo de desenvolvimento, passando por métricas, mapeamento de riscos e a tríade da validação. A ideia é entender como transformar “parece que funciona” em evidências de que o sistema é confiável para o contexto em que será utilizado. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 06/10/2026 12:30:00 06/10/2026 13:30:00 Laura Damaceno de Almeida laura-damaceno.jpg "Cientista de dados e Linkedin Top Voice. Mestre em ciências da computação com ênfase em IA, sendo uma das paixões como cientista e pesquisadora é desvendar histórias através dos dados. Co-autora do livro ""IA por Mulheres"", lançado em Harvard. Co-fundadora de uma comunidade que visa incluir e capacitar mulheres brasileiras em inteligência artificial e ciência de dados no Brasil, chamada AI Girls. Criadora de conteúdo no @laura_data_talks, cujo intuito é desmitificar a ciência de dados e IA para as pessoas" +Inteligência Artificial no Verão Tropical: Discutindo Possíveis Futuros da IA no Brasil Inteligência Artificial é um dos assuntos mais discutidos na sociedade no momento. Essa palestra tentará tatear por questões ligadas a ensino (de IA e por IA) e pesquisa (em IA e usando IA), especificamente pensando na realidade brasileira. É provável que o número de dúvidas seja maior do que o de respostas, mas é bom pelo menos organizar um pouco as ideias e procurar um caminho no meio desse avanço tecnológico avassalador. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 06/10/2026 15:10:00 06/10/2026 16:10:00 Fabio Gagliardi Cozman fabio-cozman.jpg Fabio G. Cozman é Professor Titular da Escola Politécnica da Universidade de São Paulo (USP), Diretor do Centro de Inteligência Artificial e Aprendizado de Máquina (CIAAM) da USP, com foco em aprendizado de máquina e representação de conhecimento e incerteza. Engenheiro pela Escola Politécnica USP e PhD pela Carnegie Mellon University (EUA), serviu, entre outras atividades, como Program e General Chair da Conference on Uncertainty in Artificial Intelligence, Area Chair da International Joint Conference on Artificial Intelligence, Associate Editor dos periódicos Artificial Intelligence, Journal of Artificial Intelligence Research, e Journal of Approximate Reasoning. Foi também coordenador do Comitê Especial em Inteligência Artificial da Sociedade Brasileira de Computação, e recebeu o Prêmio de Mérito Científico em Inteligência Artificial concedido por aquela sociedade. +Ameaças Invisíveis: Ataques Adversariais na Computação Clássica e Quântica Como pequenas alterações imperceptíveis aos olhos humanos podem enganar os sistemas de Inteligência Artificial mais avançados do mundo? Nesta palestra, exploraremos os fundamentos da inteligência artificial clássica e dos ataques adversariais através de um storytelling guiado por casos reais, desde falhas críticas no setor militar até os impactos no mundo corporativo. Após mapearmos as fragilidades e as ilusões digitais da computação clássica, faremos a ponte para a próxima fronteira tecnológica. Com o avanço do Quantum Machine Learning, responderemos a segunte provocação: a natureza complexa da computação quântica será a nossa salvação contra essas ameaças, ou a sua estrutura a tornará ainda mais frágil e vulnerável aos ataques adversariais? Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 08/10/2026 16:20:00 08/10/2026 17:20:00 Pedro Merino pedro-merino.jpg "Pedro é bacharel em Física pelo Instituto de Física da Universidade de São Paulo (IFUSP). Atualmente, cursa mestrado em Engenharia Eletrônica e de Computação no Instituto Tecnológico de Aeronáutica (ITA), onde sua pesquisa se concentra na investigação de ataques adversariais em sistemas de aprendizado de máquina quânticos. Paralelamente ao trabalho acadêmico, dedica parte do seu tempo à comunidade de computação quântica como voluntário do IBM Qiskit Advocate. Durante o último ano de graduação, realizou um projeto de pesquisa financiado pela FAPESP, intitulado ""Detecção e Classificação de Objetos Estelares Jovens com Métodos de Aprendizado de Máquina"", no qual desenvolveu uma rede neural utilizando dados fotométricos para detectar e classificar estrelas. Durante o ensino médio, obteve resultados excepcionais em competições acadêmicas, notadamente conquistando a Medalha de Ouro na Olimpíada Brasileira de Astronomia e Astronáutica (OBA) em 2021 e a Medalha de Bronze em 2020. Também recebeu uma Medalha de Prata na Olimpíada Nacional de Ciências em 2021 e uma Medalha de Bronze em 2020." +Hackeando a Pilha de Rede do Linux: Como eBPF e XDP Reprogramam o Kernel para Streaming de Vídeo de Ultra-Baixa Latência Com o passar dos anos, a Internet passou de uma rede voltada essencialmente ao transporte de texto para uma infraestrutura capaz de suportar áudio, vídeo, jogos e aplicações interativas. Diferentemente do texto, aplicações multimídia são muito sensíveis a atrasos, perdas e variações na rede (ninguém quer que o vídeo trave justamente no momento mais importante!) Nesta palestra, veremos que Redes de Computadores não são apenas protocolos isolados: o sistema operacional também tem um papel fundamental no tratamento dos pacotes e pode ser programado para modificar seu comportamento. Veremos na prática como eBPF e XDP permitem reprogramar parte do processamento de rede no kernel Linux e como essa capacidade pode ser utilizada para proteger um fluxo de vídeo em tempo real contra tráfego agressivo. Ao final, serão apresentadas questões que vão além da parte prática apresentada na palestra e que podem dar origem a projetos de iniciação científica e pesquisas avançadas em Redes de Computadores. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 08/10/2026 13:40:00 08/10/2026 14:40:00 Daniel Macêdo Batista daniel-batista.jpeg Daniel possui graduação em Ciência da Computação pela UFBA, mestrado em Ciência da Computação pela Unicamp e doutorado em Ciência da Computação também pela Unicamp. É professor do Departamento de Ciência da Computação do IME/USP desde fevereiro de 2011 onde ministra regularmente as disciplinas de Sistemas Operacionais e Redes de Computadores para o BCC. Sua principal área de pesquisa é Redes de Computadores e orienta trabalhos nessa área nos níveis de doutorado, mestrado e iniciação científica. +Sorria! Você está sendo filmado: Os Problemas e Problemas da Vigilância Automatizada Baseada em Vídeos Com o crescente número de câmeras instaladas nas cidades e o grande interesse em sistemas de inteligência artificial, discutir vigilância automatizada se torna imprescindível. Esta palestra irá introduzir o assunto, passando por conceitos fundamentais, possíveis aplicações e desafios. Também discutiremos os principais impactos dessas tecnologias. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 07/10/2026 12:30:00 07/10/2026 13:30:00 Helena de Almeida Maia helena-maia.jpg Helena Maia é professora no Instituto de Computação (IC) da Universidade Estadual de Campinas (UNICAMP). É membro do laboratório de inteligência artificial recod.ai, professora colaboradora no Hub de Inteligência Artificial e Arquiteturas Cognitivas (H.IAAC) e pesquisadora no projeto Linguagem Humana e Inteligência Artificial (LIA). Suas áreas de atuação incluem Ética e Letramento em Inteligência Artificial, Processamento de Linguagem Natural, Visão Computacional e Aprendizado de Máquina. Possui graduação e mestrado em Ciência da Computação pela Universidade Federal de Juiz de Fora (UFJF), e doutorado em Ciência da Computação pela UNICAMP. +Computação Quântica como você nunca viu "O imaginário popular enquadra a computação quântica como um bicho de sete cabeças impossível de ser compreendido por meros mortais. Mas será que precisa mesmo ser assim? Nós usaremos o jogo de tabuleiro ""Entanglion"", desenvolvido pela IBM, para que você entenda as bases deste novo campo da ciência de maneira natural, apresentando conceitos como entrelaçamento e superposição de forma intuitiva, sem perder o viés científico." Workshop 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 05/10/2026 13:40:00 05/10/2026 14:40:00 Projeto Entanglion entanglion.jpeg O Projeto Entanglion faz parte de uma AEX (Atividade Extensionista), organizada pelo prof. Dr. Marcos Chaim, que visa divulgar a computação quântica para o público geral. Fazemos isso promovendo oficinas práticas com partidas de Entanglion nas quais explicamos os conceitos teóricos por trás do jogo de tabuleiro desenvolvido pela IBM. Já promovemos estas oficinas em Board Games Houses, escolas, além de sermos correspondentes da Rede Iberoamericana para o Avanço da Engenharia de Software Quântico (RIPAISC) +Oficina de GIT O FLUSP dará seu melhor para letrar os interessados nos fundamentos do GIT... e aqueles com a guarda baixa sem dúvida serão recrutados para utilizarem os conhecimentos adquiridos no desenvolvimento de software livre! Workshop 1 250 CEC, IME-USP - Bloco B 05/10/2026 16:20:00 05/10/2026 17:20:00 FLUSP - Free, Libre, open source software na USP flusp.jpg Grupo de Extensão de software livre e aberto da USP +Modelagem Booleana de Redes Gênicas: da lógica ao comportamento celular Como valores binários e operadores AND, OR e NOT podem ajudar a compreender o comportamento de uma célula? Nesta palestra, veremos como redes Booleanas representam interações entre componentes celulares e como regras locais podem produzir diferentes comportamentos, como a divisão celular, a interrupção do ciclo ou a morte da célula. Conectaremos conceitos familiares à Computação — estados, transições e dinâmica de redes — a questões biológicas: como uma mesma rede pode apresentar comportamentos distintos? Como alterações em seus componentes afetam essa dinâmica? E o que podemos concluir a partir das previsões de um modelo? Com exemplos de aplicações em Biologia, discutiremos as possibilidades e os limites da modelagem Booleana. Os conceitos biológicos necessários serão introduzidos ao longo da apresentação, sem exigir conhecimento prévio de Biologia. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 07/10/2026 16:20:00 07/10/2026 17:20:00 Ronaldo Fumio Hashimoto ronaldo-hashimoto.jpg Ronaldo Fumio Hashimoto é professor do Instituto de Matemática, Estatística e Ciência da Computação da Universidade de São Paulo (IME-USP). Sua pesquisa abrange processamento de imagens, aprendizado de máquina e bioinformática. Em processamento de imagens, desenvolve métodos baseados em morfologia matemática e representações hierárquicas, com foco em algoritmos eficientes de filtragem e na integração de operadores morfológicos a redes neurais. Na interface entre Computação e Biologia, investiga aplicações de aprendizado de máquina em bioinformática, além da modelagem e inferência de redes de regulação gênica. +Como a Tako escalou com a mesma infraestrutura e desenvolveu um produto de IA muito além do chatbot Cases, conceitos e frameworks que fizeram a Tako escalar e se tornar um dos principais players de IA para RH do Brasil Palestra 1 450 Auditório Jacy Monteiro, IME-USP - Bloco B 09/10/2026 13:40:00 09/10/2026 14:40:00 Bruno Cerejo | André Spanguero bruno-cerejo.jpeg | andre-spanguero.jpg Bruno Cerejo é engenheiro de software na Tako, com mais de 12 anos em tecnologia e passagens por Nubank, Mercado Livre e Cielo. É formado em Análise e Desenvolvimento de Sistemas pela Fatec São Paulo. | André Spanguero é formado em Ciência da Computação pela USP e atua como engenheiro de software na Tako. Com mais de 10 anos de experiência em tecnologia e passagens por Google, Zé Delivery e RocketSeat. +Como colorir um grafo propriamente com menos cores que o mínimo possível O número cromático χ(G) de um grafo G é menor número de cores que podemos usar em uma coloração dos vértices de G de forma que a coloração seja própria, isto é, não haja arestas com suas duas pontas de cores iguais. Curiosamente, para certos grafos G, é possível encontrar tais colorações com menos cores que χ(G), caso admitamos colorações próprias quânticas. Discutiremos esse fenômeno nesta palestra, introduzindo, naturalmente, o que se entende por tais colorações quânticas. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 06/10/2026 16:20:00 06/10/2026 17:20:00 Yoshiharu Kohayakawa yoshiharu-kohayakawa.jpg Yoshiharu Kohayakawa é Professor Titular da Universidade de São Paulo desde 2004. Obteve seu título de doutor em matemática na Universidade de Cambridge (1991), sob a orientação de Béla Bollobás. Seus interesses concentram-se nas áreas de combinatória e teoria da computação. Suas linhas de pesquisa envolvem, entre outros, grafos aleatórios, teoria de Ramsey, problemas extremais, métodos probabilísticos, e o método da regularidade. +Quando as máquinas agem: agentes, trabalho e sociedade Nesta palestra eu vou falar sobre agentes, sua história, sua relação com os modelos de linguagem atuais, seu impacto no trabalho dos profissionais de computação e a questão mais importante, quem se responsabiliza pela ação dos agentes. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 07/10/2026 13:40:00 07/10/2026 14:40:00 Roberto Hirata Jr. roberto-hirata.jpeg Roberto é professor do Instituto de Matemática, Estatística e Ciência da Computação da Universidade de São Paulo. Suas áreas de pesquisa são visão computacional e aprendizado de máquina. +Computando no escuro: criptografia homomórfica e suas aplicações em privacidade Toda consulta a um serviço online revela algo. Ao buscar um sintoma num banco de dados hospitalar, verificar se uma senha foi vazada ou mesmo identificar um número desconhecido. Em todas as consultas, o usuário entrega ao servidor alguma informação que deseja saber. A criptografia tradicional protege essa consulta de quem observa a rede, mas não do próprio servidor, que precisa de fato ler a pergunta para respondê-la. entretatanto, muitas vezes, a pergunta revela mais do que a resposta... Seria possível obter uma informação sem revelar qual informação se procura? À primeira vista, isso exigiria algo impossível: que o servidor respondesse a uma pergunta que não consegue ler. Esse é o problema da recuperação privada de informação (Private Information Retrieval - PIR). Uma das possíveis técnica para resolver esse problema é através da criptografia homomórfica, que permite realizar cálculos sobre dados cifrados. Nesta palestra, veremos como é possível perguntar sem revelar a pergunta. Não é necessário conhecimento prévio de criptografia. Palestra 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 08/10/2026 12:30:00 08/10/2026 13:30:00 Luiza Soezima luiza-soezima.jpg Luiza é estudante de doutorado na Aarhus University (Dinamarca), com orientação de Diego F. Aranha e Peter Scholl. Sua pesquisa está na interseção entre criptografia aplicada e privacidade. Ela trabalha com primitivas como a recuperação privada de informação (PIR) e operações privadas sobre conjuntos, e com aplicações como comunicação segura e transações financeiras seguras. Graduou-se em 2024 no BCC e prosseguiu com um mestrado em computação com ênfase em Cybersecurity na Université Grenoble Alpes (França). +Roda de conversa & Dúvidas sobre carreira acadêmica e pós-graduação em computação Junte-se aos professores Renata Wasserman e Guilherme Oliveira Mota, ao lado de alunos de pós-graduação do IME-USP, como Carlos Marques e Idian Capozzoli, em uma conversa aberta e descontraída sobre os rumos da carreira acadêmica em Computação. O encontro abordará como funciona a pós-graduação, a escolha de áreas de pesquisa e as vivências reais de quem está em diferentes momentos da trajetória científica. Reunindo as perspectivas de docentes e pós-graduandos, o papo promete um panorama completo e autêntico sobre o universo da pesquisa. Esta é uma oportunidade única para tirar suas dúvidas, trocar ideias e entender de perto os próximos passos para o seu futuro acadêmico. Conversa 1 250 Auditório Jacy Monteiro, IME-USP - Bloco B 09/10/2026 16:20:00 09/10/2026 17:20:00 Renata Wasserman | Guilherme Oliveira Mota | Carlos Marques | Idian Capozzoli renata-wasserman.jpg | guilherme-mota.jpg | carlos-marques.jpg | idian-capozzoli.jpg Renata Wasserman é professora associada do Departamento de Ciência da Computação do Instituto de Matemática e Estatística da USP. E membro do grupo de pesquisa em Lógica, Inteligência Artificial e Métodos Formais (LIAMF), pesquisadora do Centro de Inteligência Artificial (C4AI) e integra o conselho diretor do Lawgorithm. | Guilherme Oliveira Mota é professor do Departamento de Ciência da Computação do Instituto de Matemática e Estatística da USP. É pesquisador na área de Combinatória e Teoria dos Grafos, atuando principalmente em combinatória extremal e probabilística, métodos probabilísticos e algoritmos em grafos. | Carlos Marques é graduado no BCC do IME-USP em 2025, atualmente é aluno de mestrado no Programa de Pós Graduação em Ciência da Computação do mesmo instituto, orientado pela Profª Nina S. T. Hirata. Membro do LEARN (Liga de Estudos em Aprendizado de Máquina e Redes Neurais), possui interesse em Graph Neural Networks. | Idian Capozzoli se graduou no BCC em 2025 e atualmente é estudante e bolsista FAPESP de mestrado no IME. É orientada por Yoshiko Wakabayashi, coorientada por Cristiane Sato e trabalha com otimização combinatória, em especial com problemas de coloração em grafos. Suas principais áreas de interesse são otimização, combinatória e teoria da computação. +Encerramento Para encerrar a XVI Semana da Computação, teremos uma tradicional roda de conversa com professores e ex-alunos do curso. O encontro será um espaço aberto para trocar experiências, relembrar histórias, discutir as transformações do mundo da computação e refletir sobre as mudanças tecnológicas e acadêmicas ao longo dos anos. Além de compartilhar trajetórias e perspectivas sobre o futuro da área, o evento também será uma oportunidade para os alunos atuais tirarem dúvidas e interagirem com quem já trilhou esse caminho. Encerrando a tarde, teremos um coffee break especial para celebrar o fim de mais uma Semana da Computação e fortalecer os laços entre gerações do curso. Encerramento 1 250 09/10/2026 17:40:00 09/10/2026 18:40:00 \ No newline at end of file diff --git a/backend/scripts/seed_dev.py b/backend/scripts/seed_dev.py new file mode 100644 index 00000000..4ad42c33 --- /dev/null +++ b/backend/scripts/seed_dev.py @@ -0,0 +1,67 @@ +"""Seed the minimum data needed to exercise the local Semana flows.""" + +import asyncio +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.challenges.models.challenge import Challenge, ChallengeScoringType +from app.core.config import get_settings +from app.core.database import create_database +from app.semana.models import SemanaEvent + + +@asynccontextmanager +async def session_scope() -> AsyncIterator[AsyncSession]: + settings = get_settings() + engine, session_factory = create_database(settings) + try: + async with session_factory() as session: + try: + yield session + await session.commit() + except Exception: + await session.rollback() + raise + finally: + await engine.dispose() + + +async def main() -> None: + async with session_scope() as session: + event = await session.scalar(select(SemanaEvent).where(SemanaEvent.ano == 2026)) + if event is None: + event = SemanaEvent(nome="Semana da Computação", ano=2026) + session.add(event) + await session.flush() + + challenge = await session.scalar( + select(Challenge).where( + Challenge.semana_id == event.id, + Challenge.title == "Desafio de boas-vindas", + Challenge.deleted_at.is_(None), + ) + ) + if challenge is None: + challenge = Challenge( + title="Desafio de boas-vindas", + prompt="Digite a palavra-chave apresentada na página do evento.", + scoring_type=ChallengeScoringType.INPUT, + finishes_at=datetime.now(UTC) + timedelta(days=30), + points_value=100, + input_answer="symcomp", + semana_id=event.id, + ) + session.add(challenge) + await session.flush() + + print(f"Semana: {event.id} ({event.nome} {event.ano})") + print(f"Challenge: {challenge.id} ({challenge.title})") + print("Resposta do desafio de boas-vindas: symcomp") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/scripts/seed_mock_data.py b/backend/scripts/seed_mock_data.py new file mode 100644 index 00000000..4db3ca6f --- /dev/null +++ b/backend/scripts/seed_mock_data.py @@ -0,0 +1,598 @@ +"""Create a repeatable local dataset for exercising the active app flows. + +Run from ``backend/`` with ``uv run python -m scripts.seed_mock_data``. +Seeded accounts use the password ``local-test-password``. This script refuses to +run when ``APP_ENV=prod`` and never deletes existing rows. +""" + +import asyncio +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from datetime import UTC, datetime, timedelta +from typing import Any + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.atividade.models import Atividade, Presenca, StatusAtividade, TipoAtividade +from app.auth.security import hash_password +from app.challenges.models.answer import Answer +from app.challenges.models.challenge import Challenge, ChallengeScoringType +from app.challenges.models.challenge_participant import ChallengeParticipant +from app.challenges.models.input import Input +from app.challenges.models.question import Question +from app.core.config import AppEnv, get_settings +from app.core.database import create_database +from app.semana.models import PointEvent, SemanaEvent, SemanaParticipant +from app.users.models import User + +SEED_PASSWORD = "local-test-password" + +USER_SPECS = { + "admin": { + "email": "seed-admin@example.com", + "name": "Mock Admin", + "is_admin": True, + }, + "alice": { + "email": "alice@example.com", + "name": "Alice Almeida", + "is_admin": False, + }, + "bruno": { + "email": "bruno@example.com", + "name": "Bruno Barbosa", + "is_admin": False, + }, + "carla": { + "email": "carla@example.com", + "name": "Carla Costa", + "is_admin": False, + }, +} + + +@asynccontextmanager +async def session_scope() -> AsyncIterator[AsyncSession]: + settings = get_settings() + if settings.app_env == AppEnv.production: + raise RuntimeError("Mock data cannot be seeded when APP_ENV=prod.") + + engine, session_factory = create_database(settings) + try: + async with session_factory() as session: + try: + yield session + await session.commit() + except Exception: + await session.rollback() + raise + finally: + await engine.dispose() + + +async def get_or_create_user(session: AsyncSession, spec: dict[str, Any]) -> User: + user = await session.scalar(select(User).where(User.email == spec["email"])) + if user is None: + legacy_email = spec["email"].replace("@example.com", "@example.test") + user = await session.scalar(select(User).where(User.email == legacy_email)) + if user is None: + user = User( + email=spec["email"], + name=spec["name"], + password_hash=hash_password(SEED_PASSWORD), + is_admin=spec["is_admin"], + is_verified=True, + ) + session.add(user) + await session.flush() + else: + user.email = spec["email"] + user.name = spec["name"] + user.is_admin = spec["is_admin"] + user.is_verified = True + user.deleted_at = None + await session.flush() + return user + + +async def get_or_create_week( + session: AsyncSession, name: str, year: int +) -> SemanaEvent: + week = await session.scalar( + select(SemanaEvent).where(SemanaEvent.ano == year, SemanaEvent.nome == name) + ) + if week is None: + week = SemanaEvent(nome=name, ano=year) + session.add(week) + else: + week.nome = name + await session.flush() + return week + + +async def get_or_create_challenge( + session: AsyncSession, + week: SemanaEvent, + *, + title: str, + description: str, + scoring_type: ChallengeScoringType, + points_value: int, +) -> Challenge: + challenge = await session.scalar( + select(Challenge).where( + Challenge.semana_id == week.id, + Challenge.title == title, + Challenge.deleted_at.is_(None), + ) + ) + if challenge is None: + challenge = Challenge(title=title, semana_id=week.id) + session.add(challenge) + + challenge.description = description + challenge.scoring_type = scoring_type + challenge.points_value = points_value + challenge.finishes_at = datetime.now(UTC) + timedelta(days=30) + await session.flush() + return challenge + + +async def get_or_create_week_participant( + session: AsyncSession, + week: SemanaEvent, + user: User, + nickname: str, +) -> SemanaParticipant: + participant = await session.scalar( + select(SemanaParticipant).where( + SemanaParticipant.semana_id == week.id, + SemanaParticipant.user_id == user.id, + ) + ) + if participant is None: + participant = SemanaParticipant( + semana_id=week.id, + user_id=user.id, + nickname=nickname, + ) + session.add(participant) + else: + participant.nickname = nickname + participant.deleted_at = None + await session.flush() + return participant + + +async def get_or_create_challenge_participant( + session: AsyncSession, + user: User, + challenge: Challenge, + week_participant: SemanaParticipant, + *, + score: int, + submission: str | None, + submitted_at: datetime | None, +) -> ChallengeParticipant: + participant = await session.scalar( + select(ChallengeParticipant).where( + ChallengeParticipant.user_id == user.id, + ChallengeParticipant.challenge_id == challenge.id, + ) + ) + if participant is None: + participant = ChallengeParticipant( + user_id=user.id, + challenge_id=challenge.id, + ) + session.add(participant) + + participant.semana_participant_id = week_participant.id + participant.score = score + participant.submission = submission + participant.submitted_at = submitted_at + participant.deleted_at = None + await session.flush() + return participant + + +async def get_or_create_question( + session: AsyncSession, + challenge: Challenge, + prompt: str, + answer: str, +) -> Question: + question = await session.scalar( + select(Question).where( + Question.challenge_id == challenge.id, + Question.prompt == prompt, + ) + ) + if question is None: + question = Question( + challenge_id=challenge.id, + prompt=prompt, + answer=answer, + ) + session.add(question) + else: + question.answer = answer + await session.flush() + return question + + +async def get_or_create_answer( + session: AsyncSession, + participant: ChallengeParticipant, + question: Question, + content: str, + is_correct: bool, +) -> Answer: + answer = await session.scalar( + select(Answer).where( + Answer.participant_id == participant.id, + Answer.question_id == question.id, + ) + ) + if answer is None: + answer = Answer( + participant_id=participant.id, + question_id=question.id, + content=content, + is_correct=is_correct, + ) + session.add(answer) + else: + answer.content = content + answer.is_correct = is_correct + answer.deleted_at = None + await session.flush() + return answer + + +async def get_or_create_input( + session: AsyncSession, challenge: Challenge, prompt: str, expected_answer: str +) -> Input: + input_data = await session.scalar( + select(Input).where(Input.challenge_id == challenge.id) + ) + if input_data is None: + input_data = Input(challenge_id=challenge.id, prompt=prompt) + session.add(input_data) + input_data.prompt = prompt + input_data.input_answer = expected_answer + await session.flush() + return input_data + + +async def get_or_create_activity( + session: AsyncSession, + week: SemanaEvent, + *, + code: str, + kind: TipoAtividade, + title: str, + start: datetime, + end: datetime, + points: int, + hours: int, + status: StatusAtividade = StatusAtividade.CONFIRMADA, +) -> Atividade: + activity = await session.scalar( + select(Atividade).where( + Atividade.semana_id == week.id, + Atividade.codigo == code, + ) + ) + if activity is None: + activity = Atividade(semana_id=week.id, codigo=code, tipo=kind) + session.add(activity) + + activity.tipo = kind + activity.titulo = title + activity.descricao = f"Mock schedule entry for {title}." + activity.local = "Auditório principal" + activity.palestrantes = [ + {"nome": "Equipe SymComp", "sobre": "Palestrante de teste."} + ] + activity.link_live = None + activity.status = status + activity.comeca_as = start + activity.termina_as = end + activity.pontos = points + activity.horas = hours + await session.flush() + return activity + + +async def get_or_create_presence( + session: AsyncSession, + activity: Atividade, + *, + user: User | None, + name: str, + email: str, + hours: int, +) -> Presenca: + presence = await session.scalar( + select(Presenca).where( + Presenca.atividade_id == activity.id, + Presenca.email == email, + ) + ) + if presence is None: + legacy_email = email.replace("@example.com", "@example.test") + presence = await session.scalar( + select(Presenca).where( + Presenca.atividade_id == activity.id, + Presenca.email == legacy_email, + ) + ) + if presence is None: + presence = Presenca( + atividade_id=activity.id, + user_id=user.id if user else None, + nome=name, + email=email, + horas=hours, + ) + session.add(presence) + else: + presence.user_id = user.id if user else None + presence.nome = name + presence.email = email + presence.horas = hours + await session.flush() + return presence + + +async def get_or_create_point_event( + session: AsyncSession, + week_participant: SemanaParticipant, + *, + amount: int, + source_type: str, + source_id, + reason: str, +) -> PointEvent: + event = await session.scalar( + select(PointEvent).where( + PointEvent.semana_participant_id == week_participant.id, + PointEvent.source_type == source_type, + PointEvent.source_id == source_id, + ) + ) + if event is None: + event = PointEvent( + semana_participant_id=week_participant.id, + source_type=source_type, + source_id=source_id, + ) + session.add(event) + event.amount = amount + event.reason = reason + await session.flush() + return event + + +async def seed() -> None: + now = datetime.now(UTC).replace(minute=0, second=0, microsecond=0) + + async with session_scope() as session: + users = { + key: await get_or_create_user(session, spec) + for key, spec in USER_SPECS.items() + } + weeks = { + 2025: await get_or_create_week(session, "Semana Mock Arquivada", 2025), + 2026: await get_or_create_week(session, "Semana Mock 2026", 2026), + } + + week_participants: dict[tuple[int, str], SemanaParticipant] = {} + for year, week in weeks.items(): + for key, user in users.items(): + if key == "admin": + continue + week_participants[(year, key)] = await get_or_create_week_participant( + session, + week, + user, + nickname=f"{key}{year}", + ) + + quiz = await get_or_create_challenge( + session, + weeks[2026], + title="Mock: Quiz de fundamentos", + description="Perguntas de teste com diferentes níveis de acerto.", + scoring_type=ChallengeScoringType.QUIZ, + points_value=100, + ) + input_challenge = await get_or_create_challenge( + session, + weeks[2026], + title="Mock: Resposta livre", + description="Desafio de entrada com resposta automática.", + scoring_type=ChallengeScoringType.INPUT, + points_value=80, + ) + manual_challenge = await get_or_create_challenge( + session, + weeks[2026], + title="Mock: Avaliação manual", + description="Pontuação atribuída pela equipe.", + scoring_type=ChallengeScoringType.MANUAL, + points_value=50, + ) + await get_or_create_input( + session, + input_challenge, + prompt="Qual é a palavra-chave do evento?", + expected_answer="symcomp", + ) + + questions = [ + await get_or_create_question(session, quiz, "Quanto é 2 + 2?", "4"), + await get_or_create_question( + session, quiz, "Qual linguagem roda no navegador?", "JavaScript" + ), + ] + quiz_participants: dict[str, ChallengeParticipant] = {} + quiz_answers = { + "alice": [("4", True), ("JavaScript", True)], + "bruno": [("4", True), ("Python", False)], + "carla": [("5", False), ("Python", False)], + } + for key, answers in quiz_answers.items(): + score = sum(50 for _, is_correct in answers if is_correct) + participant = await get_or_create_challenge_participant( + session, + users[key], + quiz, + week_participants[(2026, key)], + score=score, + submission=None, + submitted_at=now - timedelta(hours=2), + ) + quiz_participants[key] = participant + for question, (content, is_correct) in zip(questions, answers, strict=True): + await get_or_create_answer( + session, participant, question, content, is_correct + ) + + input_attempts = { + "alice": ("symcomp", 80), + "bruno": ("wrong-answer", 0), + } + input_participants: dict[str, ChallengeParticipant] = {} + for key, (submission, score) in input_attempts.items(): + input_participants[key] = await get_or_create_challenge_participant( + session, + users[key], + input_challenge, + week_participants[(2026, key)], + score=score, + submission=submission, + submitted_at=now - timedelta(hours=1), + ) + + manual_participant = await get_or_create_challenge_participant( + session, + users["carla"], + manual_challenge, + week_participants[(2026, "carla")], + score=17, + submission=None, + submitted_at=None, + ) + + for key, participant in quiz_participants.items(): + await get_or_create_point_event( + session, + week_participants[(2026, key)], + amount=participant.score, + source_type="challenge", + source_id=participant.id, + reason=quiz.title, + ) + for key, participant in input_participants.items(): + await get_or_create_point_event( + session, + week_participants[(2026, key)], + amount=participant.score, + source_type="challenge", + source_id=participant.id, + reason=input_challenge.title, + ) + await get_or_create_point_event( + session, + week_participants[(2026, "carla")], + amount=manual_participant.score, + source_type="manual_adjustment", + source_id=manual_participant.id, + reason="Mock manual score adjustment", + ) + + activities = [ + await get_or_create_activity( + session, + weeks[2026], + code="1001", + kind=TipoAtividade.PALESTRA, + title="Mock: Abertura e computação", + start=now + timedelta(days=1), + end=now + timedelta(days=1, hours=1), + points=10, + hours=1, + ), + await get_or_create_activity( + session, + weeks[2026], + code="1002", + kind=TipoAtividade.WORKSHOP, + title="Mock: Laboratório de programação", + start=now + timedelta(days=1, hours=2), + end=now + timedelta(days=1, hours=4), + points=25, + hours=2, + status=StatusAtividade.PROVISORIA, + ), + await get_or_create_activity( + session, + weeks[2025], + code="1003", + kind=TipoAtividade.COFFEE_BREAK, + title="Mock: Intervalo arquivado", + start=now - timedelta(days=300), + end=now - timedelta(days=300) + timedelta(minutes=30), + points=5, + hours=1, + ), + ] + + attendance_specs = [ + (activities[0], 2026, "alice", users["alice"], 1), + (activities[0], 2026, "bruno", users["bruno"], 1), + (activities[1], 2026, "carla", users["carla"], 2), + (activities[2], 2025, None, None, 1), + ] + for activity, year, user_key, user, hours in attendance_specs: + name = user.name if user is not None else "Visitante Mock" + email = user.email if user is not None else "visitor@example.com" + presence = await get_or_create_presence( + session, + activity, + user=user, + name=name, + email=email, + hours=hours, + ) + if user_key is not None: + await get_or_create_point_event( + session, + week_participants[(year, user_key)], + amount=activity.pontos, + source_type="activity", + source_id=presence.id, + reason=activity.titulo, + ) + + print("Mock dataset ready.") + print(f"Admin: {USER_SPECS['admin']['email']} / {SEED_PASSWORD}") + for year, week in weeks.items(): + print(f"Semana {year}: {week.id} ({week.nome})") + print("Challenges:") + for challenge in (quiz, input_challenge, manual_challenge): + print(f" {challenge.id} {challenge.scoring_type.value}: {challenge.title}") + print("Activities:") + for activity in activities: + print(f" {activity.id} {activity.codigo}: {activity.titulo}") + + +async def main() -> None: + await seed() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/scripts/seed_semana_data.py b/backend/scripts/seed_semana_data.py new file mode 100644 index 00000000..86042b2c --- /dev/null +++ b/backend/scripts/seed_semana_data.py @@ -0,0 +1,279 @@ +"""Seed the initial Semana da Computacao 2026 schedule. + +Run from ``backend/`` with ``uv run python scripts/seed_semana_data.py`` after +configuring the environment for the intended database. +Existing events and activities are left unchanged; only missing records are added. +Activity details are read from ``scripts/data/palestras.tsv`` and speaker images +from ``scripts/data/imagens_palestrantes``. +""" + +import asyncio +import csv +from collections.abc import AsyncGenerator +from contextlib import asynccontextmanager +from datetime import datetime +from importlib import import_module +from pathlib import Path +from zoneinfo import ZoneInfo + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.atividade.image import MAX_IMAGE_BYTES +from app.atividade.models import Atividade, StatusAtividade, TipoAtividade +from app.atividade.services import create_atividade +from app.core.config import Settings, get_settings +from app.core.database import create_database +from app.core.storage import delete_file, save_bytes +from app.semana.models import Semana + +import_module("app.challenges.models.challenge") +import_module("app.users.models") + +DATA_DIR = Path(__file__).resolve().parent / "data" +SCHEDULE_FILE = DATA_DIR / "palestras.tsv" +SPEAKER_IMAGES_DIR = DATA_DIR / "imagens_palestrantes" +LOCAL_TIMEZONE = ZoneInfo("America/Sao_Paulo") +SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"} + +ACTIVITY_TYPES = { + "Palestra": TipoAtividade.PALESTRA, + "Workshop": TipoAtividade.WORKSHOP, + "Encerramento": TipoAtividade.ENCERRAMENTO, + "Conversa": TipoAtividade.CONVERSA, +} + + +@asynccontextmanager +async def session_scope(settings: Settings) -> AsyncGenerator[AsyncSession, None]: + engine, session_factory = create_database(settings) + try: + async with session_factory() as session: + try: + yield session + await session.commit() + except Exception: + await session.rollback() + raise + finally: + await engine.dispose() + + +def load_schedule() -> list[dict]: + required_columns = { + "Título da atividade", + "Descrição da atividade", + "Tipo de Atividade", + "Horas", + "Pontos", + "Localização", + "Horário Começo", + "Horário Término", + "Nomes dos palestrantes", + "Arquivos de Imagem", + "Descrições dos palestrantes", + } + with SCHEDULE_FILE.open(encoding="utf-8-sig", newline="") as file: + reader = csv.DictReader(file, delimiter="\t") + if reader.fieldnames is None or not required_columns.issubset( + reader.fieldnames + ): + raise ValueError(f"Unexpected columns in {SCHEDULE_FILE}.") + if len(reader.fieldnames) != len(set(reader.fieldnames)): + raise ValueError(f"Duplicate columns in {SCHEDULE_FILE}.") + + schedule = [] + seen_titles = set() + for line_number, row in enumerate(reader, start=2): + if None in row or any(value is None for value in row.values()): + raise ValueError( + f"Invalid number of columns on TSV line {line_number}." + ) + + title = row["Título da atividade"].strip() + activity_type = ACTIVITY_TYPES.get(row["Tipo de Atividade"].strip()) + if not title or activity_type is None: + raise ValueError( + f"Invalid title or activity type on TSV line {line_number}." + ) + if title in seen_titles: + raise ValueError(f"Duplicate activity title on TSV line {line_number}.") + if len(title) > 255: + raise ValueError( + f"Activity title is too long on TSV line {line_number}." + ) + + description = row["Descrição da atividade"].strip() or None + location = row["Localização"].strip() or None + if description is not None and len(description) > 5000: + raise ValueError(f"Description is too long on TSV line {line_number}.") + if location is not None and len(location) > 255: + raise ValueError(f"Location is too long on TSV line {line_number}.") + + try: + starts_at = datetime.strptime( + row["Horário Começo"].strip(), "%d/%m/%Y %H:%M:%S" + ).replace(tzinfo=LOCAL_TIMEZONE) + ends_at = datetime.strptime( + row["Horário Término"].strip(), "%d/%m/%Y %H:%M:%S" + ).replace(tzinfo=LOCAL_TIMEZONE) + hours = int(row["Horas"]) + points = int(row["Pontos"]) + except ValueError as error: + raise ValueError( + f"Invalid date or numeric value on TSV line {line_number}." + ) from error + if ends_at <= starts_at: + raise ValueError(f"Invalid schedule on TSV line {line_number}.") + if starts_at.year != 2026 or ends_at.year != 2026: + raise ValueError( + f"Schedule is outside the 2026 event on TSV line {line_number}." + ) + if hours < 1 or points < 0: + raise ValueError(f"Invalid hours or points on TSV line {line_number}.") + + speakers = [] + speaker_fields = [ + [value.strip() for value in row[field].split("|")] + for field in ( + "Nomes dos palestrantes", + "Arquivos de Imagem", + "Descrições dos palestrantes", + ) + ] + if len({len(values) for values in speaker_fields}) != 1: + raise ValueError( + f"Speaker columns have different counts on TSV line {line_number}." + ) + + for speaker_number, (name, image_name, bio) in enumerate( + zip(*speaker_fields, strict=True), start=1 + ): + name, image_name, bio = name.strip(), image_name.strip(), bio.strip() + if not any((name, image_name, bio)): + continue + if not name: + raise ValueError( + f"Speaker name is missing on TSV line {line_number}, " + f"speaker {speaker_number}." + ) + if not image_name: + raise ValueError( + f"Speaker image is missing on TSV line {line_number}, " + f"speaker {speaker_number}." + ) + if not bio: + raise ValueError( + f"Speaker bio is missing on TSV line {line_number}, " + f"speaker {speaker_number}." + ) + if Path(image_name).name != image_name or "\\" in image_name: + raise ValueError( + f"Invalid speaker image path on TSV line {line_number}." + ) + + image_path = SPEAKER_IMAGES_DIR / image_name if image_name else None + if image_path.suffix.lower() not in SUPPORTED_IMAGE_EXTENSIONS: + raise ValueError( + f"Unsupported speaker image type on TSV line {line_number}: " + f"{image_path.suffix}" + ) + if not image_path.is_file(): + raise FileNotFoundError( + f"Speaker image not found on TSV line {line_number}: {image_path}" + ) + if not 0 < image_path.stat().st_size <= MAX_IMAGE_BYTES: + raise ValueError( + f"Speaker image has an invalid size on TSV line {line_number}: " + f"{image_path}" + ) + speakers.append({"nome": name, "sobre": bio, "image_path": image_path}) + + schedule.append( + { + "tipo": activity_type, + "titulo": title, + "descricao": description, + "local": location, + "speakers": speakers, + "comeca_as": starts_at, + "termina_as": ends_at, + "pontos": points, + "horas": hours, + } + ) + seen_titles.add(title) + if not schedule: + raise ValueError(f"No activities found in {SCHEDULE_FILE}.") + return schedule + + +async def main() -> None: + settings = get_settings() + schedule = load_schedule() + stored_images = [] + created_count = 0 + skipped_count = 0 + try: + async with session_scope(settings) as session: + event = await session.scalar(select(Semana).where(Semana.ano == 2026)) + if event is None: + event = Semana(nome="Semana da Computação 2026", ano=2026) + session.add(event) + await session.flush() + + activities = await session.scalars( + select(Atividade).where(Atividade.semana_id == event.id) + ) + existing_titles = {activity.titulo for activity in activities.all()} + + for item in schedule: + if item["titulo"] in existing_titles: + skipped_count += 1 + continue + + speakers = [] + for speaker in item["speakers"]: + speaker_data = { + "nome": speaker["nome"], + "sobre": speaker["sobre"], + } + image_path = speaker["image_path"] + if image_path is not None: + extension = image_path.suffix.lstrip(".").lower() + relative_path = await save_bytes( + image_path.read_bytes(), + subdir="palestrantes", + extension=extension, + ) + stored_images.append(relative_path) + speaker_data["foto"] = f"/media/{relative_path}" + speakers.append(speaker_data) + + activity_fields = { + key: value for key, value in item.items() if key != "speakers" + } + await create_atividade( + session, + event, + **activity_fields, + palestrantes=speakers, + link_live=None, + status=StatusAtividade.CONFIRMADA, + ) + existing_titles.add(item["titulo"]) + created_count += 1 + except Exception: + for relative_path in stored_images: + delete_file(relative_path) + raise + + print(f"Semana: {event.id} ({event.nome} {event.ano})") + print( + f"Activities created: {created_count}; " + f"existing activities skipped: {skipped_count}." + ) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/backend/scripts/seed_usernames.py b/backend/scripts/seed_usernames.py deleted file mode 100755 index 37318ad1..00000000 --- a/backend/scripts/seed_usernames.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python3 - -import asyncio -from collections.abc import AsyncIterator -from contextlib import asynccontextmanager -from pathlib import Path - -from sqlalchemy.ext.asyncio import AsyncSession - -from app.core.config import get_settings -from app.core.database import create_database -from app.users.username.seed import seed_from_csv_files - -DATA_DIR = Path(__file__).parent / "data" - - -@asynccontextmanager -async def _session_scope() -> AsyncIterator[AsyncSession]: - settings = get_settings() - engine, session_factory = create_database(settings) - try: - async with session_factory() as session: - try: - yield session - await session.commit() - except Exception: - await session.rollback() - raise - finally: - await engine.dispose() - - -async def main() -> None: - async with _session_scope() as session: - n_mothers, n_usernames = await seed_from_csv_files( - session, - DATA_DIR / "mothers.csv", - DATA_DIR / "usernames.csv", - ) - print(f"Seed concluído: {n_mothers} mothers, {n_usernames} usernames.") - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/backend/uv.lock b/backend/uv.lock index 90262489..cc81ee1d 100644 --- a/backend/uv.lock +++ b/backend/uv.lock @@ -179,6 +179,8 @@ dependencies = [ { name = "alembic" }, { name = "asyncpg" }, { name = "fastapi", extra = ["standard"] }, + { name = "httpx" }, + { name = "itsdangerous" }, { name = "pwdlib", extra = ["argon2"] }, { name = "pyjwt" }, { name = "sqlalchemy" }, @@ -197,6 +199,8 @@ requires-dist = [ { name = "alembic", specifier = ">=1.18.5" }, { name = "asyncpg", specifier = ">=0.31.0" }, { name = "fastapi", extras = ["standard"], specifier = ">=0.141.1" }, + { name = "httpx", specifier = ">=0.28.1" }, + { name = "itsdangerous", specifier = ">=2.2.0" }, { name = "pwdlib", extras = ["argon2"], specifier = ">=0.2.0" }, { name = "pyjwt", specifier = ">=2.13.0" }, { name = "sqlalchemy", specifier = ">=2.0.51" }, @@ -659,8 +663,8 @@ name = "httpcore2" version = "2.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11" }, - { name = "truststore" }, + { name = "h11", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" }, + { name = "truststore", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/be/ad/f4f0e57345f1870f3e8cb624e058d7eca6e5a27d33bcc3311d9b618734cd/httpcore2-2.12.0.tar.gz", hash = "sha256:9293522bba0aa7c4c8e9e3f040c16575bd8868e155a77fa30c7a9085a5eae648", size = 67548, upload-time = "2026-08-18T13:22:08.211Z" } wheels = [ @@ -769,6 +773,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "itsdangerous" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9c/cb/8ac0172223afbccb63986cc25049b154ecfb5e85932587206f42317be31d/itsdangerous-2.2.0.tar.gz", hash = "sha256:e0050c0b7da1eea53ffaf149c0cfbb5c6e2e2b69c4bef22c81fa6eb73e5f6173", size = 54410, upload-time = "2024-04-16T21:28:15.614Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/96/92447566d16df59b2a776c0fb82dbc4d9e07cd95062562af01e408583fc4/itsdangerous-2.2.0-py3-none-any.whl", hash = "sha256:c6242fc49e35958c8b15141343aa660db5fc54d4f13a1db01a3f5891b98700ef", size = 16234, upload-time = "2024-04-16T21:28:14.499Z" }, +] + [[package]] name = "jinja2" version = "3.1.6" diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 1cb66751..dfa84406 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -25,7 +25,9 @@ services: DATABASE_URL: postgresql+asyncpg://postgres:postgres@postgres:5432/symcomp SECRET_KEY: local-development-only-do-not-use-in-production ISSUER: http://localhost:8000 + CORS_ORIGINS: '["http://localhost:3000"]' entrypoint: ["/bin/sh", "/app/entrypoint.sh"] + command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] depends_on: postgres: condition: service_healthy diff --git a/docker-compose.yml b/docker-compose.yml index 28db0425..e02532b3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -45,6 +45,8 @@ services: context: ./backend target: production restart: unless-stopped + env_file: + - .env environment: APP_ENV: prod DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER:?Set POSTGRES_USER}:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:?Set POSTGRES_DB} @@ -59,7 +61,7 @@ services: volumes: - media_data:/app/media entrypoint: ["/bin/sh", "/app/entrypoint.sh"] - command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers"] + command: ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "3", "--proxy-headers"] healthcheck: test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/v1/health', timeout=3)"] interval: 15s diff --git a/frontend/next.config.mjs b/frontend/next.config.mjs index 2908f596..92bff93f 100755 --- a/frontend/next.config.mjs +++ b/frontend/next.config.mjs @@ -2,15 +2,18 @@ const nextConfig = { output: 'standalone', async rewrites() { - const backendUrl = process.env.INTERNAL_API_URL || 'http://backend:8000' + const backendUrl = process.env.INTERNAL_API_URL || 'http://localhost:8000' return [ { source: '/api/:path*', destination: `${backendUrl}/api/:path*`, }, + { + source: '/media/:path*', + destination: `${backendUrl}/media/:path*`, + }, ] }, } export default nextConfig - diff --git a/frontend/public/logo/ime_usp.svg b/frontend/public/logo/ime_usp.svg index 917003c1..fb93672e 100644 --- a/frontend/public/logo/ime_usp.svg +++ b/frontend/public/logo/ime_usp.svg @@ -1,8 +1,8 @@ - - - - - - - + + + + + + + diff --git a/frontend/public/semana/2026/identidade-visual-symcomp.svg b/frontend/public/semana/2026/identidade-visual-symcomp.svg new file mode 100644 index 00000000..60b503e4 --- /dev/null +++ b/frontend/public/semana/2026/identidade-visual-symcomp.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/frontend/public/semana/2026/logo-horizontal.svg b/frontend/public/semana/2026/logo-horizontal.svg new file mode 100644 index 00000000..2073ea59 --- /dev/null +++ b/frontend/public/semana/2026/logo-horizontal.svg @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/frontend/public/semana/2026/logo-plate.svg b/frontend/public/semana/2026/logo-plate.svg new file mode 100644 index 00000000..27da48b2 --- /dev/null +++ b/frontend/public/semana/2026/logo-plate.svg @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/frontend/public/semana/2026/possible_background.png b/frontend/public/semana/2026/possible_background.png new file mode 100644 index 00000000..1b2b28cd Binary files /dev/null and b/frontend/public/semana/2026/possible_background.png differ diff --git a/frontend/public/semana/2026/sponsors/asper.jpeg b/frontend/public/semana/2026/sponsors/asper.jpeg new file mode 100644 index 00000000..762b4661 Binary files /dev/null and b/frontend/public/semana/2026/sponsors/asper.jpeg differ diff --git a/frontend/public/semana/2026/sponsors/incognia.png b/frontend/public/semana/2026/sponsors/incognia.png new file mode 100644 index 00000000..54486fe9 Binary files /dev/null and b/frontend/public/semana/2026/sponsors/incognia.png differ diff --git a/frontend/public/semana/2026/sponsors/tako.jpeg b/frontend/public/semana/2026/sponsors/tako.jpeg new file mode 100644 index 00000000..0e36f5a7 Binary files /dev/null and b/frontend/public/semana/2026/sponsors/tako.jpeg differ diff --git a/frontend/src/app/admin/page.tsx b/frontend/src/app/admin/page.tsx new file mode 100644 index 00000000..5453183d --- /dev/null +++ b/frontend/src/app/admin/page.tsx @@ -0,0 +1,10 @@ +import { AuthProvider } from '@/features/auth/auth-provider' +import { AdminPanel } from '@/features/admin/components/admin-panel' + +export default function AdminPage() { + return ( + + + + ) +} diff --git a/frontend/src/app/favicon.ico b/frontend/src/app/favicon.ico deleted file mode 100755 index 83707813..00000000 Binary files a/frontend/src/app/favicon.ico and /dev/null differ diff --git a/frontend/src/app/icon.png b/frontend/src/app/icon.png new file mode 100644 index 00000000..746e7791 Binary files /dev/null and b/frontend/src/app/icon.png differ diff --git a/frontend/src/app/semana/(site)/desafios/[id]/page.tsx b/frontend/src/app/semana/(site)/desafios/[id]/page.tsx new file mode 100644 index 00000000..9a278422 --- /dev/null +++ b/frontend/src/app/semana/(site)/desafios/[id]/page.tsx @@ -0,0 +1,5 @@ +import { ChallengePage } from '@/features/challenges/components/challenge-page' + +export default function ChallengeRoutePage() { + return +} diff --git a/frontend/src/app/semana/(site)/desafios/page.tsx b/frontend/src/app/semana/(site)/desafios/page.tsx new file mode 100644 index 00000000..b8923b36 --- /dev/null +++ b/frontend/src/app/semana/(site)/desafios/page.tsx @@ -0,0 +1,5 @@ +import { ChallengeListPage } from '@/features/challenges/components/challenge-list-page' + +export default function DesafiosPage() { + return +} diff --git a/frontend/src/app/semana/(site)/inicio/page.tsx b/frontend/src/app/semana/(site)/inicio/page.tsx index f6711ffb..38f73df9 100644 --- a/frontend/src/app/semana/(site)/inicio/page.tsx +++ b/frontend/src/app/semana/(site)/inicio/page.tsx @@ -1,5 +1,5 @@ -import { SemanaHome } from '@/features/semana/components/semana-home' +import { redirect } from 'next/navigation' export default function SemanaInicioPage() { - return + redirect('/semana') } diff --git a/frontend/src/app/semana/(site)/login/page.tsx b/frontend/src/app/semana/(site)/login/page.tsx index 9f902358..9529f267 100644 --- a/frontend/src/app/semana/(site)/login/page.tsx +++ b/frontend/src/app/semana/(site)/login/page.tsx @@ -1,7 +1,24 @@ import { AuthCard } from '@/features/auth/components/auth-card' import { LoginForm } from '@/features/auth/components/login-form' -export default function LoginPage() { +const oauthErrors: Record = { + provider_unavailable: 'Este método de login ainda não está configurado.', + invalid_provider: 'Provedor de autenticação inválido.', + oauth_state: 'A tentativa de login expirou ou é inválida. Tente novamente.', + oauth_denied: 'A autenticação foi cancelada.', + oauth_invalid_profile: 'Não foi possível validar sua conta no provedor.', + oauth_profile: 'O provedor não forneceu os dados necessários.', + oauth_unverified_email: 'Confirme seu e-mail no provedor antes de continuar.', + oauth_provider_error: 'O provedor não concluiu a autenticação. Tente novamente.', + email_exists: 'Este e-mail já possui cadastro. Entre usando e-mail e senha.', +} + +export default async function LoginPage({ + searchParams, +}: { + searchParams: Promise<{ error?: string }> +}) { + const { error } = await searchParams return ( + {error && oauthErrors[error] && ( +

+ {oauthErrors[error]} +

+ )} ) diff --git a/frontend/src/app/semana/(site)/patrocinadores/page.tsx b/frontend/src/app/semana/(site)/patrocinadores/page.tsx new file mode 100644 index 00000000..d934c0cc --- /dev/null +++ b/frontend/src/app/semana/(site)/patrocinadores/page.tsx @@ -0,0 +1,12 @@ +import type { Metadata } from 'next' + +import { SponsorsPage } from '@/features/semana/components/sponsors-page' + +export const metadata: Metadata = { + description: + 'Conheça as empresas patrocinadoras da 16ª Semana da Computação do IME USP.', +} + +export default function PatrocinadoresPage() { + return +} diff --git a/frontend/src/app/semana/(site)/presenca/page.tsx b/frontend/src/app/semana/(site)/presenca/page.tsx new file mode 100644 index 00000000..e5bc95b7 --- /dev/null +++ b/frontend/src/app/semana/(site)/presenca/page.tsx @@ -0,0 +1,5 @@ +import { AttendancePage } from '@/features/attendance/components/attendance-page' + +export default function AttendanceRoute() { + return +} diff --git a/frontend/src/app/semana/(site)/privacy/page.tsx b/frontend/src/app/semana/(site)/privacy/page.tsx new file mode 100644 index 00000000..dedfd5d9 --- /dev/null +++ b/frontend/src/app/semana/(site)/privacy/page.tsx @@ -0,0 +1,41 @@ +import type { Metadata } from 'next' +import Script from 'next/script' + +export const metadata: Metadata = { + title: 'Política de Privacidade | Semana da Computação', + description: 'Política de privacidade da Semana da Computação.', +} + +export default function PrivacyPage() { + return ( +
+