This commit is contained in:
andrei-mihnea-cerbu
2024-04-08 13:37:58 +03:00
parent 333ad8be09
commit 370bbdedcd
164 changed files with 3915 additions and 161 deletions
@@ -0,0 +1,150 @@
using Application.Services.Database;
using Application.Services.Database.MongoDB;
using Core.Entities;
namespace Application.Endpoints.Chats;
public class ChatHandler
{
private readonly IChatMongoDbService _chatMongoDbService;
private readonly IPatientRepository _patientRepository;
private readonly IDoctorRepository _doctorRepository;
public ChatHandler(IChatMongoDbService chatMongoDbService, IPatientRepository patientRepository,
IDoctorRepository doctorRepository)
{
_chatMongoDbService = chatMongoDbService;
_patientRepository = patientRepository;
_doctorRepository = doctorRepository;
}
public async Task<BaseResponse> HandleSendMessage(SendMessageDto sendMessageDto)
{
var validation = new SendMessageValidator();
var validationResult = await validation.ValidateAsync(sendMessageDto);
if (!validationResult.IsValid)
{
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
if (!await CheckForUsersExistence(sendMessageDto.Sender, sendMessageDto.Receiver))
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.BadRequest,
Message = "Users can't be found in the system.",
Data = null
};
}
var chatId = ChatIdentifier.GenerateChatId(sendMessageDto.Sender, sendMessageDto.Receiver);
var criteria = new List<(string, string)>();
criteria.Add(("_id", chatId));
var documents = await _chatMongoDbService.FindAsync<Chat>(criteria);
if (!documents.Any())
{
return new BaseResponse()
{
StatusCode = HttpStatusCodes.NotFound,
Message = "Access to medical history not found.",
Data = null
};
}
var chat = documents[0].Messages;
chat.Add(new Message(sendMessageDto.Sender, sendMessageDto.Message));
var newChat = new Chat();
newChat.SetId(chatId);
newChat.SetMessages(chat);
await _chatMongoDbService.ModifyAsync("_id", chatId, newChat);
return new BaseResponse
{
StatusCode = HttpStatusCodes.NoContent,
Message = null,
Data = null
};
}
public async Task<BaseResponse> HandleGetConversation(GetConversationDto getConversationDto)
{
var validation = new GetConversationValidator();
var validationResult = await validation.ValidateAsync(getConversationDto);
if (!validationResult.IsValid)
{
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
if (!await CheckForUsersExistence(getConversationDto.IdUser1, getConversationDto.IdUser2))
{
return new BaseResponse
{
StatusCode = HttpStatusCodes.BadRequest,
Message = "Users can't be found in the system.",
Data = null
};
}
var chatId = ChatIdentifier.GenerateChatId(getConversationDto.IdUser1, getConversationDto.IdUser2);
var criteria = new List<(string, string)>();
criteria.Add(("_id", chatId));
Chat? chat = null;
var documents = await _chatMongoDbService.FindAsync<Chat>(criteria);
if (!documents.Any())
{
chat = new Chat();
chat.SetId(chatId);
await _chatMongoDbService.AddAsync(chat);
}
else
{
chat = documents[0];
}
return new BaseResponse
{
StatusCode = HttpStatusCodes.OK,
Message = "Fetching messages.",
Data = chat
};
}
private async Task<bool> CheckForUsersExistence(Guid idUser1, Guid idUser2)
{
var firstCheck = await _patientRepository.GetByIdAsync(idUser1) != null &&
await _doctorRepository.GetByIdAsync(idUser2) != null;
var secondCheck = await _patientRepository.GetByIdAsync(idUser2) != null &&
await _doctorRepository.GetByIdAsync(idUser1) != null;
return firstCheck || secondCheck;
}
}
@@ -0,0 +1,18 @@
namespace Application.Endpoints.Chats;
public class ChatIdentifier
{
public static string GenerateChatId(Guid id1, Guid id2)
{
// Convert GUIDs to strings
string strId1 = id1.ToString();
string strId2 = id2.ToString();
// Sort the GUID strings
string firstId = strId1.CompareTo(strId2) < 0 ? strId1 : strId2;
string secondId = strId1.CompareTo(strId2) < 0 ? strId2 : strId1;
// Combine them to get a symmetric string
return firstId + "-" + secondId;
}
}
@@ -0,0 +1,7 @@
namespace Application.Endpoints.Chats;
public class GetConversationDto
{
public Guid IdUser1 { get; set; }
public Guid IdUser2 { get; set; }
}
@@ -0,0 +1,15 @@
using FluentValidation;
namespace Application.Endpoints.Chats;
public class GetConversationValidator : AbstractValidator<GetConversationDto>
{
public GetConversationValidator()
{
RuleFor(x => x.IdUser1)
.NotEmpty().WithMessage("IdUser1 is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString());
RuleFor(x => x.IdUser2)
.NotEmpty().WithMessage("IdUser2 is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
}
@@ -0,0 +1,8 @@
namespace Application.Endpoints.Chats;
public class SendMessageDto
{
public Guid Sender { get; set; }
public Guid Receiver { get; set; }
public string Message { get; set; }
}
@@ -0,0 +1,18 @@
using FluentValidation;
namespace Application.Endpoints.Chats;
public class SendMessageValidator : AbstractValidator<SendMessageDto>
{
public SendMessageValidator()
{
RuleFor(x => x.Sender)
.NotEmpty().WithMessage("Sender Id is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString());
RuleFor(x => x.Receiver)
.NotEmpty().WithMessage("Receiver Id is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString());
RuleFor(x => x.Message)
.NotEmpty().WithMessage("Message is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
}
@@ -0,0 +1,7 @@
namespace Application.Endpoints.MedicalHistories.FileManagement;
public class MedicalHistoryCreateDto
{
public Guid UserId { get; set; }
public byte[] Content { get; set; } = [];
}
@@ -0,0 +1,28 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.MedicalHistories.FileManagement;
public class MedicalHistoryCreateValidation : AbstractValidator<MedicalHistoryCreateDto>
{
private readonly IPatientRepository _patientRepository;
public MedicalHistoryCreateValidation(IPatientRepository patientRepository)
{
_patientRepository = patientRepository;
RuleFor(x => x.UserId)
.NotEmpty().WithMessage("Patient is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeExistingUser).WithMessage("Specified patient doesn't exist.")
.WithErrorCode(HttpStatusCodes.NotFound.ToString());
RuleFor(x => x.Content)
.NotEmpty().WithMessage("Description is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString());
}
private async Task<bool> BeExistingUser(Guid userId, CancellationToken cancellationToken)
{
var patient = await _patientRepository.GetByIdAsync(userId);
return patient != null;
}
}
@@ -0,0 +1,156 @@
using Application.Services.Database;
using Application.Services.Database.MongoDB;
using Core.Entities;
namespace Application.Endpoints.MedicalHistories.FileManagement;
public class MedicalHistoryFileManagementHandler
{
private readonly IMedicalHistoryRepository _medicalHistoryRepository;
private readonly IMedicalHistoryMongoDbService _medicalHistoryMongoDbService;
private readonly IPatientRepository _patientRepository;
public MedicalHistoryFileManagementHandler(IMedicalHistoryRepository medicalHistoryRepository,
IPatientRepository patientRepository, IMedicalHistoryMongoDbService medicalHistoryMongoDbService)
{
_medicalHistoryRepository = medicalHistoryRepository;
_patientRepository = patientRepository;
_medicalHistoryMongoDbService = medicalHistoryMongoDbService;
}
public async Task<BaseResponse> HandleGetAll()
{
var documents = await _medicalHistoryRepository.GetAllAsync().ConfigureAwait(false);
if (documents.Any())
return new BaseResponse
{
StatusCode = HttpStatusCodes.OK,
Message = "Retrieved medical histories",
Data = documents.ToList()
};
return new BaseResponse
{
StatusCode = HttpStatusCodes.NoContent,
Message = "Medical histories not found",
Data = null
};
}
public async Task<BaseResponse> HandleGet(Guid id)
{
var medicalHistory = await _medicalHistoryRepository.GetByIdAsync(id).ConfigureAwait(false);
if (medicalHistory != null)
return new BaseResponse
{
StatusCode = HttpStatusCodes.OK,
Message = "Medical history successfully retrieved",
Data = medicalHistory
};
return new BaseResponse
{
StatusCode = HttpStatusCodes.NotFound,
Message = "Medical history not found in system.",
Data = null
};
}
public async Task<BaseResponse> HandleCreate(MedicalHistoryCreateDto medicalHistoryCreateDto)
{
var validation = new MedicalHistoryCreateValidation(_patientRepository);
var validationResult = await validation.ValidateAsync(medicalHistoryCreateDto);
if (!validationResult.IsValid)
{
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var medicalHistory = new MedicalHistory
{
UserId = medicalHistoryCreateDto.UserId,
Content = medicalHistoryCreateDto.Content
};
var medicalHistoryId = medicalHistory.Id;
var newMedicalHistory = new MedicalHistoryAuthorisationModel
{
Id = medicalHistoryId.ToString(),
Authorisation = new List<string>()
};
await _medicalHistoryMongoDbService.AddAsync(newMedicalHistory);
await _medicalHistoryRepository.AddAsync(medicalHistory);
return new BaseResponse
{
StatusCode = HttpStatusCodes.Created,
Message = "Medical history record registered successfully",
Data = medicalHistory
};
}
public async Task<BaseResponse> HandleUpdate(MedicalHistoryUpdateDto updateDto)
{
var validation = new MedicalHistoryUpdateValidation(_medicalHistoryRepository, _patientRepository);
var validationResult = await validation.ValidateAsync(updateDto);
if (!validationResult.IsValid)
{
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var medicalHistoryToUpdate = await _medicalHistoryRepository.GetByIdAsync(updateDto.Id);
medicalHistoryToUpdate.Content = updateDto.Content;
await _medicalHistoryRepository.UpdateAsync(medicalHistoryToUpdate);
return new BaseResponse
{
StatusCode = HttpStatusCodes.NoContent,
Message = "Medical record updated successfully",
Data = null
};
}
public async Task<BaseResponse> HandleDelete(Guid id)
{
var medicalRecord = await _medicalHistoryRepository.GetByIdAsync(id);
if (medicalRecord == null)
return new BaseResponse
{
StatusCode = HttpStatusCodes.NotFound,
Message = "Medical record is not in system.",
Data = null
};
await _medicalHistoryMongoDbService.DeleteAsync<MedicalHistoryAuthorisationModel>("_id", id.ToString());
await _medicalHistoryRepository.DeleteAsync(medicalRecord);
//TODO delete from MongoDB
return new BaseResponse
{
StatusCode = HttpStatusCodes.NoContent,
Message = null,
Data = null
};
}
}
@@ -0,0 +1,7 @@
namespace Application.Endpoints.MedicalHistories.FileManagement;
public class MedicalHistoryUpdateDto
{
public Guid Id { get; set; }
public byte[] Content { get; set; } = [];
}
@@ -0,0 +1,30 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.MedicalHistories.FileManagement;
public class MedicalHistoryUpdateValidation : AbstractValidator<MedicalHistoryUpdateDto>
{
private readonly IMedicalHistoryRepository _medicalHistoryRepository;
private readonly IPatientRepository _patientRepository;
public MedicalHistoryUpdateValidation(IMedicalHistoryRepository medicalHistoryRepository,
IPatientRepository patientRepository)
{
_medicalHistoryRepository = medicalHistoryRepository;
_patientRepository = patientRepository;
RuleFor(x => x.Id)
.NotEmpty().WithMessage("Id is required")
.MustAsync(BeExistingMedicalHistoryRecord).WithMessage("Medical history record does not exist");
RuleFor(x => x.Content)
.NotEmpty().WithMessage("Description is required.");
}
private async Task<bool> BeExistingMedicalHistoryRecord(Guid guid, CancellationToken token)
{
var record = await _medicalHistoryRepository.GetByIdAsync(guid);
return record != null;
}
}
@@ -0,0 +1,7 @@
namespace Application.Endpoints.MedicalHistories.ManageAuthorization;
public class MedicalHistoryManageAuthorizationDoctorDto
{
public Guid MedicalRecordId { get; set; }
public Guid DoctorId { get; set; }
}
@@ -0,0 +1,141 @@
using Application.Services.Database;
using Application.Services.Database.MongoDB;
namespace Application.Endpoints.MedicalHistories.ManageAuthorization;
public class MedicalHistoryManageAuthorizationHandler
{
private readonly IMedicalHistoryRepository _medicalHistoryRepository;
private readonly IDoctorRepository _doctorRepository;
private readonly IMedicalHistoryMongoDbService _medicalHistoryMongoDbService;
public MedicalHistoryManageAuthorizationHandler(IMedicalHistoryRepository medicalHistoryRepository,
IMedicalHistoryMongoDbService medicalHistoryMongoDbService, IDoctorRepository doctorRepository)
{
_medicalHistoryRepository = medicalHistoryRepository;
_medicalHistoryMongoDbService = medicalHistoryMongoDbService;
_doctorRepository = doctorRepository;
}
public async Task<BaseResponse> HandleGrantDoctorAccess(MedicalHistoryManageAuthorizationDoctorDto infoDto)
{
var validation = new MedicalHistoryManageAuthorizationValidation(_medicalHistoryRepository, _doctorRepository);
var validationResult = await validation.ValidateAsync(infoDto);
if (!validationResult.IsValid)
{
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var criteria = new List<(string, string)>();
criteria.Add(("_id", infoDto.MedicalRecordId.ToString()));
var documents = await _medicalHistoryMongoDbService.FindAsync<MedicalHistoryAuthorisationModel>(criteria);
if (!documents.Any())
{
return new BaseResponse()
{
StatusCode = HttpStatusCodes.NotFound,
Message = "Access to medical history not found.",
Data = null
};
}
var authorisations = documents[0].Authorisation;
if (authorisations.Contains(infoDto.ToString()))
{
return new BaseResponse()
{
StatusCode = HttpStatusCodes.Conflict,
Message = "Access to medical history already granted.",
Data = null
};
}
authorisations.Add(infoDto.DoctorId.ToString());
var authorizationModel = new MedicalHistoryAuthorisationModel()
{
Id = infoDto.MedicalRecordId.ToString(),
Authorisation = authorisations
};
await _medicalHistoryMongoDbService.ModifyAsync("_id", infoDto.MedicalRecordId.ToString(), authorizationModel);
return new BaseResponse()
{
StatusCode = HttpStatusCodes.OK,
Message = "Access to medical history granted.",
Data = null
};
}
public async Task<BaseResponse> HandleRevokeDoctorAccess(MedicalHistoryManageAuthorizationDoctorDto infoDto)
{
var validation = new MedicalHistoryManageAuthorizationValidation(_medicalHistoryRepository, _doctorRepository);
var validationResult = await validation.ValidateAsync(infoDto);
if (!validationResult.IsValid)
{
var firstError = validationResult.Errors.FirstOrDefault();
var errorCode = int.TryParse(firstError.ErrorCode, out var code) ? code : -1;
var errorMessage = firstError.ErrorMessage;
return new BaseResponse
{
StatusCode = errorCode,
Message = errorMessage,
Data = null
};
}
var criteria = new List<(string, string)>();
criteria.Add(("_id", infoDto.MedicalRecordId.ToString()));
var documents = await _medicalHistoryMongoDbService.FindAsync<MedicalHistoryAuthorisationModel>(criteria);
if (!documents.Any())
{
return new BaseResponse()
{
StatusCode = HttpStatusCodes.NotFound,
Message = "Access to medical history not found.",
Data = null
};
}
var authorisations = documents[0].Authorisation;
if (!authorisations.Contains(infoDto.DoctorId.ToString()))
{
return new BaseResponse()
{
StatusCode = HttpStatusCodes.Conflict,
Message = "Access to medical history already revoked.",
Data = null
};
}
authorisations.Remove(infoDto.DoctorId.ToString());
var authorizationModel = new MedicalHistoryAuthorisationModel()
{
Id = infoDto.MedicalRecordId.ToString(),
Authorisation = authorisations
};
await _medicalHistoryMongoDbService.ModifyAsync("_id", infoDto.MedicalRecordId.ToString(), authorizationModel);
return new BaseResponse()
{
StatusCode = HttpStatusCodes.OK,
Message = "Access to medical history granted.",
Data = null
};
}
}
@@ -0,0 +1,39 @@
using Application.Services.Database;
using FluentValidation;
namespace Application.Endpoints.MedicalHistories.ManageAuthorization;
public class MedicalHistoryManageAuthorizationValidation : AbstractValidator<MedicalHistoryManageAuthorizationDoctorDto>
{
private readonly IMedicalHistoryRepository _medicalHistoryRepository;
private readonly IDoctorRepository _doctorRepository;
public MedicalHistoryManageAuthorizationValidation(IMedicalHistoryRepository medicalHistoryRepository,
IDoctorRepository doctorRepository)
{
RuleFor(x => x.MedicalRecordId)
.NotEmpty().WithMessage("Id is required").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(BeExistingMedicalHistoryRecord).WithMessage("Medical history record does not exist")
.WithErrorCode(HttpStatusCodes.NotFound.ToString());
RuleFor(x => x.DoctorId)
.NotEmpty().WithMessage("Id is required.").WithErrorCode(HttpStatusCodes.BadRequest.ToString())
.MustAsync(IsDoctorRegistered).WithMessage("Doctor is not registered in system")
.WithErrorCode(HttpStatusCodes.NotFound.ToString());
_medicalHistoryRepository = medicalHistoryRepository;
_doctorRepository = doctorRepository;
}
private async Task<bool> BeExistingMedicalHistoryRecord(Guid guid, CancellationToken token)
{
var record = await _medicalHistoryRepository.GetByIdAsync(guid);
return record != null;
}
private async Task<bool> IsDoctorRegistered(Guid id, CancellationToken cancellationToken)
{
var doctor = await _doctorRepository.GetByIdAsync(id);
return doctor != null;
}
}