Example #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);
                }
            }

            dto.Id = Guid.NewGuid();
            var ticketSale = new TicketSale
            {
                Id           = dto.Id,
                ConferenceId = dto.ConferenceId,
                From         = dto.From,
                To           = dto.To,
                Amount       = dto.Amount,
                Price        = dto.Price,
                Name         = dto.Name
            };
            await _ticketSaleRepository.AddAsync(ticketSale);

            _logger.LogInformation($"Added a ticket sale conference with ID: '{conference.Id}' ({dto.From} - {dto.To}).");

            if (ticketSale.Amount.HasValue)
            {
                _logger.LogInformation($"Generating {ticketSale.Amount} tickets for conference with ID: '{conference.Id}'...");
                var tickets = new List <Ticket>();
                for (var i = 0; i < ticketSale.Amount; i++)
                {
                    var ticket = _ticketGenerator.Generate(conference.Id, ticketSale.Id, ticketSale.Price);
                    tickets.Add(ticket);
                }

                await _ticketRepository.AddManyAsync(tickets);
            }
        }