Exemplo n.º 1
0
        public async Task AddAsync(TicketSaleDto dto)
        {
            var conference = await _conferenceRepository.GetAsync(dto.ConferenceId);

            if (conference is null)
            {
                throw new ConferenceNotFoundException(dto.ConferenceId);
            }

            if (conference.ParticipantsLimit.HasValue)
            {
                var ticketsCount = await _ticketRepository.CountForConferenceAsync(conference.Id);

                if (ticketsCount + dto.Amount > conference.ParticipantsLimit)
                {
                    throw new TooManyTicketsException(conference.Id);
                }
            }

            var ticketSale = new TicketSale(dto.ConferenceId, dto.Name, dto.Price, dto.Amount, dto.From, dto.To);

            _ticketSaleRepository.Add(ticketSale);
            await _ticketSaleRepository.UnitOfWork.SaveChangesAsync();

            if (ticketSale.Amount.HasValue)
            {
                var tickets = new List <Ticket>();
                for (var i = 0; i < ticketSale.Amount; i++)
                {
                    var ticket = _ticketsFactory.Generate(conference.Id, ticketSale.Price, ticketSale);
                    tickets.Add(ticket);
                }

                _ticketRepository.AddMany(tickets);
                await _ticketRepository.UnitOfWork.SaveChangesAsync();
            }
        }