autobus-api_old/AutobusApi.Application/Companies/Commands/CreateCompany/CreateCompanyCommandHandler.cs

62 lines
2.0 KiB
C#

using AutobusApi.Application.Common.Interfaces;
using AutobusApi.Domain.Entities;
using AutobusApi.Domain.Enums;
using MediatR;
namespace AutobusApi.Application.Companies.Commands.CreateCompany;
public class CreateCompanyCommandHandler : IRequestHandler<CreateCompanyCommand, int>
{
private readonly IApplicationDbContext _dbContext;
private readonly IIdentityService _identityService;
public CreateCompanyCommandHandler(
IApplicationDbContext dbContext,
IIdentityService identityService)
{
_dbContext = dbContext;
_identityService = identityService;
}
public async Task<int> Handle(
CreateCompanyCommand request,
CancellationToken cancellationToken)
{
var company = new Company();
company.Name = request.Name;
company.LegalAddress = request.LegalAddress;
company.ContactPhoneNumber = request.ContactPhoneNumber;
company.ContactEmail = request.ContactEmail;
var userId = await _identityService.RegisterAsync(request.OwnerEmail, request.OwnerPassword, cancellationToken);
company.Employees = new List<Employee>()
{
new Employee()
{
IdentityId = userId,
FirstName = request.OwnerFirstName,
LastName = request.OwnerLastName,
Patronymic = request.OwnerPatronymic,
Sex = Enum.Parse<Sex>(request.OwnerSex),
BirthDate = request.OwnerBirthDate,
Documents = new List<EmployeeDocument>()
{
new EmployeeDocument()
{
Type = Enum.Parse<EmployeeDocumentType>(request.OwnerDocumentType),
Information = request.OwnerDocumentInformation
}
}
}
};
_dbContext.Companies.Add(company);
await _dbContext.SaveChangesAsync(cancellationToken);
return company.Id;
}
}