74 lines
2.6 KiB
C#
74 lines
2.6 KiB
C#
using AutobusApi.Application.Common.Interfaces;
|
|
using AutobusApi.Domain.Entities;
|
|
using AutobusApi.Domain.Enums;
|
|
using MediatR;
|
|
|
|
namespace AutobusApi.Application.TicketGroups.Commands.CreateTicketGroup;
|
|
|
|
public class CreateTicketGroupCommandHandler : IRequestHandler<CreateTicketGroupCommand, int>
|
|
{
|
|
private readonly IApplicationDbContext _dbContext;
|
|
|
|
public CreateTicketGroupCommandHandler(IApplicationDbContext dbContext)
|
|
{
|
|
_dbContext = dbContext;
|
|
}
|
|
|
|
public async Task<int> Handle(
|
|
CreateTicketGroupCommand request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var ticketGroup = new TicketGroup();
|
|
|
|
ticketGroup.BuyerFirstName = request.BuyerFirstName;
|
|
ticketGroup.BuyerLastName = request.BuyerLastName;
|
|
ticketGroup.BuyerPhoneNumber = request.BuyerPhoneNumber;
|
|
ticketGroup.BuyerEmailAddress = request.BuyerEmail;
|
|
|
|
ticketGroup.PassengerFirstName = request.PassengerFirstName;
|
|
ticketGroup.PassengerLastName = request.PassengerLastName;
|
|
ticketGroup.PassengerPatronymic = request.PassengerPatronymic;
|
|
ticketGroup.PassengerSex = Enum.Parse<Sex>(request.PassengerSex);
|
|
ticketGroup.PassengerBirthDate = request.PassengerBirthDate;
|
|
|
|
ticketGroup.PurchaseDateTimeUtc = DateTime.UtcNow;
|
|
|
|
ticketGroup.TicketDocument = new TicketDocument
|
|
{
|
|
Type = Enum.Parse<TicketDocumentType>(request.DocumentType),
|
|
Information = request.DocumentInformation
|
|
};
|
|
|
|
foreach (var ticket in request.Tickets)
|
|
{
|
|
// Check if the given departure and arrival addresses are present in this vehicle enrollment
|
|
var addressCountInRoute = _dbContext.VehicleEnrollments
|
|
.Single(ve => ve.Id == ticket.VehicleEnrollmentId)
|
|
.Route.RouteAddresses
|
|
.OrderBy(ra => ra.Order)
|
|
.SkipWhile(ra => ra.AddressId != ticket.DepartureAddressId)
|
|
.TakeWhile(ra => ra.AddressId != ticket.ArrivalAddressId)
|
|
.Count();
|
|
|
|
if (addressCountInRoute == 0)
|
|
{
|
|
// TODO: throw custom exception
|
|
throw new NotImplementedException();
|
|
}
|
|
|
|
ticketGroup.Tickets.Add(new Ticket
|
|
{
|
|
VehicleEnrollmentId = ticket.VehicleEnrollmentId,
|
|
DepartureAddressId = ticket.DepartureAddressId,
|
|
ArrivalAddressId = ticket.ArrivalAddressId
|
|
});
|
|
}
|
|
|
|
_dbContext.TicketGroups.Add(ticketGroup);
|
|
|
|
await _dbContext.SaveChangesAsync(cancellationToken);
|
|
|
|
return ticketGroup.Id;
|
|
}
|
|
}
|