Skip to content

fix(journey): restore patient journey contract#76

Open
rafaellucian0 wants to merge 80 commits into
mainfrom
hotfix/test-e2e
Open

fix(journey): restore patient journey contract#76
rafaellucian0 wants to merge 80 commits into
mainfrom
hotfix/test-e2e

Conversation

@rafaellucian0

Copy link
Copy Markdown
Collaborator

Resumo

Corrige o contrato do endpoint de jornada do paciente e restaura a integração com doses, consultas e eventos persistidos.

Também resolve os conflitos existentes com a branch main.

Validação

  • Backend: 265 testes aprovados
  • Ruff check/format: aprovado
  • Frontend build: aprovado
  • Frontend tests: falham por erros preexistentes não relacionados

sarahdomingos and others added 30 commits May 19, 2026 13:46
- Added new CI workflow for managing linting, testing, and security checks.
- Updated build workflow to include Docker image validation and improved environment setup.
- Integrated PostgreSQL and Redis services for testing.
- Enhanced Dockerfile for better dependency management and added health checks.
- Updated Python dependencies in pyproject.toml to include coverage and other testing tools.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>
Co-authored-by: Lucas Heron <lhsa@ic.ufal.br>
Co-authored-by: Sarah Domingos <sdls@ic.ufal.br>
Co-authored-by: Leila Biggi <leilamariabiggi@outlook.com>
* feat: add treatment and dose management features

- Introduced new models for DoseLog, AdherenceSnapshot, HealthProfessional, Symptom, Treatment, and DoseSchedule.
- Implemented repositories for managing doses, health professionals, treatments, and symptoms.
- Created use cases for registering doses, creating treatments, and retrieving adherence data.
- Added API routes for treatment management, including creating treatments, registering doses, and fetching adherence snapshots.
- Updated main.py to include new routers for treatments and symptoms.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* feat: create treatments and related tables

- Added migration script to create health_professionals, symptoms, treatments, dose_schedules, and dose_logs tables.
- Defined ENUM types for symptom categories, treatment regimens, treatment statuses, and dose frequencies.
- Established foreign key relationships for treatments and health professionals.
- Included necessary indexes for efficient querying of treatments and dose schedules.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* feat(tests): add integration and unit tests for dose registration and adherence calculation

- Introduced integration tests for the dose registration flow, covering scenarios such as successful dose registration, handling of duplicate doses, and access restrictions for health professionals from different units.
- Added unit tests for the AdherenceService, validating the calculation of adherence percentages under various conditions, including edge cases and parameterized tests.

These tests ensure robust functionality.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* feat: add API endpoints for treatment and dose management

- Introduced new endpoints for registering doses, creating treatments, retrieving treatment details, and listing symptoms.
- Implemented request and response structures, including necessary authentication and validation.
- Added documentation for each endpoint, detailing usage, rate limits, and access restrictions.

These additions enhance the treatment management capabilities of the application.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* fix(treatment): apply PR #17 review feedback

- Validate token sub/role via get_actor_from_token (401 on corrupt UUID)
- Replace deprecated HTTP_422_UNPROCESSABLE_ENTITY with HTTP_422_UNPROCESSABLE_CONTENT
- Log duplicate dose attempts in DoseRepository for audit trail
- Reduce symptoms endpoint rate limit to 50/minute
- Document WHO MDT regimen codes (PB/MB) and add DoseSchedule.validate_dose_mg

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(config): add method to safely derive test database URL

- Introduced `get_test_database_url` method in the Settings class to handle test database URL derivation securely, avoiding potential user corruption in the URL.
- Updated test configuration to utilize the new method for obtaining the test database URL.
- Added unit tests to ensure correct behavior of the new method under various scenarios, including explicit settings and CI configurations.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* chore(ci): enhance workflow configurations and environment setup

- Updated build and test workflows to improve environment variable handling, including the addition of DATABASE_URL_TEST for testing purposes.
- Refactored the creation of the .env file to use a heredoc for better readability and maintainability.
- Enhanced CI triggers to include release, hotfix, and feature branches for more comprehensive coverage.
- Improved health check configurations for PostgreSQL and Redis services in the test environment.

These changes aim to streamline the CI/CD process and ensure a more robust testing environment.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* chore: apply ruff format to files failing CI lint

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(alembic): evita DuplicateObjectError em ENUMs da migration 004

Centraliza tipos PostgreSQL em pequi.db.pg_enums e reutiliza
postgresql.ENUM com create_type=False nas colunas após create único.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…21)

Expand targeted unit tests and coverage config so CI can reach the 80% threshold without inflating metrics on infrastructure-only modules.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>
* feat: implement patient check-in system with automated alert evaluation and AI feedback background processing

* feat: implement alert system and check-in history functionality with supporting repositories and service logic

* feat: implement check-in system with use cases, repositories, async job queueing, and integration tests

* fix: resolve CI blockers and improve data access audit logging

* fix: resolve CI blockers (migration enum, trivy version)

* fix: format migration file with ruff

* fix: remove unnecessary PR description files

* fix: resolve CI failures in security and tests jobs

- Update trivy-action to valid version 0.27.0
- Fix PostgreSQL syntax error in checkins index using DATE() function

* fix: use trivy-action@master to resolve version not found error

* fix: correct Bandit SARIF path and update CodeQL action to v4

* fix: remove Bandit SARIF upload (Bandit doesn't support SARIF format)

* fix: pin uv version and add --no-cache-dir to satisfy Hadolint

* fix: add continue-on-error to Gitleaks step to bypass license requirement
[PEQ-41]: Criar escala de intensidade dos sintomas
[PEQ-128]: trocar a ordem de como esta se sentindo no checkin
* feat: add body map functionality with models, repositories, and API endpoints

- Introduced BodyArea, BodyMapEntry, and BodyAreaHistory models to represent body mapping data.
- Implemented BodyMapRepository for database interactions related to body map entries and areas.
- Created API endpoints for managing body maps, including retrieval, updates, and upload URL generation.
- Added use cases for handling body map history and updates, ensuring proper validation and error handling.
- Integrated body map functionality into existing check-in processes to enhance patient data tracking.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* feat: create body map tables and related functionality

- Added migration script to create body map tables: body_areas, body_map_entries, and body_area_history.
- Introduced ENUM types for body sides, system parts, and finding types to standardize data entries.
- Implemented bulk insert for initial body area data to enhance patient mapping capabilities.
- Established foreign key constraints and indexes to optimize data integrity and query performance.

This update lays the groundwork for enhanced body mapping features in the application.

* tests(body map): add integration and unit tests for body map functionality

- Introduced integration tests for body map API endpoints, covering body area creation, updates, and retrieval.
- Implemented unit tests for BodyMapUpdateRequest schema validation, ensuring proper handling of intensity and finding type constraints.
- Enhanced test coverage for body mapping features to ensure robustness and reliability in the application.

These additions improve the overall test suite and validate the functionality of the body map features.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* feat: add body map API endpoints for retrieval and updates

- Introduced new endpoints for getting the current body map, its history, and listing body areas.
- Implemented functionality for updating the body map with entries and handling invalid area updates.
- Added image upload capabilities with validation for file types.

These additions enhance the body mapping features, providing comprehensive access and management of patient body map data.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* refactor: remove unused UTC import from test_body_map.py

- Cleaned up the import statements in the integration test file by removing the unused UTC import, streamlining the code for better readability and maintainability.

* refactor: remove unused import from test_body_map.py

- Eliminated the unused import of `datetime` from the integration test file, improving code clarity and maintainability.

* chore: add datetime import to test_body_map.py

- Included the `datetime` import in the integration test file to facilitate date handling in future test cases. This addition prepares the file for upcoming enhancements related to date functionalities.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* chore: update ruff configuration to ignore E501 for alembic version files

- Added a per-file ignore rule for E501 (line too long) in alembic version files to accommodate longer lines without triggering linting errors. This adjustment helps maintain code quality while allowing necessary flexibility in version scripts.

* refactor: optimize body area data insertion in migration script

- Replaced the bulk insert method with a direct SQL execution

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>

* fix(body-map): apply PR #24 review feedback

Preserve test DB password in derived URL, validate upload file extensions,
harden professional tenant checks when health_unit_id is missing, inject
StorageService via Depends, and return 422 when patient_id is omitted.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: implement anonymous community module with post, comment, like, and moderation features

* feat: implement audit logging system and administrative moderation use cases for community management

* fix: resolve NameError in community router by moving repository imports to module level and add documentation for code reviews

* fix: ruff lint errors

* fix: ruff format error

* fix: migrations error

* fix: tests with coverage errors

* fix: coverage response

* fix: undo test deleted and post response

* fix: implement community module with database schema, models, and toggle-like use case

* fix: raise exception error

* fix: ruff variables errors

Co-authored-by: Matheus Ryan <mrysn@ic.ufal.br>
…eature (#28)

* PEQ-49-51-124: Profile feature and fixing some stuff in appointment feature

* fix: changed the medication tab to choose unit and frequency
* feat(articles): implement M7 educational articles library (PEQ-82)

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(migration): linearize alembic chain after M6 community branch

Articles migration now revises 007_create_community; audit_logs revises
007_create_articles so CI has a single head for alembic upgrade head.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(articles): assert view_count via repo in same transaction

Background task commits in a separate session; integration tests use
rollback transactions, so increment_article_view_count cannot see uncommitted rows.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(articles): address PR #30 review (PEQ-82)

- Rename migrations to 008_create_articles and 009_create_audit_logs
- Add audit logging for admin create/update/delete article actions
- Use atomic SQL for view_count increment with error handling in task
- Improve slug fallback for non-Latin titles; register article models in conftest

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(articles): reload article after update to avoid async lazy-load

Partial refresh expired scalars like updated_at and triggered
MissingGreenlet when building ArticleResponse after audit log write.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
* build(nginx): Add production-ready Docker Compose and Nginx configuration

* build(nginx): Add nginx/certs/ to .gitignore

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>
lawtherea and others added 16 commits June 6, 2026 08:39
* fix(community): create patient profiles for users

* feat/integrated community feature with back

---------

Co-authored-by: rafaellucian0 <rafael.ifal2018@gmail.com>
…ara cartilha do paciente (#65)

* fix(community): create patient profiles for users

* feat/integrated community feature with back

* feat/implementing and integrating my treatment, my data, medication, appointments and cartilha export

* [fix] added success toasts when saving personal data and fixing ruff errors

* [fix] ruff format

---------

Co-authored-by: rafaellucian0 <rafael.ifal2018@gmail.com>
…e compilação (#66)

* feat(staging): add staging environment configuration and build settings

* fix(docs): correct note formatting in README
* feat: add journey endpoint and related use case for patient treatment journey

- Introduced a new router for patient journey with endpoint /v1/journey.
- Implemented GetPatientJourneyUseCase to fetch the treatment journey for authenticated patients.
- Added JourneyService to calculate treatment progress, timeline, and summary.
- Updated schemas for journey response, including events and monthly summaries.
- Refactored treatment and dose models to remove unnecessary fields and dependencies on health professionals.
- Adjusted treatment creation and dose registration logic to allow patient self-management.
- Enhanced adherence and treatment retrieval use cases to restrict access to patient-owned data.

* feat: update treatment and journey endpoints for patient authentication and dose registration

* refactor(migrations): remove professional fields from treatments and dose_logs

* Refactor( treatment)related tests and remove unnecessary professional references

- Updated tests in `test_alert_after_checkin.py` and `test_dose_flow.py` to remove the need for health professional creation during treatment setup.
- Simplified treatment creation logic in tests by removing the `prescribed_by` field.
- Added new integration tests for patient journey in `test_journey_flow.py` to validate journey retrieval with doses and consultations.
- Enhanced existing tests in `test_patient_health_appointment.py` and `test_patient_treatment_record.py` to align with the new treatment structure.
- Introduced unit tests for `JourneyService` to validate journey calculations and event handling.
- Updated treatment use case tests to ensure proper validation when creating treatments without active professionals.

* feat(doses): Introduce v2 treatment endpoints and enhance dose registration logic

- Updated treatment router to include v2 endpoints for treatments and journeys.
- Added new treatment_v2 router with endpoints for creating treatments, getting treatment details, registering doses, and fetching adherence snapshots.
- Enhanced DoseRepository and TreatmentRepository to handle duplicate dose and treatment registrations with appropriate error handling.
- Introduced new schemas for v1 treatment and dose log responses to support the new API versioning.
- Refactored use cases to separate v1 and v2 logic for treatment creation, adherence fetching, and dose registration.
- Improved journey service to include skipped doses in the summary response.

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>
Co-authored-by: Sarah Domingos <sdls@ic.ufal.br>

* fix(routes): implement v2 endpoints for dose registration and treatment creation, update journey URL

* feat(treatments): add partial unique index for one active treatment per patient

* tests(treatment): add E2E tests for patient treatment endpoints and enhance journey service tests

* feat(treatments): add v2 endpoints for retrieving treatment and adherence snapshots

* feat(treatments): enhance treatment and dose models with new fields and constraints

* feat(tests): add E2E tests for legacy treatment and dose flow, including unique index conflict handling

* feat(treatments): make professional treatment fields optional for patient-only v2

* test(treatments): fix appointment dose regression test

* feat(journey): persist and unify treatment events

---------

Co-authored-by: Rafael Luciano <rafael.ifal2018@gmail.com>
Co-authored-by: Sarah Domingos <sdls@ic.ufal.br>
* calendar integration

* fix: mapeamento de humor

* fix: lint error

* feat: integra consultas no calendário

* fix: muda cor dos pontos no calendário
* feat: front da tela de jornada finalizado

* test: correção de testes com bugs

* feat: journey funciona integrado, mas sem medication/alerts integrados

* style: ajuste na ordem de prioridade de mês atual

* feat: journey funciona com medicamentos + card medicamentos na home integrado

* fix: lint errors

* fix: try to retest

* fix: ruff organize

* fix: organize import

* fix: apply alembic ruff suggestions

---------

Co-authored-by: Lucas Heron <lsantosanchieta@gmail.com>
# Conflicts:
#	backend/src/pequi/routers/journey.py
#	backend/src/pequi/routers/patient.py
#	backend/src/pequi/use_cases/get_patient_journey.py
#	frontend/src/app/features/checkin/services/checkin.service.ts
@rafaellucian0 rafaellucian0 requested review from LukeHer0, TETEURYAN, lawtherea and sarahdomingos and removed request for TETEURYAN and sarahdomingos June 9, 2026 11:12

@TETEURYAN TETEURYAN left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Erros apresentados em bateria de testes

A bateria de testes ainda possui erro em 6 testes. Corrigir

@TETEURYAN TETEURYAN added the bug Something isn't working label Jun 9, 2026
@TETEURYAN TETEURYAN self-requested a review June 11, 2026 17:06

@TETEURYAN TETEURYAN left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Camadas ocultas

Aplicação da PIR está inconsistente e com falhas graves de segurança.

...,
ge=0,
description="Quantidade de doses/checkboxes marcados como tomados no dia",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Eu adicionaria isso para garantir validação em todas as etapas

if data.expected_count < 0:
    raise ValidationFailedError(
        "expected_count não pode ser negativo."
    )

if data.taken_count < 0:
    raise ValidationFailedError(
        "taken_count não pode ser negativo."
    )



class GetDailyMedicationSummaryUseCase:
def __init__(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A regra de negócio está adequadamente inserida aqui?

Solicito revisão

@model_validator(mode="after")
def validate_counts(self):
    if self.taken_count > self.expected_count:
        raise ValueError(
            "taken_count não pode ser maior que expected_count."
        )
    return self

appointment_repo=HealthAppointmentRepository(session),
journey_event_repo=JourneyEventRepository(session),
)
return await use_case.execute(user_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

O problema é que nem todo IntegrityError é erro de validação do usuário.

Pode ser:

  • constraint inválida;
  • bug de migration;
  • banco inconsistente;
  • índice quebrado;
  • FK incorreta.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants