Skip to content

[Refactor] Remover uso de mock e padronizar consumo da api no appointmentservice#604

Merged
JoaoGabrielCosta2004 merged 4 commits intodevfrom
585-refactor-remover-uso-de-mock-e-padronizar-consumo-da-api-no-appointmentservice
Mar 30, 2026
Merged

[Refactor] Remover uso de mock e padronizar consumo da api no appointmentservice#604
JoaoGabrielCosta2004 merged 4 commits intodevfrom
585-refactor-remover-uso-de-mock-e-padronizar-consumo-da-api-no-appointmentservice

Conversation

@emanuelleGued
Copy link
Copy Markdown

@emanuelleGued emanuelleGued commented Mar 28, 2026

O que mudou?

Este PR refatora o appointmentService no frontend para consumir exclusivamente a API real, removendo todo o fallback automático para dados mockados.
Anteriormente, o uso da flag USE_MOCK_DATA e dos fallbacks estava mascarando erros da API, gerando inconsistências no formato das respostas e exibindo dados irReais nas telas. Com essa mudança, garantimos que a aplicação reflita o estado fiel do banco de dados e que os erros de requisição sejam devidamente propagados.

Tarefas Relacionadas

Mudanças Realizadas

  • Remoção de Mocks: Remoção completa da flag de controle de mock e de todos os fallbacks para dados estáticos dentro do appointmentService.ts.
  • Tratamento de Erros: Ajuste para garantir que erros da API sejam propagados corretamente para a interface, em vez de serem silenciados por retornos mockados.
  • Padronização de Retorno: Ajuste nas respostas das funções para respeitar o contrato esperado pelos componentes (ex: formato Page para listagens e agendamentos do dia).
  • Métodos Auxiliares: Refatoração de métodos como getPacientes e getProfissionaisDaSaude para manter consistência com o consumo da API real.
  • Compatibilidade: Manutenção das assinaturas dos métodos do serviço para garantir que nenhuma tela existente (Dashboard, listagens, etc.) precisasse de alterações estruturais.
  • Adição da Coluna de Horário: Implementação do LocalDate nas camadas de serviços, rotas (controllers) e repositórios para possibilitar a adição e o correto preenchimento da coluna "Horário" na tabela de listagem de agendamentos do dia.

Evidências

Tela de agendamento do dia listando todos os agendamentos:

Captura de Tela 2026-03-28 às 09 34 33

Summary by CodeRabbit

Release Notes

  • New Features

    • Added time display for each appointment in the table
    • Enhanced date-based appointment filtering capability
  • Bug Fixes

    • Improved error handling during appointment data retrieval
    • Added empty state message when no appointments found for selected date
  • Improvements

    • Updated UI text labels for improved clarity
    • Modified subtitle to display completed appointments count

@emanuelleGued emanuelleGued added this to the 2026.1 - Sprint 2 milestone Mar 28, 2026
@emanuelleGued emanuelleGued self-assigned this Mar 28, 2026
@emanuelleGued emanuelleGued added backend Lista de tarefas para backend database Lista de tarefas para banco de dados frontend Lista de tarefas para frontend bug Para correções de erros. hotfix Correções urgentes diretamente na produção Alta Refatoração Squad de refatoração agendamentos Refatorar e evoluir o módulo de agendamentos para garantir maior aderência às necessidades da APAE. 13 labels Mar 28, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 28, 2026

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 52228a2e-1d79-41c4-8d4e-3e2688322465

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • ✅ Review completed - (🔄 Check again to review again)
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 585-refactor-remover-uso-de-mock-e-padronizar-consumo-da-api-no-appointmentservice

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/apae/src/app/page.tsx`:
- Around line 61-70: The code is discarding pagination metadata by pulling only
page.content into state; instead preserve the full Page object so
totalElements/totalPages remain available. Update the state used by fetchers
(replace or add state variables referenced in fetchAllAppointments and the today
fetch — e.g., todayAppointmentsPage, setTodayAppointments, allAppointmentsPage /
setAllAppointments or similar) to store the full Page<TodayAppointment> and
Page<AppointmentResponseDTO> objects returned by listTodayAppointment and
getAppointments, and keep using page.content where the UI needs the array;
ensure any UI components that consume setTodayAppointments/setAllAppointments
are updated to read page.content and page.totalElements/totalPages as needed.

In `@apps/apae/src/app/services/appointmentService.ts`:
- Around line 315-318: Client is calling PUT /api/generated/{id}/... which
doesn't match the backend controller that exposes PATCH
/appointments/generated/{id}/reschedule and PATCH
/appointments/generated/{id}/cancel; update the fetch calls to use method:
"PATCH" and the correct path prefix
"/api/appointments/generated/${id}/reschedule" (and
"/api/appointments/generated/${id}/cancel") instead of
"/api/generated/${id}/...", keeping the existing headers and
JSON.stringify(backendDto) body; apply the same change to the other occurrence
that constructs the cancel request so both reschedule and cancel fetch calls
match the backend contract.
- Around line 311-313: The backendDto currently uses new
Date(dto.newDateTime).toISOString(), which converts to UTC and appends a Z;
instead format dto.newDateTime as a timezone‑naive LocalDateTime string
("yyyy-MM-dd'T'HH:mm:ss") so the wall‑clock is preserved for the backend
reschedule endpoint. Update the appointmentService code that builds backendDto
(the newDateTime assignment) to produce a local datetime string (e.g., via a
small helper like formatLocalDateTime(date) or using date methods/date-fns to
build "yyyy-MM-dd'T'HH:mm:ss") rather than toISOString().

In
`@apps/api/src/main/java/br/org/apae/api/appointment/application/internal/AppointmentApplicationServiceImpl.java`:
- Around line 340-365: The code in listAppointmentForToday currently uses a
broad catch(Exception) around patient/guardian lookups which masks expected
not-found cases; remove the blanket try/catch (or narrow it) so that lookup
failures from patientRepo.findById and guardianRepo.findByPatientId propagate
as-is (or throw specific NotFound exceptions), and only catch and wrap actual
mapping errors from mapper.toTodayResponseDTO or DTO construction if needed;
update the block around patientRepo.findById, guardianRepo.findByPatientId,
parentRepo.findAllByPatientId, vaccine mapping and mapper.toTodayResponseDTO so
that you don't convert lookup Optional.empty cases into a generic
RuntimeException.

In
`@apps/api/src/main/java/br/org/apae/api/appointment/domain/repository/GeneratedAppointmentRepository.java`:
- Around line 27-29: The query in
GeneratedAppointmentRepository.listAppointmentsForToday returns an unordered
Page which makes the "Horário" column jump; update the `@Query` to append a stable
ORDER BY using the same datetime expression and a tie-breaker id (e.g., ORDER BY
COALESCE(g.overriddenDateTime, g.scheduledDateTime), g.id) so results are
deterministically ordered when the client sends no sort; locate the `@Query`
annotation on listAppointmentsForToday and modify the JPQL string accordingly.

In
`@apps/api/src/main/java/br/org/apae/api/appointment/interfaces/controllers/AppointmentController.java`:
- Around line 78-80: The /today endpoint must preserve its old behavior by
treating a missing date as today; update the AppointmentController method
signature to accept an optional request param (e.g., annotate the LocalDate
parameter with `@RequestParam`(required = false)) and ensure the implementation
(or default in the controller) sets date = (date == null) ? LocalDate.now() :
date before calling the service; reference
AppointmentController.listTodayAppointment and TodayAppointmentsResponseDTO and
ensure clients in apps/apae/src/app/services/appointmentService.ts still work
without sending a date.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 391e147e-f40e-40b7-ad95-a42c321a3ac0

📥 Commits

Reviewing files that changed from the base of the PR and between d67cf2f and ef839d2.

📒 Files selected for processing (7)
  • apps/apae/src/app/page.tsx
  • apps/apae/src/app/services/appointmentService.ts
  • apps/api/src/main/java/br/org/apae/api/appointment/application/interfaces/AppointmentApplicationService.java
  • apps/api/src/main/java/br/org/apae/api/appointment/application/internal/AppointmentApplicationServiceImpl.java
  • apps/api/src/main/java/br/org/apae/api/appointment/domain/repository/GeneratedAppointmentRepository.java
  • apps/api/src/main/java/br/org/apae/api/appointment/interfaces/controllers/AppointmentController.java
  • apps/api/src/main/java/br/org/apae/api/controllers/appointment/AppointmentControllerImpl.java

Comment thread apps/apae/src/app/page.tsx
Comment thread apps/apae/src/app/services/appointmentService.ts
Comment thread apps/apae/src/app/services/appointmentService.ts Outdated
Copy link
Copy Markdown
Collaborator

@JoaoGabrielCosta2004 JoaoGabrielCosta2004 left a comment

Choose a reason for hiding this comment

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

Deixei uns comentários pra resolver. Tirando um que eu acho que dê mais trabalho, os outros dois foram somente uns erros de digitação mais leves.

Comment thread apps/apae/src/app/services/appointmentService.ts Outdated
Comment thread apps/apae/src/app/services/appointmentService.ts
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/apae/src/app/services/appointmentService.ts`:
- Around line 420-429: getPacientes currently returns data.content || data || []
which can yield a non-array object and break the declared Promise<Patient[]>;
update getPacientes to explicitly resolve to an array by checking
Array.isArray(data.content) first and returning that, otherwise if data is an
array return data, else return []; apply the same pattern to the other fetch
helper(s) in this file (the analogous function around lines 431-440) so callers
always receive an array of Patients/Professionals.
- Line 414: Replace the mojibake in the thrown error messages by correcting the
corrupted PT-BR strings to proper UTF-8 (e.g., "ausência", "não",
"confirmação"); locate the throw new Error(...) occurrences in
appointmentService.ts (the three spots around the shown throw and the ones at
the other noted locations) and update the string literals to their correct
Portuguese spellings so logs and UX show readable messages.
- Around line 465-472: The DTO construction in toggleConfirmacao uses
appointment.hour.replace(":00","") which can produce "17" and break
saveAppointment; replace that with a stable HH:mm normalization: if
appointment.hour already matches /^\d{1,2}:\d{2}$/ ensure hour and minute are
zero-padded to two digits (e.g., padStart) and use that; if it is a bare hour
like "17" append ":00"; implement this in toggleConfirmacao (or call a small
helper normalizeTime) when setting CreateAppointmentDTO.hour so saveAppointment
always receives a "HH:mm" string.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6ee2df72-1559-41c7-900d-7c7160d6608a

📥 Commits

Reviewing files that changed from the base of the PR and between ef839d2 and 66cc247.

📒 Files selected for processing (2)
  • apps/apae/src/app/services/appointmentService.ts
  • apps/api/src/main/java/br/org/apae/api/appointment/application/interfaces/AppointmentApplicationService.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/api/src/main/java/br/org/apae/api/appointment/application/interfaces/AppointmentApplicationService.java

Comment thread apps/apae/src/app/services/appointmentService.ts
Comment thread apps/apae/src/app/services/appointmentService.ts
Comment thread apps/apae/src/app/services/appointmentService.ts
@JoaoGabrielCosta2004 JoaoGabrielCosta2004 merged commit 2e9c516 into dev Mar 30, 2026
7 checks passed
@thalesluiz45 thalesluiz45 deleted the 585-refactor-remover-uso-de-mock-e-padronizar-consumo-da-api-no-appointmentservice branch April 23, 2026 20:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

13 agendamentos Refatorar e evoluir o módulo de agendamentos para garantir maior aderência às necessidades da APAE. Alta backend Lista de tarefas para backend bug Para correções de erros. database Lista de tarefas para banco de dados frontend Lista de tarefas para frontend hotfix Correções urgentes diretamente na produção Refatoração Squad de refatoração

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants