Search in sources :

Example 1 with ContactAndTicketsForm

use of alfio.controller.form.ContactAndTicketsForm in project alf.io by alfio-event.

the class ReverseChargeManagerIntegrationTest method createReservation.

private ReservationInfo createReservation(String id, boolean requestInvoice) {
    var categories = ticketCategoryRepository.findAllTicketCategories(event.getId());
    var form = new ReservationForm();
    var first = new TicketReservationModification();
    first.setQuantity(2);
    first.setTicketCategoryId(categories.get(0).getId());
    var second = new TicketReservationModification();
    second.setQuantity(2);
    second.setTicketCategoryId(categories.get(1).getId());
    form.setReservation(List.of(first, second));
    var reservationId = id;
    if (reservationId == null) {
        var res = eventApiV2Controller.reserveTickets(event.getShortName(), "en", form, new BeanPropertyBindingResult(form, "reservation"), new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse()), null);
        assertEquals(HttpStatus.OK, res.getStatusCode());
        var resBody = res.getBody();
        assertNotNull(resBody);
        assertTrue(resBody.isSuccess());
        assertEquals(0, resBody.getErrorCount());
        reservationId = resBody.getValue();
    }
    // enter billing data
    var contactForm = new ContactAndTicketsForm();
    // move to overview status
    contactForm = new ContactAndTicketsForm();
    contactForm.setFirstName("First");
    contactForm.setLastName("Last");
    contactForm.setEmail("test@test.com");
    contactForm.setAddCompanyBillingDetails(requestInvoice);
    contactForm.setInvoiceRequested(requestInvoice);
    if (requestInvoice) {
        contactForm.setBillingAddressLine1("Piazza della Riforma");
        contactForm.setBillingAddressCity("Lugano");
        contactForm.setBillingAddressZip("6900");
        contactForm.setVatCountryCode("CH");
        contactForm.setVatNr("123456789");
    }
    var tickets = ticketRepository.findTicketsInReservation(reservationId).stream().map(t -> {
        var ticketForm = new UpdateTicketOwnerForm();
        ticketForm.setFirstName("ticketfull");
        ticketForm.setLastName("ticketname");
        ticketForm.setEmail("tickettest@test.com");
        return Map.entry(t.getUuid(), ticketForm);
    }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    contactForm.setTickets(tickets);
    var overviewRes = reservationApiV2Controller.validateToOverview(reservationId, "en", false, contactForm, new BeanPropertyBindingResult(contactForm, "paymentForm"), null);
    assertEquals(HttpStatus.OK, overviewRes.getStatusCode());
    var resInfoRes = reservationApiV2Controller.getReservationInfo(reservationId, null);
    assertEquals(HttpStatus.OK, resInfoRes.getStatusCode());
    var reservation = resInfoRes.getBody();
    assertNotNull(reservation);
    assertFalse(reservation.getOrderSummary().isFree());
    return reservation;
}
Also used : ContactAndTicketsForm(alfio.controller.form.ContactAndTicketsForm) ReservationForm(alfio.controller.form.ReservationForm) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) TicketReservationModification(alfio.model.modification.TicketReservationModification) TicketCategoryRepository(alfio.repository.TicketCategoryRepository) AlfioMetadata(alfio.model.metadata.AlfioMetadata) Autowired(org.springframework.beans.factory.annotation.Autowired) ActiveProfiles(org.springframework.test.context.ActiveProfiles) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) BigDecimal(java.math.BigDecimal) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) LocalTime(java.time.LocalTime) ReservationApiV2Controller(alfio.controller.api.v2.user.ReservationApiV2Controller) OrganizationRepository(alfio.repository.user.OrganizationRepository) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) EventRepository(alfio.repository.EventRepository) Collectors(java.util.stream.Collectors) ConfigurationRepository(alfio.repository.system.ConfigurationRepository) Test(org.junit.jupiter.api.Test) List(java.util.List) Initializer(alfio.config.Initializer) ContactAndTicketsForm(alfio.controller.form.ContactAndTicketsForm) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) LocalDate(java.time.LocalDate) Configuration(alfio.model.system.Configuration) DataSourceConfiguration(alfio.config.DataSourceConfiguration) ClockProvider(alfio.util.ClockProvider) ConfigurationManager(alfio.manager.system.ConfigurationManager) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) DateTimeModification(alfio.model.modification.DateTimeModification) SummaryRow(alfio.model.SummaryRow) ControllerConfiguration(alfio.controller.api.ControllerConfiguration) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) ReservationInfo(alfio.controller.api.v2.model.ReservationInfo) BaseIntegrationTest(alfio.util.BaseIntegrationTest) TicketCategoryModification(alfio.model.modification.TicketCategoryModification) TicketRepository(alfio.repository.TicketRepository) UpdateTicketOwnerForm(alfio.controller.form.UpdateTicketOwnerForm) IntegrationTestUtil(alfio.test.util.IntegrationTestUtil) HttpStatus(org.springframework.http.HttpStatus) TicketCategory(alfio.model.TicketCategory) EventApiV2Controller(alfio.controller.api.v2.user.EventApiV2Controller) UserManager(alfio.manager.user.UserManager) ContextConfiguration(org.springframework.test.context.ContextConfiguration) Assertions(org.junit.jupiter.api.Assertions) Event(alfio.model.Event) TestConfiguration(alfio.TestConfiguration) ConfigurationKeys(alfio.model.system.ConfigurationKeys) Transactional(org.springframework.transaction.annotation.Transactional) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ReservationForm(alfio.controller.form.ReservationForm) UpdateTicketOwnerForm(alfio.controller.form.UpdateTicketOwnerForm) TicketReservationModification(alfio.model.modification.TicketReservationModification) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) Map(java.util.Map) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 2 with ContactAndTicketsForm

use of alfio.controller.form.ContactAndTicketsForm in project alf.io by alfio-event.

the class ReverseChargeManager method checkAndApplyVATRules.

public void checkAndApplyVATRules(PurchaseContext purchaseContext, String reservationId, ContactAndTicketsForm contactAndTicketsForm, BindingResult bindingResult) {
    String country = contactAndTicketsForm.getVatCountryCode();
    // validate VAT presence if Reverse Charge is enabled
    var reverseChargeConfiguration = EuVatChecker.loadConfigurationForReverseChargeCheck(configurationManager, purchaseContext);
    if (EuVatChecker.reverseChargeEnabled(reverseChargeConfiguration) && (country == null || isEUCountry(country))) {
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "vatNr", "error.emptyField");
    }
    boolean isEvent = purchaseContext.ofType(PurchaseContext.PurchaseContextType.event);
    // we must take into account specific configuration only if the purchase context is an Event.
    // Otherwise, specific settings do not apply
    boolean reverseChargeInPerson = !isEvent || reverseChargeConfiguration.get(ENABLE_REVERSE_CHARGE_IN_PERSON).getValueAsBooleanOrDefault();
    boolean reverseChargeOnline = !isEvent || reverseChargeConfiguration.get(ENABLE_REVERSE_CHARGE_ONLINE).getValueAsBooleanOrDefault();
    try {
        var optionalReservation = ticketReservationRepository.findOptionalReservationById(reservationId);
        List<TicketCategory> categoriesList = optionalReservation.filter(// skip load if the current context is not "event"
        res -> isEvent).map(res -> ticketCategoryRepository.findCategoriesInReservation(res.getId())).orElse(List.of());
        Optional<VatDetail> vatDetail = optionalReservation.filter(e -> {
            if (purchaseContext.ofType(PurchaseContext.PurchaseContextType.event) && (!reverseChargeInPerson || !reverseChargeOnline)) {
                var eventFormat = purchaseContext.event().orElseThrow().getFormat();
                // if we find at least one category matching the criteria, then we can proceed
                return categoriesList.stream().anyMatch(findReverseChargeCategory(reverseChargeInPerson, reverseChargeOnline, eventFormat));
            }
            var vatStatus = purchaseContext.getVatStatus();
            return vatStatus == INCLUDED || vatStatus == NOT_INCLUDED;
        }).filter(e -> vatChecker.isReverseChargeEnabledFor(purchaseContext)).flatMap(e -> vatChecker.checkVat(contactAndTicketsForm.getVatNr(), country, purchaseContext));
        if (vatDetail.isPresent()) {
            var vatValidation = vatDetail.get();
            if (!vatValidation.isValid()) {
                bindingResult.rejectValue("vatNr", "error.STEP_2_INVALID_VAT");
            } else {
                var reservation = ticketReservationManager.findById(reservationId).orElseThrow();
                var currencyCode = reservation.getCurrencyCode();
                PriceContainer.VatStatus vatStatus = determineVatStatus(purchaseContext.getVatStatus(), vatValidation.isVatExempt());
                // standard case: Reverse Charge is applied to the entire reservation
                var discount = reservation.getPromoCodeDiscountId() != null ? promoCodeDiscountRepository.findById(reservation.getPromoCodeDiscountId()) : null;
                if (!isEvent || (reverseChargeOnline && reverseChargeInPerson)) {
                    if (isEvent) {
                        var event = purchaseContext.event().orElseThrow();
                        var priceContainers = mapPriceContainersByCategoryId(categoriesList, (a) -> true, currencyCode, vatStatus, discount, event);
                        // update all tickets in reservation to match the VAT_STATUS
                        ticketRepository.updateVatStatusForReservation(reservationId, vatStatus);
                        updateTicketPricesByCategory(reservationId, currencyCode, vatStatus, event, priceContainers);
                    }
                    updateBillingData(reservationId, contactAndTicketsForm, purchaseContext, country, trimToNull(vatValidation.getVatNr()), reservation, vatStatus);
                } else {
                    var event = purchaseContext.event().orElseThrow();
                    var eventFormat = event.getFormat();
                    var matchingCategories = mapPriceContainersByCategoryId(categoriesList, findReverseChargeCategory(reverseChargeInPerson, reverseChargeOnline, eventFormat), currencyCode, vatStatus, discount, event);
                    updateTicketPricesByCategory(reservationId, currencyCode, vatStatus, event, matchingCategories);
                    // update billing data for the reservation, using the original VatStatus from reservation
                    updateBillingData(reservationId, contactAndTicketsForm, purchaseContext, country, trimToNull(vatValidation.getVatNr()), reservation, reservation.getVatStatus());
                }
                vatChecker.logSuccessfulValidation(vatValidation, reservationId, purchaseContext);
            }
        } else if (optionalReservation.isPresent() && contactAndTicketsForm.isItalyEInvoicingSplitPayment()) {
            var reservation = optionalReservation.get();
            var vatStatus = purchaseContext.getVatStatus() == INCLUDED ? INCLUDED_NOT_CHARGED : NOT_INCLUDED_NOT_CHARGED;
            updateBillingData(reservationId, contactAndTicketsForm, purchaseContext, country, trimToNull(contactAndTicketsForm.getVatNr()), reservation, vatStatus);
        }
    } catch (IllegalStateException ise) {
        // vat checker failure
        bindingResult.rejectValue("vatNr", "error.vatVIESDown");
    }
}
Also used : alfio.repository(alfio.repository) NOT_INCLUDED_NOT_CHARGED(alfio.model.PriceContainer.VatStatus.NOT_INCLUDED_NOT_CHARGED) StringUtils.trimToNull(org.apache.commons.lang3.StringUtils.trimToNull) MonetaryUtil.unitToCents(alfio.util.MonetaryUtil.unitToCents) Predicate(java.util.function.Predicate) NamedParameterJdbcTemplate(org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) BindingResult(org.springframework.validation.BindingResult) ConfigurationManager(alfio.manager.system.ConfigurationManager) Function(java.util.function.Function) ReservationPriceCalculator(alfio.manager.system.ReservationPriceCalculator) BigDecimal(java.math.BigDecimal) Component(org.springframework.stereotype.Component) List(java.util.List) ContactAndTicketsForm(alfio.controller.form.ContactAndTicketsForm) ValidationUtils(org.springframework.validation.ValidationUtils) Collectors.toMap(java.util.stream.Collectors.toMap) alfio.model(alfio.model) Map(java.util.Map) Optional(java.util.Optional) AllArgsConstructor(lombok.AllArgsConstructor) VatStatus(alfio.model.PriceContainer.VatStatus) ConfigurationKeys(alfio.model.system.ConfigurationKeys) VatStatus(alfio.model.PriceContainer.VatStatus)

Example 3 with ContactAndTicketsForm

use of alfio.controller.form.ContactAndTicketsForm in project alf.io by alfio-event.

the class BillingDocumentCreationIntegrationTest method createReservation.

private String createReservation(Consumer<ContactAndTicketsForm> formCustomizer) {
    var categories = ticketCategoryRepository.findAllTicketCategories(event.getId());
    assertFalse(categories.isEmpty());
    int categoryId = categories.get(0).getId();
    var form = new ReservationForm();
    var ticketReservation = new TicketReservationModification();
    ticketReservation.setQuantity(1);
    ticketReservation.setTicketCategoryId(categoryId);
    form.setReservation(List.of(ticketReservation));
    var res = eventApiV2Controller.reserveTickets(event.getShortName(), "en", form, new BeanPropertyBindingResult(form, "reservation"), new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse()), null);
    assertEquals(HttpStatus.OK, res.getStatusCode());
    var resBody = res.getBody();
    assertNotNull(resBody);
    assertTrue(resBody.isSuccess());
    assertEquals(0, resBody.getErrorCount());
    var reservationId = resBody.getValue();
    // reservation is now in PENDING status
    var resInfoRes = reservationApiV2Controller.getReservationInfo(reservationId, null);
    assertEquals(HttpStatus.OK, resInfoRes.getStatusCode());
    assertNotNull(resInfoRes.getBody());
    var ticketsByCat = resInfoRes.getBody().getTicketsByCategory();
    assertEquals(1, ticketsByCat.size());
    assertEquals(1, ticketsByCat.get(0).getTickets().size());
    var ticket = ticketsByCat.get(0).getTickets().get(0);
    var contactForm = new ContactAndTicketsForm();
    contactForm.setAddCompanyBillingDetails(true);
    contactForm.setSkipVatNr(false);
    contactForm.setInvoiceRequested(true);
    contactForm.setEmail("test@test.com");
    contactForm.setFirstName("full");
    contactForm.setLastName("name");
    var ticketForm1 = new UpdateTicketOwnerForm();
    ticketForm1.setFirstName("ticketfull");
    ticketForm1.setLastName("ticketname");
    ticketForm1.setEmail("tickettest@test.com");
    formCustomizer.accept(contactForm);
    contactForm.setTickets(Map.of(ticket.getUuid(), ticketForm1));
    var success = reservationApiV2Controller.validateToOverview(reservationId, "en", false, contactForm, new BeanPropertyBindingResult(contactForm, "paymentForm"), null);
    assertEquals(HttpStatus.OK, success.getStatusCode());
    var paymentForm = new PaymentForm();
    paymentForm.setPrivacyPolicyAccepted(true);
    paymentForm.setTermAndConditionsAccepted(true);
    paymentForm.setPaymentProxy(PaymentProxy.OFFLINE);
    paymentForm.setSelectedPaymentMethod(PaymentMethod.BANK_TRANSFER);
    var handleRes = reservationApiV2Controller.confirmOverview(reservationId, "en", paymentForm, new BeanPropertyBindingResult(paymentForm, "paymentForm"), new MockHttpServletRequest(), null);
    assertEquals(HttpStatus.OK, handleRes.getStatusCode());
    return reservationId;
}
Also used : ContactAndTicketsForm(alfio.controller.form.ContactAndTicketsForm) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) PaymentForm(alfio.controller.form.PaymentForm) ReservationForm(alfio.controller.form.ReservationForm) UpdateTicketOwnerForm(alfio.controller.form.UpdateTicketOwnerForm) TicketReservationModification(alfio.model.modification.TicketReservationModification) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Aggregations

ContactAndTicketsForm (alfio.controller.form.ContactAndTicketsForm)3 ReservationForm (alfio.controller.form.ReservationForm)2 UpdateTicketOwnerForm (alfio.controller.form.UpdateTicketOwnerForm)2 ConfigurationManager (alfio.manager.system.ConfigurationManager)2 TicketReservationModification (alfio.model.modification.TicketReservationModification)2 ConfigurationKeys (alfio.model.system.ConfigurationKeys)2 BigDecimal (java.math.BigDecimal)2 List (java.util.List)2 Map (java.util.Map)2 TestConfiguration (alfio.TestConfiguration)1 DataSourceConfiguration (alfio.config.DataSourceConfiguration)1 Initializer (alfio.config.Initializer)1 ControllerConfiguration (alfio.controller.api.ControllerConfiguration)1 ReservationInfo (alfio.controller.api.v2.model.ReservationInfo)1 EventApiV2Controller (alfio.controller.api.v2.user.EventApiV2Controller)1 ReservationApiV2Controller (alfio.controller.api.v2.user.ReservationApiV2Controller)1 PaymentForm (alfio.controller.form.PaymentForm)1 ReservationPriceCalculator (alfio.manager.system.ReservationPriceCalculator)1 UserManager (alfio.manager.user.UserManager)1 alfio.model (alfio.model)1