finalizare 1.0

This commit is contained in:
andrei-mihnea-cerbu
2024-05-21 12:10:53 +03:00
parent f7795f7519
commit 1cc1d34003
11268 changed files with 2102399 additions and 10909 deletions
@@ -0,0 +1,38 @@
using System.Net.Http.Json;
using System.Text.Json;
using HealthcareManagerUiWebAssem.Entities;
using HealthcareManagerUiWebAssem.Models;
using HealthcareManagerUiWebAssem.Services.RequestHttp;
namespace HealthcareManagerUiWebAssem.Services.AdminUserManagement;
public class AdminManagementService(IRequestHttpService requestHttpService) : IAdminManagementService
{
public async Task<ApiResponse<List<Doctor>>> GetDoctors()
{
var response = await requestHttpService.GetAsync("/api/Doctors");
var responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<ApiResponse<List<Doctor>>>(responseContent,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
public async Task<ApiResponse<List<Patient>>> GetPatients()
{
var response = await requestHttpService.GetAsync("/api/Patients");
var responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<ApiResponse<List<Patient>>>(responseContent,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
public async Task<bool> DeleteDoctor(Guid id)
{
var response = await requestHttpService.DeleteAsync($"/api/Doctors/{id}");
return response.IsSuccessStatusCode;
}
public async Task<bool> DeletePatient(Guid id)
{
var response = await requestHttpService.DeleteAsync($"/api/Patients/{id}");
return response.IsSuccessStatusCode;
}
}
@@ -0,0 +1,12 @@
using HealthcareManagerUiWebAssem.Entities;
using HealthcareManagerUiWebAssem.Models;
namespace HealthcareManagerUiWebAssem.Services.AdminUserManagement;
public interface IAdminManagementService
{
Task<ApiResponse<List<Doctor>>> GetDoctors();
Task<ApiResponse<List<Patient>>> GetPatients();
Task<bool> DeleteDoctor(Guid id);
Task<bool> DeletePatient(Guid id);
}
@@ -1,88 +0,0 @@
using HealthcareManagerUiWebAssem.Models;
using HealthcareManagerUiWebAssem.Services.Http;
namespace HealthcareManagerUiWebAssem.Services.Appointment;
public class AppointmentService : IAppointmentService
{
private readonly IRequestHttpService _requestHttpService;
public AppointmentService(IRequestHttpService requestHttpService)
{
_requestHttpService = requestHttpService;
}
public async Task<BaseResponse> GetAppointmentsByPatient(Guid patientId)
{
try
{
var response = await _requestHttpService.GetByIdAsync("/Appointments/patient", patientId);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> GetAppointmentsByDoctor(Guid doctorId)
{
try
{
var response = await _requestHttpService.GetByIdAsync("/Appointments/doctor", doctorId);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> CreateAppointment(
AppointmentManagementModel model)
{
try
{
var response = await _requestHttpService.PostAsync("/Appointments", model);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> DeleteAppointment(AppointmentManagementModel model)
{
try
{
var response = await _requestHttpService.DeleteByFilterAsync("/Appointments", model);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
}
@@ -1,14 +0,0 @@
using HealthcareManagerUiWebAssem.Models;
namespace HealthcareManagerUiWebAssem.Services.Appointment;
public interface IAppointmentService
{
Task<BaseResponse> GetAppointmentsByPatient(Guid patientId);
Task<BaseResponse> GetAppointmentsByDoctor(Guid doctorId);
Task<BaseResponse> CreateAppointment(AppointmentManagementModel model);
Task<BaseResponse> DeleteAppointment(AppointmentManagementModel model);
}
@@ -1,104 +1,98 @@
using HealthcareManagerUiWebAssem.Models;
using HealthcareManagerUiWebAssem.Services.Http;
using System.IdentityModel.Tokens.Jwt;
using HealthcareManagerUiWebAssem.Models;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Text.Json;
using Blazored.LocalStorage;
using HealthcareManagerUiWebAssem.Services.RequestHttp;
using Microsoft.AspNetCore.Components.Authorization;
namespace HealthcareManagerUiWebAssem.Services.Authentication;
public class AuthenticationService : IAuthenticationService
public class AuthenticationService(
IRequestHttpService requestHttpService,
ILocalStorageService localStorageService,
AuthenticationStateProvider authenticationStateProvider)
: IAuthenticationService
{
private readonly IRequestHttpService _requestHttpService;
public AuthenticationService(IRequestHttpService requestHttpService)
public async Task<ApiResponse<string>> Login(UserLoginModel loginModel)
{
_requestHttpService = requestHttpService;
var response = await requestHttpService.PostAsync("/api/Authorization/login", loginModel);
var responseContent = await response.Content.ReadAsStringAsync();
var loginResponse = JsonSerializer.Deserialize<ApiResponse<string>>(responseContent,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (response.IsSuccessStatusCode) await localStorageService.SetItemAsync("authToken", loginResponse.Data);
return loginResponse;
}
public async Task<BaseResponse> Login(UserLoginModel userLoginModel)
public async Task<ApiResponse<string>> Register(UserRegisterModel registerModel)
{
try
{
var response = await _requestHttpService.PostAsync("/Authorization/login", userLoginModel);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
var response = await requestHttpService.PostAsync("/api/Authorization/register", registerModel);
var responseContent = await response.Content.ReadAsStringAsync();
var registerResponse = JsonSerializer.Deserialize<ApiResponse<string>>(responseContent,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
return registerResponse;
}
public async Task<BaseResponse> RegisterDoctor(UserRegisterModel userRegistrationModel)
public async Task<ApiResponse<string>> ResetJwt(string token)
{
try
{
var response = await _requestHttpService.PostAsync("/Doctors/register", userRegistrationModel);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> RegisterPatient(UserRegisterModel userRegistrationModel)
{
try
{
var response = await _requestHttpService.PostAsync("/Patients/register", userRegistrationModel);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
var requestBody = new { token = token };
var response = await requestHttpService.PostAsync("/api/Authorization/refresh_token", requestBody);
var responseContent = await response.Content.ReadAsStringAsync();
var resetJwtResponse = JsonSerializer.Deserialize<ApiResponse<string>>(responseContent,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (response.IsSuccessStatusCode) await localStorageService.SetItemAsync("authToken", resetJwtResponse.Data);
return resetJwtResponse;
}
public async Task<BaseResponse> ResetPassword(UserLoginModel dto)
public async Task<ApiResponse<object>> ResetPassword(ResetPasswordModel resetPasswordModel)
{
try
{
var response = await _requestHttpService.PostAsync("/Authorization/reset_password", dto);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
var requestBody = new { email = resetPasswordModel.Email, password = resetPasswordModel.Password };
var response = await requestHttpService.PostAsync("/api/Authorization/reset_password", requestBody);
var responseContent = await response.Content.ReadAsStringAsync();
var resetPasswordResponse = JsonSerializer.Deserialize<ApiResponse<object>>(responseContent,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
return resetPasswordResponse;
}
public async Task<BaseResponse> RefreshToken(TokenRefreshModel dto)
public async Task<UserInformation?> GetUserInformation()
{
try
var token = await GetAuthToken();
if (string.IsNullOrEmpty(token)) return null;
var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadJwtToken(token);
var name = jwtToken.Claims.FirstOrDefault(c => c.Type == "unique_name")?.Value;
var id = jwtToken.Claims.FirstOrDefault(c => c.Type == "nameid")?.Value;
var role = jwtToken.Claims.FirstOrDefault(c => c.Type == "role")?.Value;
return new UserInformation
{
var response = await _requestHttpService.PostAsync("/Authorization/refresh_token", dto);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
Name = name,
Id = Guid.Parse(id),
Role = role
};
}
public async Task Logout()
{
await localStorageService.RemoveItemAsync("authToken");
((CustomAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogout();
}
public async Task<string> GetAuthToken()
{
return await localStorageService.GetItemAsync<string>("authToken");
}
public async Task RemoveAuthToken()
{
await localStorageService.RemoveItemAsync("authToken");
}
}
@@ -4,9 +4,12 @@ namespace HealthcareManagerUiWebAssem.Services.Authentication;
public interface IAuthenticationService
{
Task<BaseResponse> Login(UserLoginModel userLoginModel);
Task<BaseResponse> RegisterPatient(UserRegisterModel userRegistrationModel);
Task<BaseResponse> RegisterDoctor(UserRegisterModel userRegistrationModel);
Task<BaseResponse> ResetPassword(UserLoginModel userResetPasswordModel);
Task<BaseResponse> RefreshToken(TokenRefreshModel dto);
Task<ApiResponse<string>> Login(UserLoginModel loginModel);
Task<ApiResponse<string>> Register(UserRegisterModel registerModel);
Task<ApiResponse<object>> ResetPassword(ResetPasswordModel resetPasswordModel);
Task<ApiResponse<string>> ResetJwt(string token);
Task Logout();
Task<string> GetAuthToken();
Task RemoveAuthToken();
Task<UserInformation?> GetUserInformation();
}
@@ -0,0 +1,108 @@
using System.Net.Http.Json;
using HealthcareManagerUiWebAssem.Entities;
using HealthcareManagerUiWebAssem.Models;
using HealthcareManagerUiWebAssem.Services.RequestHttp;
namespace HealthcareManagerUiWebAssem.Services.DoctorManagement;
public class DoctorManagementService(IRequestHttpService requestHttpService) : IDoctorManagementService
{
public async Task<Doctor> GetDoctorProfileAsync(Guid doctorId)
{
var response = await requestHttpService.GetAsync($"/api/Doctors/{doctorId}");
if (!response.IsSuccessStatusCode) return null;
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<Doctor>>();
return apiResponse?.Data;
}
public async Task<bool> UpdateDoctorProfileAsync(Doctor doctor)
{
var response = await requestHttpService.PutAsync("/api/Doctors", doctor);
return response.IsSuccessStatusCode;
}
public async Task<bool> DeleteDoctorProfileAsync(Guid doctorId)
{
var response = await requestHttpService.DeleteAsync($"/api/Doctors/{doctorId}");
return response.IsSuccessStatusCode;
}
public async Task<MedicalHistory?> GetMedicalHistoryAsync(Guid userId)
{
var response = await requestHttpService.GetAsync($"/api/MedicalHistory/user/{userId}");
if (!response.IsSuccessStatusCode) return null;
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<MedicalHistory>>();
return apiResponse.Data;
}
public async Task<List<Patient>> GetAllPatientsAsync()
{
var response = await requestHttpService.GetAsync("/api/Patients");
if (!response.IsSuccessStatusCode) return [];
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<List<Patient>>>();
return apiResponse?.Data ?? [];
}
public async Task<List<Appointment>> GetAppointmentsAsync(Guid doctorId)
{
var response = await requestHttpService.GetAsync($"/api/Appointments/doctor/{doctorId}");
if (!response.IsSuccessStatusCode) return [];
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<List<Appointment>>>();
return apiResponse?.Data ?? [];
}
public async Task<bool> SendMessageAsync(Guid senderId, Guid receiverId, string message)
{
var requestBody = new { sender = senderId, receiver = receiverId, message = message };
var response = await requestHttpService.PostAsync("/api/Chat/send_message", requestBody);
return response.IsSuccessStatusCode;
}
public async Task<bool> CancelAppointmentAsync(Guid doctorId, Guid patientId, DateTime appointmentDate)
{
var cancellationRequest = new AppointmentCancellationRequest
{
DoctorId = doctorId,
PatientId = patientId,
Appointment = appointmentDate
};
var response = await requestHttpService.PutAsync("/api/Appointments", cancellationRequest);
return response.IsSuccessStatusCode;
}
public async Task<Chat> GetConversationAsync(Guid userId1, Guid userId2)
{
var requestBody = new { idUser1 = userId1, idUser2 = userId2 };
var response = await requestHttpService.PostAsync("/api/Chat/get_conversation", requestBody);
if (!response.IsSuccessStatusCode) return null;
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<Chat>>();
return apiResponse?.Data;
}
public async Task<byte[]> DownloadMedicalHistoryAsync(Guid patientId)
{
var response = await requestHttpService.GetAsync($"/api/MedicalHistory/user/{patientId}");
if (!response.IsSuccessStatusCode) return null;
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<MedicalHistory>>();
return apiResponse.Data.Content;
}
public async Task<bool> CheckForAccessAsync(Guid medicalRecordId, Guid doctorId)
{
var requestBody = new { MedicalRecordId = medicalRecordId, DoctorId = doctorId };
var response = await requestHttpService.PostAsync("/api/MedicalHistory/check_access", requestBody);
return response.IsSuccessStatusCode;
}
public async Task<ApiResponse<List<PredictionResult>>> GetSicknessPrediction(string text)
{
var requestBody = new { text };
var response = await requestHttpService.PostAsync("/api/SicknessPrediction", requestBody);
if (!response.IsSuccessStatusCode) return null;
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<List<PredictionResult>>>();
return apiResponse;
}
}
@@ -0,0 +1,22 @@
using HealthcareManagerUiWebAssem.Entities;
using HealthcareManagerUiWebAssem.Models;
namespace HealthcareManagerUiWebAssem.Services.DoctorManagement;
public interface IDoctorManagementService
{
Task<Doctor> GetDoctorProfileAsync(Guid doctorId);
Task<bool> UpdateDoctorProfileAsync(Doctor doctor);
Task<bool> DeleteDoctorProfileAsync(Guid doctorId);
Task<List<Appointment>> GetAppointmentsAsync(Guid doctorId);
Task<bool> CancelAppointmentAsync(Guid doctorId, Guid patientId, DateTime appointmentDate);
Task<MedicalHistory?> GetMedicalHistoryAsync(Guid userId);
Task<List<Patient>> GetAllPatientsAsync();
Task<bool> SendMessageAsync(Guid senderId, Guid receiverId, string message);
Task<Chat> GetConversationAsync(Guid userId1, Guid userId2);
Task<byte[]> DownloadMedicalHistoryAsync(Guid patientId);
Task<bool> CheckForAccessAsync(Guid medicalRecordId, Guid doctorId);
Task<ApiResponse<List<PredictionResult>>> GetSicknessPrediction(string text);
}
@@ -1,17 +0,0 @@
using HealthcareManagerUiWebAssem.Models;
namespace HealthcareManagerUiWebAssem.Services.Http;
public interface IRequestHttpService
{
Task<BaseResponse> GetAsync(string uri, IDictionary<string, string> headers = null);
Task<BaseResponse> GetByIdAsync(string uri, Guid id, IDictionary<string, string> headers = null);
Task<BaseResponse> PostAsync(string uri, object data, IDictionary<string, string> headers = null);
Task<BaseResponse> PutAsync(string uri, object data, IDictionary<string, string> headers = null);
Task<BaseResponse> DeleteAsync(string uri, Guid id, IDictionary<string, string> headers = null);
Task<BaseResponse> DeleteByFilterAsync(string uri, object data, IDictionary<string, string> headers = null);
}
@@ -1,144 +0,0 @@
using System.Text;
using System.Text.Json;
using HealthcareManagerUiWebAssem.Models;
using HealthcareManagerUiWebAssem.Services.UserSessionInformation;
using Microsoft.Extensions.Options;
namespace HealthcareManagerUiWebAssem.Services.Http;
public class RequestHttpService : IRequestHttpService
{
private readonly string _apiEndpoint;
private readonly string _apiKey;
private readonly HttpClient _httpClient;
private readonly IUserSessionInformation _userSessionInformation;
public RequestHttpService(IHttpClientFactory httpClientFactory, IUserSessionInformation userSessionInformation,
IOptions<ApplicationSettings> settings)
{
_httpClient = httpClientFactory.CreateClient();
_apiKey = settings.Value.ApiKey ?? "NoKey";
_apiEndpoint = settings.Value.ApiEndpoint;
_userSessionInformation = userSessionInformation;
}
public async Task<BaseResponse> GetByIdAsync(string uri, Guid id, IDictionary<string, string>? headers = null)
{
headers ??= new Dictionary<string, string>();
var request = new HttpRequestMessage(HttpMethod.Get, $"{_apiEndpoint}{uri}/{id}");
AddHeaders(request, headers);
var response = await _httpClient.SendAsync(request);
Thread.Sleep(1000);
return await HandleResponse(response, uri);
}
public async Task<BaseResponse> GetAsync(string uri, IDictionary<string, string>? headers = null)
{
headers ??= new Dictionary<string, string>();
var request = new HttpRequestMessage(HttpMethod.Get, $"{_apiEndpoint}{uri}");
AddHeaders(request, headers);
var response = await _httpClient.SendAsync(request);
Thread.Sleep(1000);
return await HandleResponse(response, uri);
}
public async Task<BaseResponse> PostAsync(string uri, object data, IDictionary<string, string>? headers = null)
{
headers ??= new Dictionary<string, string>();
var request = new HttpRequestMessage(HttpMethod.Post, $"{_apiEndpoint}{uri}"); // Prepend _apiEndpoint
AddHeaders(request, headers);
request.Content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");
var response = await _httpClient.SendAsync(request);
Thread.Sleep(1000);
return await HandleResponse(response, uri);
}
public async Task<BaseResponse> PutAsync(string uri, object data, IDictionary<string, string>? headers = null)
{
headers ??= new Dictionary<string, string>();
var request = new HttpRequestMessage(HttpMethod.Put, $"{_apiEndpoint}{uri}");
AddHeaders(request, headers);
request.Content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");
var response = await _httpClient.SendAsync(request);
Thread.Sleep(1000);
return await HandleResponse(response, uri);
}
public async Task<BaseResponse> DeleteAsync(string uri, Guid id, IDictionary<string, string>? headers = null)
{
headers ??= new Dictionary<string, string>();
var request = new HttpRequestMessage(HttpMethod.Delete, $"{_apiEndpoint}{uri}/{id}");
AddHeaders(request, headers);
var response = await _httpClient.SendAsync(request);
Thread.Sleep(1000);
return await HandleResponse(response, uri);
}
public async Task<BaseResponse> DeleteByFilterAsync(string uri, object data, IDictionary<string, string>? headers = null)
{
headers ??= new Dictionary<string, string>();
var request = new HttpRequestMessage(HttpMethod.Delete, $"{_apiEndpoint}{uri}");
AddHeaders(request, headers);
request.Content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");
var response = await _httpClient.SendAsync(request);
Thread.Sleep(1000);
return await HandleResponse(response, uri);
}
private async void AddHeaders(HttpRequestMessage request, IDictionary<string, string>? headers)
{
request.Headers.Add("ApiKey", _apiKey);
request.Headers.Add("Authorization", "Bearer " + await _userSessionInformation.GetTokenAsync());
if (headers == null) return;
foreach (var header in headers) request.Headers.Add(header.Key, header.Value);
}
private async Task<BaseResponse> HandleResponse(HttpResponseMessage? response, string uri)
{
var responseContent = await response.Content.ReadAsStringAsync();
var responseJson = JsonSerializer.Deserialize<JsonResponse>(
responseContent,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true }
);
var baseResponse = new BaseResponse();
if (responseJson != null)
{
baseResponse.StatusCode = responseJson.StatusCode;
baseResponse.Message = responseJson.Message;
baseResponse.Data = responseJson.Data.ToString();
baseResponse.Headers = new Dictionary<string, string>();
}
foreach (var header in response.Headers.Concat(response.Content.Headers))
{
Console.WriteLine(header.Key);
if (baseResponse.Headers.ContainsKey(header.Key))
{
baseResponse.Headers[header.Key] += ", " + string.Join(", ", header.Value);
}
else
{
baseResponse.Headers.Add(header.Key, string.Join(", ", header.Value));
}
}
return baseResponse;
}
class JsonResponse
{
public int StatusCode { get; set; }
public string Message { get; set; }
public JsonElement Data { get; set; }
}
}
@@ -0,0 +1,30 @@
using HealthcareManagerUiWebAssem.Entities;
using HealthcareManagerUiWebAssem.Models;
namespace HealthcareManagerUiWebAssem.Services.PatientManagement;
public interface IPatientManagementService
{
Task<Patient> GetPatientProfileAsync(Guid patientId);
Task<bool> UpdatePatientProfileAsync(Patient patient);
Task<bool> DeletePatientProfileAsync(Guid patientId);
Task<List<Appointment>> GetAppointmentsAsync(Guid patientId);
Task<ApiResponse<object>> BookAppointmentAsync(NewAppointmentModel newAppointment);
Task<bool> CancelAppointmentAsync(Guid doctorId, Guid patientId, DateTime appointmentDate);
Task<MedicalHistory?> GetMedicalHistoryAsync(Guid userId);
Task<ApiResponse<object>> UploadMedicalHistoryAsync(Guid userId, byte[] content);
Task<bool> DeleteMedicalHistoryAsync(Guid fileId);
Task<byte[]> DownloadMedicalHistoryAsync(Guid fileId);
Task<List<Doctor>> GetAllDoctorsAsync();
Task<bool> CheckForAccessAsync(Guid medicalRecordId, Guid doctorId);
Task<bool> GrantAccessAsync(Guid medicalRecordId, Guid doctorId);
Task<bool> RevokeAccessAsync(Guid medicalRecordId, Guid doctorId);
Task<bool> SendMessageAsync(Guid senderId, Guid receiverId, string message);
Task<Chat> GetConversationAsync(Guid userId1, Guid userId2);
}
@@ -0,0 +1,139 @@
using System.Net.Http.Json;
using HealthcareManagerUiWebAssem.Entities;
using HealthcareManagerUiWebAssem.Models;
using HealthcareManagerUiWebAssem.Services.RequestHttp;
namespace HealthcareManagerUiWebAssem.Services.PatientManagement;
public class PatientManagementService(IRequestHttpService requestHttpService) : IPatientManagementService
{
public async Task<Patient> GetPatientProfileAsync(Guid patientId)
{
var response = await requestHttpService.GetAsync($"/api/Patients/{patientId}");
if (!response.IsSuccessStatusCode) return null;
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<Patient>>();
return apiResponse?.Data;
}
public async Task<bool> UpdatePatientProfileAsync(Patient patient)
{
var response = await requestHttpService.PutAsync("/api/Patients", patient);
return response.IsSuccessStatusCode;
}
public async Task<bool> DeletePatientProfileAsync(Guid patientId)
{
var response = await requestHttpService.DeleteAsync($"/api/Patients/{patientId}");
return response.IsSuccessStatusCode;
}
public async Task<List<Appointment>> GetAppointmentsAsync(Guid patientId)
{
var response = await requestHttpService.GetAsync($"/api/Appointments/patient/{patientId}");
if (!response.IsSuccessStatusCode) return new List<Appointment>();
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<List<Appointment>>>();
return apiResponse?.Data ?? [];
}
public async Task<ApiResponse<object>> BookAppointmentAsync(NewAppointmentModel newAppointment)
{
var response = await requestHttpService.PostAsync("/api/Appointments", newAppointment);
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<object>>();
return apiResponse;
}
public async Task<bool> CancelAppointmentAsync(Guid doctorId, Guid patientId, DateTime appointmentDate)
{
var cancellationRequest = new AppointmentCancellationRequest
{
DoctorId = doctorId,
PatientId = patientId,
Appointment = appointmentDate
};
var response = await requestHttpService.PutAsync("/api/Appointments", cancellationRequest);
return response.IsSuccessStatusCode;
}
// Medical history methods
public async Task<MedicalHistory?> GetMedicalHistoryAsync(Guid userId)
{
var response = await requestHttpService.GetAsync($"/api/MedicalHistory/user/{userId}");
if (!response.IsSuccessStatusCode) return null;
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<MedicalHistory>>();
return apiResponse.Data;
}
public async Task<ApiResponse<object>> UploadMedicalHistoryAsync(Guid userId, byte[] content)
{
var requestBody = new { UserId = userId, Content = content };
var response = await requestHttpService.PostAsync("/api/MedicalHistory", requestBody);
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<object>>();
return apiResponse;
}
public async Task<bool> DeleteMedicalHistoryAsync(Guid fileId)
{
var response = await requestHttpService.DeleteAsync($"/api/MedicalHistory/{fileId}");
return response.IsSuccessStatusCode;
}
public async Task<byte[]> DownloadMedicalHistoryAsync(Guid fileId)
{
var response = await requestHttpService.GetAsync($"/api/MedicalHistory/{fileId}");
if (response.IsSuccessStatusCode) return await response.Content.ReadAsByteArrayAsync();
return null;
}
public async Task<List<Doctor>> GetAllDoctorsAsync()
{
var response = await requestHttpService.GetAsync("/api/Doctors");
if (!response.IsSuccessStatusCode) return [];
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<List<Doctor>>>();
return apiResponse?.Data ?? [];
}
public async Task<bool> CheckForAccessAsync(Guid medicalRecordId, Guid doctorId)
{
var requestBody = new { MedicalRecordId = medicalRecordId, DoctorId = doctorId };
var response = await requestHttpService.PostAsync("/api/MedicalHistory/check_access", requestBody);
return response.IsSuccessStatusCode;
}
public async Task<bool> GrantAccessAsync(Guid medicalRecordId, Guid doctorId)
{
var requestBody = new { MedicalRecordId = medicalRecordId, DoctorId = doctorId };
var response = await requestHttpService.PutAsync("/api/MedicalHistory/grant_access", requestBody);
if (!response.IsSuccessStatusCode) return false;
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<object>>();
return apiResponse.StatusCode == HttpStatusCodes.OK;
}
public async Task<bool> RevokeAccessAsync(Guid medicalRecordId, Guid doctorId)
{
var requestBody = new { MedicalRecordId = medicalRecordId, DoctorId = doctorId };
var response = await requestHttpService.PutAsync("/api/MedicalHistory/revoke_access", requestBody);
if (!response.IsSuccessStatusCode) return false;
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<object>>();
return apiResponse.StatusCode == HttpStatusCodes.OK;
}
public async Task<bool> SendMessageAsync(Guid senderId, Guid receiverId, string message)
{
var requestBody = new { sender = senderId, receiver = receiverId, message = message };
var response = await requestHttpService.PostAsync("/api/Chat/send_message", requestBody);
return response.IsSuccessStatusCode;
}
public async Task<Chat> GetConversationAsync(Guid userId1, Guid userId2)
{
var requestBody = new { idUser1 = userId1, idUser2 = userId2 };
var response = await requestHttpService.PostAsync("/api/Chat/get_conversation", requestBody);
if (!response.IsSuccessStatusCode) return null;
var apiResponse = await response.Content.ReadFromJsonAsync<ApiResponse<Chat>>();
return apiResponse?.Data;
}
}
@@ -1,22 +0,0 @@
using HealthcareManagerUiWebAssem.Models;
namespace HealthcareManagerUiWebAssem.Services.Profile;
public interface IProfileService
{
Task<BaseResponse> GetDoctors();
Task<BaseResponse> GetPatients();
Task<BaseResponse> GetDoctorById(Guid id);
Task<BaseResponse> GetPatientById(Guid id);
Task<BaseResponse> UpdateDoctorProfile(UserUpdateProfileModel userUpdateProfileModel);
Task<BaseResponse> UpdatePatientProfile(UserUpdateProfileModel userUpdateProfileModel);
Task<BaseResponse> DeleteDoctorProfile(Guid id);
Task<BaseResponse> DeletePatientProfile(Guid id);
}
-161
View File
@@ -1,161 +0,0 @@
using HealthcareManagerUiWebAssem.Models;
using HealthcareManagerUiWebAssem.Services.Http;
namespace HealthcareManagerUiWebAssem.Services.Profile;
public class ProfileService : IProfileService
{
private readonly IRequestHttpService _requestHttpService;
public ProfileService(IRequestHttpService requestHttpService)
{
_requestHttpService = requestHttpService;
}
public async Task<BaseResponse> GetDoctors()
{
try
{
var response = await _requestHttpService.GetAsync("/Doctors");
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> GetPatients()
{
try
{
var response = await _requestHttpService.GetAsync("/Patients");
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> GetDoctorById(Guid id)
{
try
{
var response = await _requestHttpService.GetByIdAsync("/Doctors", id);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> GetPatientById(Guid id)
{
try
{
var response = await _requestHttpService.GetByIdAsync("/Patients", id);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> UpdateDoctorProfile(
UserUpdateProfileModel userUpdateProfileModel)
{
try
{
var response = await _requestHttpService.PutAsync("/Doctors", userUpdateProfileModel);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> UpdatePatientProfile(
UserUpdateProfileModel userUpdateProfileModel)
{
try
{
var response = await _requestHttpService.PutAsync("/Patients", userUpdateProfileModel);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> DeleteDoctorProfile(Guid id)
{
try
{
var response = await _requestHttpService.DeleteAsync("/Doctors", id);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
public async Task<BaseResponse> DeletePatientProfile(Guid id)
{
try
{
var response = await _requestHttpService.DeleteAsync("/Patients", id);
return response;
}
catch (Exception ex)
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.InternalServerError,
Data = null,
Message = ex.Message
};
}
}
}
@@ -0,0 +1,9 @@
namespace HealthcareManagerUiWebAssem.Services.RequestHttp;
public interface IRequestHttpService
{
Task<HttpResponseMessage> GetAsync(string requestUri);
Task<HttpResponseMessage> PostAsync<T>(string requestUri, T value);
Task<HttpResponseMessage> PutAsync<T>(string requestUri, T value);
Task<HttpResponseMessage> DeleteAsync(string requestUri);
}
@@ -0,0 +1,34 @@
using System.Net.Http.Json;
namespace HealthcareManagerUiWebAssem.Services.RequestHttp;
public class RequestHttpService : IRequestHttpService
{
private readonly HttpClient _httpClient;
public RequestHttpService(HttpClient httpClient, ApplicationSettings apiSettings)
{
httpClient.BaseAddress = new Uri(apiSettings.BaseAddress);
_httpClient = httpClient;
}
public async Task<HttpResponseMessage> GetAsync(string requestUri)
{
return await _httpClient.GetAsync(requestUri);
}
public async Task<HttpResponseMessage> PostAsync<T>(string requestUri, T value)
{
return await _httpClient.PostAsJsonAsync(requestUri, value);
}
public async Task<HttpResponseMessage> PutAsync<T>(string requestUri, T value)
{
return await _httpClient.PutAsJsonAsync(requestUri, value);
}
public async Task<HttpResponseMessage> DeleteAsync(string requestUri)
{
return await _httpClient.DeleteAsync(requestUri);
}
}
-56
View File
@@ -1,56 +0,0 @@
using System.Text.Json;
using HealthcareManagerUiWebAssem.Models;
using HealthcareManagerUiWebAssem.Services.Profile;
namespace HealthcareManagerUiWebAssem.Services.User;
public class UserService
{
public Guid UserId { get; private set; }
public void SetUserId(Guid id)
{
UserId = id;
}
public async Task<UserUpdateProfileModel?> InitializeProfile(string role, IProfileService profileService)
{
var response = role switch
{
"doctor" => await profileService.GetDoctorById(UserId),
"patient" => await profileService.GetPatientById(UserId),
_ => null
};
if (response.Data != null)
{
var jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
if (role.Equals("doctor", StringComparison.OrdinalIgnoreCase))
{
var doctor = JsonSerializer.Deserialize<Doctor>(response.Data.ToString(), jsonOptions);
return new UserUpdateProfileModel
{
Id = doctor.Id,
Name = doctor.Name,
Email = doctor.Email,
Password = doctor.Password,
Description = doctor.Description
};
}
if (role.Equals("patient", StringComparison.OrdinalIgnoreCase))
{
var patient = JsonSerializer.Deserialize<Patient>(response.Data.ToString(), jsonOptions);
return new UserUpdateProfileModel
{
Id = patient.Id,
Name = patient.Name,
Email = patient.Email,
Password = patient.Password
};
}
}
return new UserUpdateProfileModel();
}
}
@@ -1,20 +0,0 @@
namespace HealthcareManagerUiWebAssem.Services.UserSessionInformation;
public interface IUserSessionInformation
{
Task SaveUserInformationAsync(Guid id, string role, string username, string email, string token);
Task SetIdAsync(Guid id);
Task SetRoleAsync(string role);
Task SetUsernameAsync(string username);
Task SetEmailAsync(string email);
Task SetTokenAsync(string token);
Task<Guid> GetIdAsync();
Task<string> GetRoleAsync();
Task<string> GetUsernameAsync();
Task<string> GetEmailAsync();
Task<string> GetTokenAsync();
Task RefreshTokenAsync();
}
@@ -1,114 +0,0 @@
using System.Net.Http.Json;
using System.Text.Json;
using Blazored.LocalStorage;
using HealthcareManagerUiWebAssem.Models;
using Microsoft.Extensions.Options;
namespace HealthcareManagerUiWebAssem.Services.UserSessionInformation;
public class UserSessionInformation : IUserSessionInformation
{
private readonly ILocalStorageService _localStorageService;
private readonly HttpClient _httpClient;
private readonly string _apiEndpoint;
private readonly string _apiKey;
public UserSessionInformation(ILocalStorageService localStorageService, IHttpClientFactory httpClientFactory, IOptions<ApplicationSettings> settings)
{
_localStorageService = localStorageService;
_httpClient = httpClientFactory.CreateClient();
_apiEndpoint = settings.Value.ApiEndpoint;
_apiKey = settings.Value.ApiKey ?? "NoKey";
}
public async Task SaveUserInformationAsync(Guid id, string role, string username, string email, string token)
{
await SetIdAsync(id);
await SetRoleAsync(role);
await SetUsernameAsync(username);
await SetEmailAsync(email);
await SetTokenAsync(token);
}
public async Task SetIdAsync(Guid id)
{
await _localStorageService.SetItemAsync("id", id);
}
public async Task SetRoleAsync(string role)
{
await _localStorageService.SetItemAsync("role", role);
}
public async Task SetUsernameAsync(string username)
{
await _localStorageService.SetItemAsync("username", username);
}
public async Task SetEmailAsync(string email)
{
await _localStorageService.SetItemAsync("email", email);
}
public async Task SetTokenAsync(string token)
{
await _localStorageService.SetItemAsync("jwtToken", token);
}
public async Task<Guid> GetIdAsync()
{
return await _localStorageService.GetItemAsync<Guid>("id");
}
public async Task<string> GetRoleAsync()
{
return await _localStorageService.GetItemAsync<string>("role");
}
public async Task<string> GetUsernameAsync()
{
return await _localStorageService.GetItemAsync<string>("username");
}
public async Task<string> GetEmailAsync()
{
return await _localStorageService.GetItemAsync<string>("email");
}
public async Task<string> GetTokenAsync()
{
return await _localStorageService.GetItemAsync<string>("jwtToken");
}
public async Task RefreshTokenAsync()
{
var currentToken = await GetTokenAsync();
if (string.IsNullOrWhiteSpace(currentToken)) return;
var tokenRequestModel = new TokenRefreshModel(currentToken);
var requestUri = $"{_apiEndpoint}/refresh_token";
var jsonContent = JsonContent.Create(tokenRequestModel);
var request = new HttpRequestMessage(HttpMethod.Post, requestUri)
{
Content = jsonContent
};
request.Headers.Add("ApiKey", _apiKey);
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode) return;
var responseContent = await response.Content.ReadAsStringAsync();
var baseResponse = JsonSerializer.Deserialize<BaseResponse>(
responseContent,
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (baseResponse == null || baseResponse.StatusCode < HttpStatusCodes.BadRequest) return;
var tokenObj = JsonSerializer.Deserialize<TokenRefreshModel>(baseResponse.Data.ToString(),
new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
if (tokenObj != null) await SetTokenAsync(tokenObj.Token);
}
}