Compare commits

..

No commits in common. "6c362e0d95fad66e6c34c3f388965c3c40be5ec3" and "f888085d47ce36d6237cd8274dd85c629cc294ca" have entirely different histories.

5 changed files with 139 additions and 294 deletions

View File

@ -61,11 +61,6 @@ class MedMapAPI {
return try await apiClient.request(url, method: .get) return try await apiClient.request(url, method: .get)
} }
func getMyPatientProfile() async throws -> PatientDTO {
let url = "\(baseURL)/api/patients/me"
return try await apiClient.request(url, method: .get)
}
func listPatients(professionalId: String) async throws -> PatientsByProfessionalResponse { func listPatients(professionalId: String) async throws -> PatientsByProfessionalResponse {
let url = "\(baseURL)/api/patients/list" let url = "\(baseURL)/api/patients/list"
return try await apiClient.request(url, method: .post, parameters: ListPatientsRequest(professionalId: professionalId)) return try await apiClient.request(url, method: .post, parameters: ListPatientsRequest(professionalId: professionalId))

View File

@ -1,13 +1,11 @@
import Foundation import Foundation
import SwiftUI import SwiftUI
import Combine import Combine
@MainActor @MainActor
final class DashboardViewModel: ViewModel { final class DashboardViewModel: ViewModel {
@Published private(set) var patient: PatientDTO?
@Published private(set) var prescriptions: [PrescriptionWithSchedulesResponse] = [] @Published private(set) var prescriptions: [PrescriptionWithSchedulesResponse] = []
@Published private(set) var medications: [String: MedicationDTO] = [:] @Published private(set) var medicationNames: [String: String] = [:]
@Published private(set) var errorMessage: String? @Published private(set) var errorMessage: String?
private let api: MedMapAPI private let api: MedMapAPI
@ -17,36 +15,23 @@ final class DashboardViewModel: ViewModel {
super.init() super.init()
} }
var patientAge: Int? { var nextDose: DashboardDose? {
guard let dateOfBirth = patient?.dateOfBirth else { return nil } scheduledDoses.first(where: { $0.time >= currentTime }) ?? scheduledDoses.first
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd"
guard let birthDate = formatter.date(from: dateOfBirth) else { return nil }
return Calendar.current.dateComponents([.year], from: birthDate, to: .now).year
} }
var totalDosesToday: Int { var scheduledDoses: [DashboardDose] {
medicationCards.reduce(0) { $0 + $1.doseTimes.count } prescriptions.flatMap { response in
} response.schedules.flatMap { schedule in
schedule.timesOfDay.map { time in
var medicationCards: [MedicationCard] { DashboardDose(
prescriptions.map { response in time: time,
let times = response.schedules title: medicationNames[response.medicationId] ?? "Medicacao prescrita",
.flatMap(\.timesOfDay) detail: response.prescription.instructions ?? doseDescription(schedule)
.sorted() )
let medication = medications[response.medicationId] }
}
return MedicationCard(
id: response.prescription.id,
medicationId: response.medicationId,
name: medication?.name ?? "Medicacao prescrita",
tag: medication?.activeIngredient ?? medication?.dosageForm ?? "Ativo",
photoBase64: medication?.medicationPhoto,
doseTimes: times,
nextDoseTime: times.first(where: { $0 >= currentTime }) ?? times.first
)
} }
.sorted { $0.time < $1.time }
} }
func loadDashboard() async { func loadDashboard() async {
@ -57,15 +42,13 @@ final class DashboardViewModel: ViewModel {
defer { isLoading = false } defer { isLoading = false }
do { do {
async let myPatient = api.getMyPatientProfile()
async let activePrescriptions = api.listMyActivePrescriptions() async let activePrescriptions = api.listMyActivePrescriptions()
async let medicationsResponse = api.listMedications() async let medications = api.listMedications()
let (patient, prescriptions, medicationsResponseValue) = try await (myPatient, activePrescriptions, medicationsResponse) let (prescriptions, medicationResponse) = try await (activePrescriptions, medications)
self.patient = patient
self.prescriptions = prescriptions self.prescriptions = prescriptions
medications = Dictionary( medicationNames = Dictionary(
uniqueKeysWithValues: medicationsResponseValue.medications.map { ($0.medicationId, $0) } uniqueKeysWithValues: medicationResponse.medications.map { ($0.medicationId, $0.name) }
) )
} catch { } catch {
errorMessage = "Nao foi possivel carregar a sua medicacao." errorMessage = "Nao foi possivel carregar a sua medicacao."
@ -79,16 +62,20 @@ final class DashboardViewModel: ViewModel {
formatter.dateFormat = "HH:mm" formatter.dateFormat = "HH:mm"
return formatter.string(from: .now) return formatter.string(from: .now)
} }
private func doseDescription(_ schedule: PrescriptionScheduleResponse) -> String {
guard let amount = schedule.doseAmount else { return "Dose conforme prescricao" }
let formattedAmount = amount.formatted(.number.precision(.fractionLength(0...2)))
return schedule.doseUnit.map { "\(formattedAmount) \($0)" } ?? formattedAmount
}
} }
struct MedicationCard: Identifiable { struct DashboardDose: Identifiable {
let id: String let time: String
let medicationId: String let title: String
let name: String let detail: String
let tag: String
let photoBase64: String? var id: String { "\(time)-\(title)-\(detail)" }
let doseTimes: [String]
let nextDoseTime: String?
} }
// Created by RSA on 28/08/2026. // Created by RSA on 28/08/2026.
// //

View File

@ -5,33 +5,15 @@ struct DashboardView: View {
@StateObject private var viewModel = DashboardViewModel() @StateObject private var viewModel = DashboardViewModel()
var body: some View { var body: some View {
ZStack { ScrollView {
Color.appSecondary.ignoresSafeArea() VStack(alignment: .leading, spacing: 24) {
header
VStack(alignment: .leading, spacing: 20) { nextDoseCard
topBar todaySection
patientHeader
reminderBanner
if viewModel.isLoading && viewModel.medicationCards.isEmpty {
ProgressView()
.frame(maxWidth: .infinity)
.padding(.top, 40)
} else if let errorMessage = viewModel.errorMessage {
errorState(errorMessage)
} else if viewModel.medicationCards.isEmpty {
Text("Nao ha medicacao ativa para mostrar.")
.font(.jakartaRegular16)
.foregroundStyle(Color.appTextPrimary.opacity(0.65))
.padding(.horizontal, 20)
} else {
medicationCarousel
}
Spacer(minLength: 0)
} }
.padding(.top, 12) .padding(20)
} }
.background(Color.appSecondary.ignoresSafeArea())
.navigationBarHidden(true) .navigationBarHidden(true)
.task { .task {
await viewModel.loadDashboard() await viewModel.loadDashboard()
@ -41,215 +23,113 @@ struct DashboardView: View {
} }
} }
// MARK: - Top bar private var header: some View {
VStack(alignment: .leading, spacing: 6) {
private var topBar: some View { Text("O seu plano")
HStack { .font(.jakartaBold24)
Circle() .foregroundStyle(Color.appTextPrimary)
.fill(Color.appBackground) Text("A sua medicacao de hoje")
.frame(width: 40, height: 40) .font(.jakartaRegular16)
.overlay { .foregroundStyle(Color.appTextPrimary.opacity(0.65))
Image(systemName: "person.fill")
.foregroundStyle(.white)
}
Spacer()
HStack(spacing: 6) {
Image(systemName: "dot.radiowaves.left.and.right")
.foregroundStyle(Color.appTextPrimary.opacity(0.55))
Circle()
.fill(.green)
.frame(width: 8, height: 8)
}
} }
.padding(.horizontal, 20)
}
// MARK: - Patient header
private var patientHeader: some View {
VStack(spacing: 6) {
ZStack {
Circle()
.stroke(Color.green, lineWidth: 3)
.frame(width: 92, height: 92)
patientAvatar
.frame(width: 78, height: 78)
.clipShape(Circle())
}
Text(viewModel.patient?.name ?? "Doente")
.font(.jakartaBold18)
.foregroundStyle(Color.appAccent)
if let age = viewModel.patientAge {
Text("\(age) Anos")
.font(.jakartaRegular14)
.foregroundStyle(Color.appTextPrimary.opacity(0.55))
}
Text("🙂")
.font(.system(size: 20))
.padding(.top, 2)
}
.frame(maxWidth: .infinity)
} }
@ViewBuilder @ViewBuilder
private var patientAvatar: some View { private var nextDoseCard: some View {
if let photo = viewModel.patient?.photo, let image = decodedImage(from: photo) { if viewModel.isLoading && viewModel.prescriptions.isEmpty {
image.resizable().scaledToFill() ProgressView()
} else { .frame(maxWidth: .infinity, minHeight: 156)
Color.appBorder } else if let errorMessage = viewModel.errorMessage {
.overlay { VStack(alignment: .leading, spacing: 12) {
Image(systemName: "person.fill") Text(errorMessage)
.foregroundStyle(Color.appTextPrimary.opacity(0.4)) .font(.jakartaRegular16)
.foregroundStyle(.red)
Button("Tentar novamente") {
Task { await viewModel.loadDashboard() }
} }
}
}
// MARK: - Reminder banner
private var reminderBanner: some View {
VStack(spacing: 4) {
Text("Não se esqueça!")
.font(.jakartaBold16) .font(.jakartaBold16)
.foregroundStyle(Color.appAccent)
Group {
Text("Tem ") +
Text("\(viewModel.totalDosesToday) Comprimidos")
.fontWeight(.bold) +
Text(" para tomar hoje.")
}
.font(.jakartaRegular14)
.foregroundStyle(Color.appAccent)
}
.frame(maxWidth: .infinity)
.multilineTextAlignment(.center)
}
// MARK: - Medication carousel
private var medicationCarousel: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 16) {
ForEach(viewModel.medicationCards) { card in
MedicationCardView(card: card)
.frame(width: 260)
}
}
.padding(.horizontal, 20)
.padding(.bottom, 20)
}
}
private func errorState(_ message: String) -> some View {
VStack(alignment: .leading, spacing: 12) {
Text(message)
.font(.jakartaRegular16)
.foregroundStyle(.red)
Button("Tentar novamente") {
Task { await viewModel.loadDashboard() }
}
.font(.jakartaBold16)
.foregroundStyle(Color.appBackground)
}
.padding(.horizontal, 20)
}
private func decodedImage(from base64String: String) -> Image? {
guard let data = Data(base64Encoded: base64String), let uiImage = UIImage(data: data) else {
return nil
}
return Image(uiImage: uiImage)
}
}
private struct MedicationCardView: View {
let card: MedicationCard
var body: some View {
VStack(spacing: 14) {
medicationImage
.frame(height: 140)
.frame(maxWidth: .infinity)
.background(Color.appSecondary)
.clipShape(RoundedRectangle(cornerRadius: 12))
.overlay(alignment: .topTrailing) {
Image(systemName: "info.circle.fill")
.foregroundStyle(Color.appBackground)
.padding(8)
.background(.white)
.clipShape(Circle())
.padding(8)
}
Text(card.name)
.font(.jakartaBold16)
.foregroundStyle(Color.appAccent)
.multilineTextAlignment(.center)
Text(card.tag)
.font(.jakartaMedium14)
.foregroundStyle(.white)
.padding(.horizontal, 14)
.padding(.vertical, 6)
.background(Color.appBackground)
.clipShape(Capsule())
if let nextDoseTime = card.nextDoseTime {
Group {
Text("Próxima toma às ") +
Text("\(nextDoseTime)h").fontWeight(.bold)
}
.font(.jakartaRegular14)
.foregroundStyle(Color.appBackground) .foregroundStyle(Color.appBackground)
} }
.frame(maxWidth: .infinity, alignment: .leading)
Divider() .padding(20)
.background(.white)
doseTimesGrid .clipShape(RoundedRectangle(cornerRadius: 8))
} } else if let dose = viewModel.nextDose {
.padding(16) VStack(alignment: .leading, spacing: 12) {
.background(.white) Text("PROXIMA TOMA")
.clipShape(RoundedRectangle(cornerRadius: 16)) .font(.jakartaBold12)
.shadow(color: .black.opacity(0.06), radius: 8, y: 4) .foregroundStyle(.white.opacity(0.75))
} HStack(alignment: .center) {
Text(dose.time)
@ViewBuilder .font(.jakartaBold40)
private var medicationImage: some View { Spacer()
if let photoBase64 = card.photoBase64, Image(systemName: "pills.fill")
let data = Data(base64Encoded: photoBase64), .font(.system(size: 31))
let uiImage = UIImage(data: data) { }
Image(uiImage: uiImage) Text(dose.title)
.resizable() .font(.jakartaBold18)
.scaledToFill() Text(dose.detail)
.clipped() .font(.jakartaRegular16)
} else { .foregroundStyle(.white.opacity(0.82))
Image(systemName: "pills.fill") }
.font(.system(size: 40)) .foregroundStyle(.white)
.foregroundStyle(Color.appBackground.opacity(0.5)) .frame(maxWidth: .infinity, alignment: .leading)
} .padding(22)
} .background(Color.appBackground)
.clipShape(RoundedRectangle(cornerRadius: 8))
private var doseTimesGrid: some View { } else {
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 10) { VStack(spacing: 10) {
ForEach(card.doseTimes, id: \.self) { time in Image(systemName: "checkmark.circle.fill")
HStack(spacing: 6) { .font(.system(size: 34))
Image(systemName: time == card.nextDoseTime ? "bell.fill" : "clock") .foregroundStyle(Color.appBackground)
.font(.system(size: 13)) Text("Nao tem tomas agendadas.")
Text("\(time)") .font(.jakartaRegular16)
.font(time == card.nextDoseTime ? .jakartaBold14 : .jakartaRegular14) .foregroundStyle(Color.appTextPrimary)
}
.frame(maxWidth: .infinity, minHeight: 156)
.background(.white)
.clipShape(RoundedRectangle(cornerRadius: 8))
}
}
private var todaySection: some View {
VStack(alignment: .leading, spacing: 14) {
Text("Medicacao de hoje")
.font(.jakartaBold18)
.foregroundStyle(Color.appTextPrimary)
if viewModel.scheduledDoses.isEmpty && !viewModel.isLoading && viewModel.errorMessage == nil {
Text("Nao ha medicacao ativa para mostrar.")
.font(.jakartaRegular16)
.foregroundStyle(Color.appTextPrimary.opacity(0.65))
} else {
ForEach(viewModel.scheduledDoses) { dose in
HStack(spacing: 16) {
Text(dose.time)
.font(.jakartaBold16)
.foregroundStyle(Color.appBackground)
.frame(width: 54, alignment: .leading)
Circle()
.fill(Color.appBackground.opacity(0.18))
.frame(width: 40, height: 40)
.overlay {
Image(systemName: "pills.fill")
.foregroundStyle(Color.appBackground)
}
VStack(alignment: .leading, spacing: 3) {
Text(dose.title)
.font(.jakartaBold16)
.foregroundStyle(Color.appTextPrimary)
Text(dose.detail)
.font(.jakartaRegular14)
.foregroundStyle(Color.appTextPrimary.opacity(0.62))
}
Spacer(minLength: 0)
}
.padding(16)
.background(.white)
.clipShape(RoundedRectangle(cornerRadius: 8))
} }
.foregroundStyle(
time == card.nextDoseTime
? Color.appBackground
: Color.appTextPrimary.opacity(0.4)
)
} }
} }
} }
@ -258,3 +138,6 @@ private struct MedicationCardView: View {
#Preview { #Preview {
DashboardView() DashboardView()
} }
// Created by RSA on 28/08/2026.
//

View File

@ -90,18 +90,4 @@ public class PatientsController {
public ResponseEntity<ListOfPatientPeriods> getPatientMedicationDayPeriods(@CurrentUser AppUser sessionUser) { public ResponseEntity<ListOfPatientPeriods> getPatientMedicationDayPeriods(@CurrentUser AppUser sessionUser) {
return ResponseEntity.ok(this.patientsService.getPatientMedicationDayPeriods(sessionUser)); return ResponseEntity.ok(this.patientsService.getPatientMedicationDayPeriods(sessionUser));
} }
@Operation(summary = "Get my patient profile", description = "Returns the authenticated patient's own profile.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Patient found"),
@ApiResponse(responseCode = "403", description = "Only patient accounts can access this endpoint")
})
@GetMapping("/me")
public ResponseEntity<PatientDTO> getMyPatientProfile(@CurrentUser AppUser sessionUser) {
if (sessionUser == null || sessionUser.getRole() != com.voidsoftware.map02.models.Role.PATIENT) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
return ResponseEntity.ok(patientsService.getMyProfile(sessionUser));
}
} }

View File

@ -99,12 +99,6 @@ public class PatientsService {
return this.dataConversionService.convertToPatientDTO(patient.get()); return this.dataConversionService.convertToPatientDTO(patient.get());
} }
public PatientDTO getMyProfile(AppUser sessionUser) {
Patient patient = patientRepository.findByUserId(sessionUser.getId())
.orElseThrow(() -> new IllegalArgumentException("Patient account is not linked to a patient profile"));
return this.dataConversionService.convertToPatientDTO(patient);
}
public List<PatientDTO> getPatientsListByProfessional(AppUser sessionUser, ListPatientsRequest request) { public List<PatientDTO> getPatientsListByProfessional(AppUser sessionUser, ListPatientsRequest request) {
if (sessionUser.getRole().equals(Role.PATIENT)) { if (sessionUser.getRole().equals(Role.PATIENT)) {