[Refactor] Remover uso de mock e padronizar consumo da api no appointmentservice#604
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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
📒 Files selected for processing (7)
apps/apae/src/app/page.tsxapps/apae/src/app/services/appointmentService.tsapps/api/src/main/java/br/org/apae/api/appointment/application/interfaces/AppointmentApplicationService.javaapps/api/src/main/java/br/org/apae/api/appointment/application/internal/AppointmentApplicationServiceImpl.javaapps/api/src/main/java/br/org/apae/api/appointment/domain/repository/GeneratedAppointmentRepository.javaapps/api/src/main/java/br/org/apae/api/appointment/interfaces/controllers/AppointmentController.javaapps/api/src/main/java/br/org/apae/api/controllers/appointment/AppointmentControllerImpl.java
JoaoGabrielCosta2004
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
apps/apae/src/app/services/appointmentService.tsapps/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
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
Evidências
Tela de agendamento do dia listando todos os agendamentos:
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Improvements