Search in sources :

Example 1 with TicketReservationWithOptionalCodeModification

use of alfio.model.modification.TicketReservationWithOptionalCodeModification in project alf.io by alfio-event.

the class ReservationForm method validateCategory.

private static void validateCategory(Errors bindingResult, TicketReservationManager tickReservationManager, EventManager eventManager, Event event, int maxAmountOfTicket, List<TicketReservationWithOptionalCodeModification> res, Optional<SpecialPrice> specialCode, ZonedDateTime now, TicketReservationModification r) {
    TicketCategory tc = eventManager.getTicketCategoryById(r.getTicketCategoryId(), event.getId());
    SaleableTicketCategory ticketCategory = new SaleableTicketCategory(tc, "", now, event, tickReservationManager.countAvailableTickets(event, tc), maxAmountOfTicket, null);
    if (!ticketCategory.getSaleable()) {
        bindingResult.reject(ErrorsCode.STEP_1_TICKET_CATEGORY_MUST_BE_SALEABLE);
        return;
    }
    res.add(new TicketReservationWithOptionalCodeModification(r, ticketCategory.isAccessRestricted() ? specialCode : Optional.empty()));
}
Also used : TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) TicketCategory(alfio.model.TicketCategory)

Example 2 with TicketReservationWithOptionalCodeModification

use of alfio.model.modification.TicketReservationWithOptionalCodeModification in project alf.io by alfio-event.

the class ReservationForm method validate.

public Optional<Pair<List<TicketReservationWithOptionalCodeModification>, List<ASReservationWithOptionalCodeModification>>> validate(Errors bindingResult, TicketReservationManager tickReservationManager, AdditionalServiceRepository additionalServiceRepository, EventManager eventManager, Event event) {
    int selectionCount = ticketSelectionCount();
    if (selectionCount <= 0) {
        bindingResult.reject(ErrorsCode.STEP_1_SELECT_AT_LEAST_ONE);
        return Optional.empty();
    }
    List<Pair<TicketReservationModification, Integer>> maxTicketsByTicketReservation = selected().stream().map(r -> Pair.of(r, tickReservationManager.maxAmountOfTicketsForCategory(event.getOrganizationId(), event.getId(), r.getTicketCategoryId()))).collect(toList());
    Optional<Pair<TicketReservationModification, Integer>> error = maxTicketsByTicketReservation.stream().filter(p -> p.getKey().getAmount() > p.getValue()).findAny();
    if (error.isPresent()) {
        bindingResult.reject(ErrorsCode.STEP_1_OVER_MAXIMUM, new Object[] { error.get().getValue() }, null);
        return Optional.empty();
    }
    final List<TicketReservationModification> categories = selected();
    final List<AdditionalServiceReservationModification> additionalServices = selectedAdditionalServices();
    final boolean validCategorySelection = categories.stream().allMatch(c -> {
        TicketCategory tc = eventManager.getTicketCategoryById(c.getTicketCategoryId(), event.getId());
        return OptionalWrapper.optionally(() -> eventManager.findEventByTicketCategory(tc)).isPresent();
    });
    final boolean validAdditionalServiceSelected = additionalServices.stream().allMatch(asm -> {
        AdditionalService as = eventManager.getAdditionalServiceById(asm.getAdditionalServiceId(), event.getId());
        ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
        return as.getInception(event.getZoneId()).isBefore(now) && as.getExpiration(event.getZoneId()).isAfter(now) && asm.getQuantity() >= 0 && ((as.isFixPrice() && asm.isQuantityValid(as, selectionCount)) || (!as.isFixPrice() && asm.getAmount() != null && asm.getAmount().compareTo(BigDecimal.ZERO) >= 0)) && OptionalWrapper.optionally(() -> eventManager.findEventByAdditionalService(as)).isPresent();
    });
    if (!validCategorySelection || !validAdditionalServiceSelected) {
        bindingResult.reject(ErrorsCode.STEP_1_TICKET_CATEGORY_MUST_BE_SALEABLE);
        return Optional.empty();
    }
    List<TicketReservationWithOptionalCodeModification> res = new ArrayList<>();
    // 
    Optional<SpecialPrice> specialCode = Optional.ofNullable(StringUtils.trimToNull(promoCode)).flatMap((trimmedCode) -> tickReservationManager.getSpecialPriceByCode(trimmedCode));
    // 
    final ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
    maxTicketsByTicketReservation.forEach((pair) -> validateCategory(bindingResult, tickReservationManager, eventManager, event, pair.getRight(), res, specialCode, now, pair.getLeft()));
    return bindingResult.hasErrors() ? Optional.empty() : Optional.of(Pair.of(res, additionalServices.stream().map(as -> new ASReservationWithOptionalCodeModification(as, specialCode)).collect(Collectors.toList())));
}
Also used : Errors(org.springframework.validation.Errors) TicketReservationModification(alfio.model.modification.TicketReservationModification) ZonedDateTime(java.time.ZonedDateTime) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) BigDecimal(java.math.BigDecimal) Pair(org.apache.commons.lang3.tuple.Pair) ASReservationWithOptionalCodeModification(alfio.model.modification.ASReservationWithOptionalCodeModification) AdditionalServiceRepository(alfio.repository.AdditionalServiceRepository) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) Collections.emptyList(java.util.Collections.emptyList) Optional.ofNullable(java.util.Optional.ofNullable) ErrorsCode(alfio.util.ErrorsCode) OptionalWrapper(alfio.util.OptionalWrapper) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) TicketReservationManager(alfio.manager.TicketReservationManager) TicketCategory(alfio.model.TicketCategory) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) EventManager(alfio.manager.EventManager) AdditionalService(alfio.model.AdditionalService) SpecialPrice(alfio.model.SpecialPrice) Data(lombok.Data) Optional(java.util.Optional) Event(alfio.model.Event) AdditionalServiceReservationModification(alfio.model.modification.AdditionalServiceReservationModification) SpecialPrice(alfio.model.SpecialPrice) AdditionalService(alfio.model.AdditionalService) ArrayList(java.util.ArrayList) SaleableTicketCategory(alfio.controller.decorator.SaleableTicketCategory) TicketCategory(alfio.model.TicketCategory) ASReservationWithOptionalCodeModification(alfio.model.modification.ASReservationWithOptionalCodeModification) AdditionalServiceReservationModification(alfio.model.modification.AdditionalServiceReservationModification) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) ZonedDateTime(java.time.ZonedDateTime) TicketReservationModification(alfio.model.modification.TicketReservationModification) Pair(org.apache.commons.lang3.tuple.Pair)

Example 3 with TicketReservationWithOptionalCodeModification

use of alfio.model.modification.TicketReservationWithOptionalCodeModification in project alf.io by alfio-event.

the class TicketReservationManager method createTicketReservation.

/**
 * Create a ticket reservation. It will create a reservation _only_ if it can find enough tickets. Note that it will not do date/validity validation. This must be ensured by the
 * caller.
 *
 * @param event
 * @param list
 * @param reservationExpiration
 * @param forWaitingQueue
 * @return
 */
public String createTicketReservation(Event event, List<TicketReservationWithOptionalCodeModification> list, List<ASReservationWithOptionalCodeModification> additionalServices, Date reservationExpiration, Optional<String> specialPriceSessionId, Optional<String> promotionCodeDiscount, Locale locale, boolean forWaitingQueue) throws NotEnoughTicketsException, MissingSpecialPriceTokenException, InvalidSpecialPriceTokenException {
    String reservationId = UUID.randomUUID().toString();
    Optional<PromoCodeDiscount> discount = promotionCodeDiscount.flatMap((promoCodeDiscount) -> promoCodeDiscountRepository.findPromoCodeInEventOrOrganization(event.getId(), promoCodeDiscount));
    ticketReservationRepository.createNewReservation(reservationId, reservationExpiration, discount.map(PromoCodeDiscount::getId).orElse(null), locale.getLanguage(), event.getId(), event.getVat(), event.isVatIncluded());
    list.forEach(t -> reserveTicketsForCategory(event, specialPriceSessionId, reservationId, t, locale, forWaitingQueue, discount.orElse(null)));
    int ticketCount = list.stream().map(TicketReservationWithOptionalCodeModification::getAmount).mapToInt(Integer::intValue).sum();
    // apply valid additional service with supplement policy mandatory one for ticket
    additionalServiceRepository.findAllInEventWithPolicy(event.getId(), AdditionalService.SupplementPolicy.MANDATORY_ONE_FOR_TICKET).stream().filter(AdditionalService::getSaleable).forEach(as -> {
        AdditionalServiceReservationModification asrm = new AdditionalServiceReservationModification();
        asrm.setAdditionalServiceId(as.getId());
        asrm.setQuantity(ticketCount);
        reserveAdditionalServicesForReservation(event.getId(), reservationId, new ASReservationWithOptionalCodeModification(asrm, Optional.empty()), discount.orElse(null));
    });
    additionalServices.forEach(as -> reserveAdditionalServicesForReservation(event.getId(), reservationId, as, discount.orElse(null)));
    TicketReservation reservation = ticketReservationRepository.findReservationById(reservationId);
    OrderSummary orderSummary = orderSummaryForReservationId(reservation.getId(), event, Locale.forLanguageTag(reservation.getUserLanguage()));
    ticketReservationRepository.addReservationInvoiceOrReceiptModel(reservationId, Json.toJson(orderSummary));
    auditingRepository.insert(reservationId, null, event.getId(), Audit.EventType.RESERVATION_CREATE, new Date(), Audit.EntityType.RESERVATION, reservationId);
    return reservationId;
}
Also used : TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) ASReservationWithOptionalCodeModification(alfio.model.modification.ASReservationWithOptionalCodeModification) AdditionalServiceReservationModification(alfio.model.modification.AdditionalServiceReservationModification)

Example 4 with TicketReservationWithOptionalCodeModification

use of alfio.model.modification.TicketReservationWithOptionalCodeModification in project alf.io by alfio-event.

the class WaitingQueueManager method distributeAvailableSeats.

private Stream<Triple<WaitingQueueSubscription, TicketReservationWithOptionalCodeModification, ZonedDateTime>> distributeAvailableSeats(Event event, Ticket.TicketStatus status, Supplier<Integer> availableSeatSupplier) {
    int availableSeats = availableSeatSupplier.get();
    int eventId = event.getId();
    log.debug("processing {} subscribers from waiting queue", availableSeats);
    List<TicketCategory> unboundedCategories = ticketCategoryRepository.findUnboundedOrderByExpirationDesc(eventId);
    Iterator<Ticket> tickets = ticketRepository.selectWaitingTicketsForUpdate(eventId, status.name(), availableSeats).stream().filter(t -> t.getCategoryId() != null || unboundedCategories.size() > 0).iterator();
    int expirationTimeout = configurationManager.getIntConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), WAITING_QUEUE_RESERVATION_TIMEOUT), 4);
    ZonedDateTime expiration = ZonedDateTime.now(event.getZoneId()).plusHours(expirationTimeout).with(WorkingDaysAdjusters.defaultWorkingDays());
    if (!tickets.hasNext()) {
        log.warn("Unable to assign tickets, returning an empty stream");
        return Stream.empty();
    }
    return waitingQueueRepository.loadWaiting(eventId, availableSeats).stream().map(wq -> Pair.of(wq, tickets.next())).map(pair -> {
        TicketReservationModification ticketReservation = new TicketReservationModification();
        ticketReservation.setAmount(1);
        Integer categoryId = Optional.ofNullable(pair.getValue().getCategoryId()).orElseGet(() -> findBestCategory(unboundedCategories, pair.getKey()).orElseThrow(RuntimeException::new).getId());
        ticketReservation.setTicketCategoryId(categoryId);
        return Pair.of(pair.getLeft(), new TicketReservationWithOptionalCodeModification(ticketReservation, Optional.<SpecialPrice>empty()));
    }).map(pair -> Triple.of(pair.getKey(), pair.getValue(), expiration));
}
Also used : java.util(java.util) TicketReservationModification(alfio.model.modification.TicketReservationModification) TicketCategoryRepository(alfio.repository.TicketCategoryRepository) AffectedRowCountAndKey(ch.digitalfondue.npjt.AffectedRowCountAndKey) WaitingQueueRepository(alfio.repository.WaitingQueueRepository) ZonedDateTime(java.time.ZonedDateTime) NamedParameterJdbcTemplate(org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) ConfigurationManager(alfio.manager.system.ConfigurationManager) Supplier(java.util.function.Supplier) Pair(org.apache.commons.lang3.tuple.Pair) WorkingDaysAdjusters(alfio.util.WorkingDaysAdjusters) Triple(org.apache.commons.lang3.tuple.Triple) TemplateResource(alfio.util.TemplateResource) MessageSource(org.springframework.context.MessageSource) EventUtil.determineAvailableSeats(alfio.util.EventUtil.determineAvailableSeats) OrganizationRepository(alfio.repository.user.OrganizationRepository) TicketRepository(alfio.repository.TicketRepository) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) Organization(alfio.model.user.Organization) TemplateManager(alfio.util.TemplateManager) EventRepository(alfio.repository.EventRepository) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) Component(org.springframework.stereotype.Component) Validate(org.apache.commons.lang3.Validate) Stream(java.util.stream.Stream) alfio.model(alfio.model) Configuration(alfio.model.system.Configuration) Log4j2(lombok.extern.log4j.Log4j2) AllArgsConstructor(lombok.AllArgsConstructor) ConfigurationKeys(alfio.model.system.ConfigurationKeys) PreReservedTicketDistributor(alfio.util.PreReservedTicketDistributor) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) ZonedDateTime(java.time.ZonedDateTime) TicketReservationModification(alfio.model.modification.TicketReservationModification)

Aggregations

TicketReservationWithOptionalCodeModification (alfio.model.modification.TicketReservationWithOptionalCodeModification)4 SaleableTicketCategory (alfio.controller.decorator.SaleableTicketCategory)2 TicketCategory (alfio.model.TicketCategory)2 ASReservationWithOptionalCodeModification (alfio.model.modification.ASReservationWithOptionalCodeModification)2 AdditionalServiceReservationModification (alfio.model.modification.AdditionalServiceReservationModification)2 TicketReservationModification (alfio.model.modification.TicketReservationModification)2 ZonedDateTime (java.time.ZonedDateTime)2 Pair (org.apache.commons.lang3.tuple.Pair)2 EventManager (alfio.manager.EventManager)1 TicketReservationManager (alfio.manager.TicketReservationManager)1 ConfigurationManager (alfio.manager.system.ConfigurationManager)1 alfio.model (alfio.model)1 AdditionalService (alfio.model.AdditionalService)1 Event (alfio.model.Event)1 SpecialPrice (alfio.model.SpecialPrice)1 Configuration (alfio.model.system.Configuration)1 ConfigurationKeys (alfio.model.system.ConfigurationKeys)1 Organization (alfio.model.user.Organization)1 AdditionalServiceRepository (alfio.repository.AdditionalServiceRepository)1 EventRepository (alfio.repository.EventRepository)1