Search in sources :

Example 1 with VatStatus

use of alfio.model.PriceContainer.VatStatus in project alf.io by alfio-event.

the class DataMigrator method collectASItemMigrationData.

private List<Pair<String, MapSqlParameterSource>> collectASItemMigrationData(String srcPriceCtsParam, final boolean eventVatIncluded, final BigDecimal vatPercentage, final String currencyCode, Map<String, Integer> eventIdParam) {
    return jdbc.queryForList("select ai.id as id, ai.paid_price_cts as paid_price_cts, a.vat_type as vat_type from additional_service_item ai, additional_service a where ai.paid_price_cts > 0 and ai.src_price_cts = 0 and ai.event_id_fk = :eventId", eventIdParam).stream().map(item -> {
        int oldPrice = (int) item.get("paid_price_cts");
        AdditionalService.VatType vatType = AdditionalService.VatType.valueOf((String) item.get("vat_type"));
        return Pair.of((Integer) item.get("id"), new PriceContainer() {

            @Override
            public int getSrcPriceCts() {
                return eventVatIncluded ? MonetaryUtil.addVAT(oldPrice, vatPercentage) : oldPrice;
            }

            @Override
            public String getCurrencyCode() {
                return currencyCode;
            }

            @Override
            public Optional<BigDecimal> getOptionalVatPercentage() {
                return Optional.of(vatPercentage);
            }

            @Override
            public VatStatus getVatStatus() {
                if (vatType == AdditionalService.VatType.INHERITED) {
                    return eventVatIncluded ? INCLUDED : NOT_INCLUDED;
                }
                // no need to check for other VatTypes. At the time of writing VAT override strategy has not yet been implemented.
                return NONE;
            }
        });
    }).map(p -> {
        PriceContainer priceContainer = p.getValue();
        return Pair.of("additional_service_item", new MapSqlParameterSource(srcPriceCtsParam, priceContainer.getSrcPriceCts()).addValue("finalPriceCts", MonetaryUtil.unitToCents(priceContainer.getFinalPrice())).addValue("vatCts", MonetaryUtil.unitToCents(priceContainer.getVAT())).addValue("additionalServiceItemId", p.getKey()));
    }).collect(toList());
}
Also used : EmptySqlParameterSource(org.springframework.jdbc.core.namedparam.EmptySqlParameterSource) java.util(java.util) TicketCategoryRepository(alfio.repository.TicketCategoryRepository) PaymentProxy(alfio.model.transaction.PaymentProxy) TransactionDefinition(org.springframework.transaction.TransactionDefinition) ZonedDateTime(java.time.ZonedDateTime) NamedParameterJdbcTemplate(org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate) Autowired(org.springframework.beans.factory.annotation.Autowired) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) EventMigration(alfio.model.system.EventMigration) Value(org.springframework.beans.factory.annotation.Value) BigDecimal(java.math.BigDecimal) Matcher(java.util.regex.Matcher) Pair(org.apache.commons.lang3.tuple.Pair) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) VatStatus(alfio.model.PriceContainer.VatStatus) EventMigrationRepository(alfio.repository.system.EventMigrationRepository) EventRepository(alfio.repository.EventRepository) Collectors(java.util.stream.Collectors) ConfigurationRepository(alfio.repository.system.ConfigurationRepository) Component(org.springframework.stereotype.Component) Validate(org.apache.commons.lang3.Validate) MonetaryUtil(alfio.util.MonetaryUtil) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) alfio.model(alfio.model) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Log4j2(lombok.extern.log4j.Log4j2) Pattern(java.util.regex.Pattern) ConfigurationKeys(alfio.model.system.ConfigurationKeys) RESET_TICKET(alfio.repository.TicketRepository.RESET_TICKET) OptionalWrapper.optionally(alfio.util.OptionalWrapper.optionally) Transactional(org.springframework.transaction.annotation.Transactional) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) VatStatus(alfio.model.PriceContainer.VatStatus)

Example 2 with VatStatus

use of alfio.model.PriceContainer.VatStatus in project alf.io by alfio-event.

the class ReservationApiController method validateEUVat.

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/vat-validation", method = RequestMethod.POST)
@Transactional
public ResponseEntity<VatDetail> validateEUVat(@PathVariable("eventName") String eventName, @PathVariable("reservationId") String reservationId, PaymentForm paymentForm, Locale locale, HttpServletRequest request) {
    String country = paymentForm.getVatCountryCode();
    Optional<Triple<Event, TicketReservation, VatDetail>> vatDetail = eventRepository.findOptionalByShortName(eventName).flatMap(e -> ticketReservationRepository.findOptionalReservationById(reservationId).map(r -> Pair.of(e, r))).filter(e -> EnumSet.of(INCLUDED, NOT_INCLUDED).contains(e.getKey().getVatStatus())).filter(e -> vatChecker.isVatCheckingEnabledFor(e.getKey().getOrganizationId())).flatMap(e -> vatChecker.checkVat(paymentForm.getVatNr(), country, e.getKey().getOrganizationId()).map(vd -> Triple.of(e.getLeft(), e.getRight(), vd)));
    vatDetail.filter(t -> t.getRight().isValid()).ifPresent(t -> {
        VatDetail vd = t.getRight();
        String billingAddress = vd.getName() + "\n" + vd.getAddress();
        PriceContainer.VatStatus vatStatus = determineVatStatus(t.getLeft().getVatStatus(), t.getRight().isVatExempt());
        ticketReservationRepository.updateBillingData(vatStatus, vd.getVatNr(), country, paymentForm.isInvoiceRequested(), reservationId);
        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, t.getLeft(), Locale.forLanguageTag(t.getMiddle().getUserLanguage()));
        ticketReservationRepository.addReservationInvoiceOrReceiptModel(reservationId, Json.toJson(orderSummary));
        ticketReservationRepository.updateTicketReservation(reservationId, t.getMiddle().getStatus().name(), paymentForm.getEmail(), paymentForm.getFullName(), paymentForm.getFirstName(), paymentForm.getLastName(), locale.getLanguage(), billingAddress, null, Optional.ofNullable(paymentForm.getPaymentMethod()).map(PaymentProxy::name).orElse(null));
        paymentForm.getTickets().forEach((ticketId, owner) -> {
            if (isNotEmpty(owner.getEmail()) && ((isNotEmpty(owner.getFirstName()) && isNotEmpty(owner.getLastName())) || isNotEmpty(owner.getFullName()))) {
                ticketHelper.preAssignTicket(eventName, reservationId, ticketId, owner, Optional.empty(), request, (tr) -> {
                }, Optional.empty());
            }
        });
    });
    return vatDetail.map(Triple::getRight).map(vd -> {
        if (vd.isValid()) {
            return ResponseEntity.ok(vd);
        } else {
            return new ResponseEntity<VatDetail>(HttpStatus.BAD_REQUEST);
        }
    }).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
Also used : Triple(org.apache.commons.lang3.tuple.Triple) ValidationResult(alfio.model.result.ValidationResult) java.util(java.util) TicketHelper(alfio.controller.api.support.TicketHelper) PaymentProxy(alfio.model.transaction.PaymentProxy) TicketReservationRepository(alfio.repository.TicketReservationRepository) PaymentForm(alfio.controller.form.PaymentForm) BindingResult(org.springframework.validation.BindingResult) StringUtils.isNotEmpty(org.apache.commons.lang3.StringUtils.isNotEmpty) RequestContextUtils(org.springframework.web.servlet.support.RequestContextUtils) Json(alfio.util.Json) Model(org.springframework.ui.Model) HttpServletRequest(javax.servlet.http.HttpServletRequest) Pair(org.apache.commons.lang3.tuple.Pair) EuVatChecker(alfio.manager.EuVatChecker) UserDetails(org.springframework.security.core.userdetails.UserDetails) Triple(org.apache.commons.lang3.tuple.Triple) VatStatus(alfio.model.PriceContainer.VatStatus) TemplateManager(alfio.util.TemplateManager) UpdateTicketOwnerForm(alfio.controller.form.UpdateTicketOwnerForm) EventRepository(alfio.repository.EventRepository) Collectors(java.util.stream.Collectors) HttpStatus(org.springframework.http.HttpStatus) TicketReservationManager(alfio.manager.TicketReservationManager) alfio.model(alfio.model) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) ResponseEntity(org.springframework.http.ResponseEntity) I18nManager(alfio.manager.i18n.I18nManager) AllArgsConstructor(lombok.AllArgsConstructor) Authentication(org.springframework.security.core.Authentication) Transactional(org.springframework.transaction.annotation.Transactional) PaymentProxy(alfio.model.transaction.PaymentProxy) VatStatus(alfio.model.PriceContainer.VatStatus) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with VatStatus

use of alfio.model.PriceContainer.VatStatus in project alf.io by alfio-event.

the class DataMigrator method migratePrices.

private void migratePrices(final int eventId) {
    final Map<String, Integer> eventIdParam = Collections.singletonMap("eventId", eventId);
    final String srcPriceCtsParam = "srcPriceCts";
    Map<String, List<MapSqlParameterSource>> migrationData = jdbc.queryForList("select * from event where type = :type and id = :eventId and regular_price_cts > 0", new MapSqlParameterSource("type", Event.EventType.INTERNAL.name()).addValue("eventId", eventId)).stream().flatMap(event -> {
        // fill the event prices
        boolean eventVatIncluded = (boolean) event.get("vat_included");
        BigDecimal vatPercentage = Optional.ofNullable((BigDecimal) event.get("vat")).orElse(BigDecimal.ZERO);
        int price = (int) event.get("regular_price_cts");
        String currencyCode = (String) event.get("currency");
        int eventSrcPrice = eventVatIncluded ? MonetaryUtil.addVAT(price, vatPercentage) : price;
        List<Pair<String, MapSqlParameterSource>> modifications = new ArrayList<>();
        if (((int) event.get("src_price_cts")) == 0) {
            modifications.add(Pair.of("event", new MapSqlParameterSource(srcPriceCtsParam, eventSrcPrice).addValue("vatStatus", eventVatIncluded ? INCLUDED.name() : NOT_INCLUDED.name()).addValue("eventId", eventId)));
        }
        // ticket categories
        modifications.addAll(collectTicketCategoryMigrationData(srcPriceCtsParam, eventVatIncluded, vatPercentage, eventIdParam));
        // tickets
        modifications.addAll(collectTicketMigrationData(srcPriceCtsParam, eventVatIncluded, vatPercentage, currencyCode, eventId, eventIdParam));
        // additional_service
        modifications.addAll(collectASMigrationData(srcPriceCtsParam, eventVatIncluded, vatPercentage, eventIdParam));
        // additional_service_item
        modifications.addAll(collectASItemMigrationData(srcPriceCtsParam, eventVatIncluded, vatPercentage, currencyCode, eventIdParam));
        log.debug("Price migration: got {} modifications for event {}", modifications.size(), event.get("short_name"));
        return modifications.stream();
    }).collect(groupingBy(Pair::getKey, mapping(Pair::getValue, toList())));
    if (migrationData.size() > 0) {
        log.debug("Price migration: got modifications for: {}", migrationData.keySet());
        PRICE_UPDATE_BY_KEY.entrySet().stream().filter(e -> migrationData.containsKey(e.getKey())).map(e -> Pair.of(e, migrationData.get(e.getKey()))).forEach(p -> {
            Map.Entry<String, String> entry = p.getLeft();
            log.debug("migrating {} prices...", entry.getKey());
            performPriceMigration(entry.getValue(), p.getRight(), jdbc);
        });
    }
}
Also used : EmptySqlParameterSource(org.springframework.jdbc.core.namedparam.EmptySqlParameterSource) java.util(java.util) TicketCategoryRepository(alfio.repository.TicketCategoryRepository) PaymentProxy(alfio.model.transaction.PaymentProxy) TransactionDefinition(org.springframework.transaction.TransactionDefinition) ZonedDateTime(java.time.ZonedDateTime) NamedParameterJdbcTemplate(org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate) Autowired(org.springframework.beans.factory.annotation.Autowired) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) EventMigration(alfio.model.system.EventMigration) Value(org.springframework.beans.factory.annotation.Value) BigDecimal(java.math.BigDecimal) Matcher(java.util.regex.Matcher) Pair(org.apache.commons.lang3.tuple.Pair) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) VatStatus(alfio.model.PriceContainer.VatStatus) EventMigrationRepository(alfio.repository.system.EventMigrationRepository) EventRepository(alfio.repository.EventRepository) Collectors(java.util.stream.Collectors) ConfigurationRepository(alfio.repository.system.ConfigurationRepository) Component(org.springframework.stereotype.Component) Validate(org.apache.commons.lang3.Validate) MonetaryUtil(alfio.util.MonetaryUtil) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) alfio.model(alfio.model) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Log4j2(lombok.extern.log4j.Log4j2) Pattern(java.util.regex.Pattern) ConfigurationKeys(alfio.model.system.ConfigurationKeys) RESET_TICKET(alfio.repository.TicketRepository.RESET_TICKET) OptionalWrapper.optionally(alfio.util.OptionalWrapper.optionally) Transactional(org.springframework.transaction.annotation.Transactional) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) BigDecimal(java.math.BigDecimal) Pair(org.apache.commons.lang3.tuple.Pair)

Aggregations

alfio.model (alfio.model)3 VatStatus (alfio.model.PriceContainer.VatStatus)3 PaymentProxy (alfio.model.transaction.PaymentProxy)3 EventRepository (alfio.repository.EventRepository)3 java.util (java.util)3 Collectors (java.util.stream.Collectors)3 Pair (org.apache.commons.lang3.tuple.Pair)3 Transactional (org.springframework.transaction.annotation.Transactional)3 ConfigurationKeys (alfio.model.system.ConfigurationKeys)2 EventMigration (alfio.model.system.EventMigration)2 TicketCategoryRepository (alfio.repository.TicketCategoryRepository)2 RESET_TICKET (alfio.repository.TicketRepository.RESET_TICKET)2 ConfigurationRepository (alfio.repository.system.ConfigurationRepository)2 EventMigrationRepository (alfio.repository.system.EventMigrationRepository)2 MonetaryUtil (alfio.util.MonetaryUtil)2 OptionalWrapper.optionally (alfio.util.OptionalWrapper.optionally)2 BigDecimal (java.math.BigDecimal)2 ZonedDateTime (java.time.ZonedDateTime)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2