44 lines
1.7 KiB
C#
44 lines
1.7 KiB
C#
namespace DocuMed.Repository.Handlers.Patients;
|
|
|
|
public class CreatePatientCommandHandler(IRepositoryWrapper repositoryWrapper , UserManager<ApplicationUser> userManager) : IRequestHandler<CreatePatientCommand,Guid>
|
|
{
|
|
public async Task<Guid> Handle(CreatePatientCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var user = await userManager.Users.FirstOrDefaultAsync(u => u.NationalId == request.NationalId,
|
|
cancellationToken);
|
|
if (user == null)
|
|
{
|
|
user = new ApplicationUser
|
|
{
|
|
UserName = request.NationalId,
|
|
NationalId = request.NationalId,
|
|
FirstName = request.FirstName,
|
|
LastName = request.LastName,
|
|
SignUpStatus = SignUpStatus.StartSignUp
|
|
};
|
|
var result = await userManager.CreateAsync(user);
|
|
if (!result.Succeeded)
|
|
throw new AppException(string.Join('|', result.Errors));
|
|
}
|
|
var section = await repositoryWrapper.SetRepository<Section>()
|
|
.TableNoTracking
|
|
.FirstOrDefaultAsync(f => f.Id == request.SectionId, cancellationToken);
|
|
if (section == null)
|
|
throw new BaseApiException(ApiResultStatusCode.NotFound, "Section not found");
|
|
|
|
var patient = Patient.Create(
|
|
request.UnitNumber,
|
|
request.Room,
|
|
request.Bed,
|
|
request.AdmissionAt,
|
|
request.SectionId,
|
|
user.Id,
|
|
section.HospitalId
|
|
);
|
|
|
|
repositoryWrapper.SetRepository<Patient>()
|
|
.Add(patient);
|
|
await repositoryWrapper.SaveChangesAsync(cancellationToken);
|
|
return patient.Id;
|
|
}
|
|
} |