Search in sources :

Example 1 with ASReservationWithOptionalCodeModification

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

the class TicketReservationManager method reserveAdditionalServicesForReservation.

private void reserveAdditionalServicesForReservation(int eventId, String transactionId, ASReservationWithOptionalCodeModification additionalServiceReservation, PromoCodeDiscount discount) {
    Optional.ofNullable(additionalServiceReservation.getAdditionalServiceId()).flatMap(id -> optionally(() -> additionalServiceRepository.getById(id, eventId))).filter(as -> additionalServiceReservation.getQuantity() > 0 && (as.isFixPrice() || Optional.ofNullable(additionalServiceReservation.getAmount()).filter(a -> a.compareTo(BigDecimal.ZERO) > 0).isPresent())).map(as -> Pair.of(eventRepository.findById(eventId), as)).ifPresent(pair -> {
        Event e = pair.getKey();
        AdditionalService as = pair.getValue();
        IntStream.range(0, additionalServiceReservation.getQuantity()).forEach(i -> {
            AdditionalServicePriceContainer pc = AdditionalServicePriceContainer.from(additionalServiceReservation.getAmount(), as, e, discount);
            additionalServiceItemRepository.insert(UUID.randomUUID().toString(), ZonedDateTime.now(Clock.systemUTC()), transactionId, as.getId(), AdditionalServiceItemStatus.PENDING, eventId, pc.getSrcPriceCts(), unitToCents(pc.getFinalPrice()), unitToCents(pc.getVAT()), unitToCents(pc.getAppliedDiscount()));
        });
    });
}
Also used : alfio.repository(alfio.repository) PaymentProxy(alfio.model.transaction.PaymentProxy) DiscountType(alfio.model.PromoCodeDiscount.DiscountType) ZonedDateTime(java.time.ZonedDateTime) PaymentResult(alfio.manager.support.PaymentResult) AdditionalServicePriceContainer(alfio.model.decorator.AdditionalServicePriceContainer) PartialTicketTextGenerator(alfio.manager.support.PartialTicketTextGenerator) Mailer(alfio.manager.system.Mailer) TicketStatus(alfio.model.Ticket.TicketStatus) StringUtils(org.apache.commons.lang3.StringUtils) Collections.singletonList(java.util.Collections.singletonList) BigDecimal(java.math.BigDecimal) MonetaryUtil.formatCents(alfio.util.MonetaryUtil.formatCents) DateUtils.truncate(org.apache.commons.lang3.time.DateUtils.truncate) Pair(org.apache.commons.lang3.tuple.Pair) OFFLINE_PAYMENT(alfio.model.TicketReservation.TicketReservationStatus.OFFLINE_PAYMENT) Arrays.asList(java.util.Arrays.asList) ASReservationWithOptionalCodeModification(alfio.model.modification.ASReservationWithOptionalCodeModification) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) Triple(org.apache.commons.lang3.tuple.Triple) OrganizationRepository(alfio.repository.user.OrganizationRepository) Organization(alfio.model.user.Organization) Predicate(java.util.function.Predicate) FeeCalculator(alfio.manager.support.FeeCalculator) Visit(de.danielbechler.diff.node.Visit) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) DiffNode(de.danielbechler.diff.node.DiffNode) Role(alfio.model.user.Role) Stream(java.util.stream.Stream) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) alfio.model(alfio.model) UserRepository(alfio.repository.user.UserRepository) AdditionalServiceItemPriceContainer(alfio.model.decorator.AdditionalServiceItemPriceContainer) Configuration(alfio.model.system.Configuration) AdditionalServiceItemStatus(alfio.model.AdditionalServiceItem.AdditionalServiceItemStatus) AdditionalServiceReservationModification(alfio.model.modification.AdditionalServiceReservationModification) OptionalWrapper.optionally(alfio.util.OptionalWrapper.optionally) IntStream(java.util.stream.IntStream) java.util(java.util) MonetaryUtil.unitToCents(alfio.util.MonetaryUtil.unitToCents) TransactionDefinition(org.springframework.transaction.TransactionDefinition) ConfigurationManager(alfio.manager.system.ConfigurationManager) Function(java.util.function.Function) alfio.util(alfio.util) TicketPriceContainer(alfio.model.decorator.TicketPriceContainer) IN_PAYMENT(alfio.model.TicketReservation.TicketReservationStatus.IN_PAYMENT) UserDetails(org.springframework.security.core.userdetails.UserDetails) TicketReservationStatus(alfio.model.TicketReservation.TicketReservationStatus) MessageSource(org.springframework.context.MessageSource) ObjectDifferBuilder(de.danielbechler.diff.ObjectDifferBuilder) TicketReservationWithOptionalCodeModification(alfio.model.modification.TicketReservationWithOptionalCodeModification) UpdateTicketOwnerForm(alfio.controller.form.UpdateTicketOwnerForm) IOException(java.io.IOException) Status(alfio.model.SpecialPrice.Status) DateUtils.addHours(org.apache.commons.lang3.time.DateUtils.addHours) Component(org.springframework.stereotype.Component) Validate(org.apache.commons.lang3.Validate) ChronoUnit(java.time.temporal.ChronoUnit) CategoryEvaluator(alfio.manager.support.CategoryEvaluator) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Log4j2(lombok.extern.log4j.Log4j2) Clock(java.time.Clock) ConfigurationKeys(alfio.model.system.ConfigurationKeys) Transactional(org.springframework.transaction.annotation.Transactional) AdditionalServicePriceContainer(alfio.model.decorator.AdditionalServicePriceContainer)

Example 2 with ASReservationWithOptionalCodeModification

use of alfio.model.modification.ASReservationWithOptionalCodeModification 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 ASReservationWithOptionalCodeModification

use of alfio.model.modification.ASReservationWithOptionalCodeModification 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)

Aggregations

ASReservationWithOptionalCodeModification (alfio.model.modification.ASReservationWithOptionalCodeModification)3 AdditionalServiceReservationModification (alfio.model.modification.AdditionalServiceReservationModification)3 TicketReservationWithOptionalCodeModification (alfio.model.modification.TicketReservationWithOptionalCodeModification)3 BigDecimal (java.math.BigDecimal)2 SaleableTicketCategory (alfio.controller.decorator.SaleableTicketCategory)1 UpdateTicketOwnerForm (alfio.controller.form.UpdateTicketOwnerForm)1 EventManager (alfio.manager.EventManager)1 TicketReservationManager (alfio.manager.TicketReservationManager)1 CategoryEvaluator (alfio.manager.support.CategoryEvaluator)1 FeeCalculator (alfio.manager.support.FeeCalculator)1 PartialTicketTextGenerator (alfio.manager.support.PartialTicketTextGenerator)1 PaymentResult (alfio.manager.support.PaymentResult)1 ConfigurationManager (alfio.manager.system.ConfigurationManager)1 Mailer (alfio.manager.system.Mailer)1 alfio.model (alfio.model)1 AdditionalService (alfio.model.AdditionalService)1 AdditionalServiceItemStatus (alfio.model.AdditionalServiceItem.AdditionalServiceItemStatus)1 Event (alfio.model.Event)1 DiscountType (alfio.model.PromoCodeDiscount.DiscountType)1 SpecialPrice (alfio.model.SpecialPrice)1