Search in sources :

Example 1 with Transaction

use of alfio.model.transaction.Transaction in project alf.io by alfio-event.

the class PaymentManager method refund.

public boolean refund(TicketReservation reservation, Event event, Optional<Integer> amount, String username) {
    Transaction transaction = transactionRepository.loadByReservationId(reservation.getId());
    boolean res;
    switch(reservation.getPaymentMethod()) {
        case PAYPAL:
            res = paypalManager.refund(transaction, event, amount);
            break;
        case STRIPE:
            res = stripeManager.refund(transaction, event, amount);
            break;
        default:
            throw new IllegalStateException("Cannot refund ");
    }
    if (res) {
        Map<String, Object> changes = new HashMap<>();
        changes.put("refund", amount.map(Object::toString).orElse("full"));
        changes.put("paymentMethod", reservation.getPaymentMethod().toString());
        auditingRepository.insert(reservation.getId(), userRepository.findIdByUserName(username).orElse(null), event.getId(), Audit.EventType.REFUND, new Date(), Audit.EntityType.RESERVATION, reservation.getId(), Collections.singletonList(changes));
    }
    return res;
}
Also used : Transaction(alfio.model.transaction.Transaction)

Example 2 with Transaction

use of alfio.model.transaction.Transaction in project alf.io by alfio-event.

the class PaymentManager method getInfo.

TransactionAndPaymentInfo getInfo(TicketReservation reservation, Event event) {
    Optional<TransactionAndPaymentInfo> maybeTransaction = transactionRepository.loadOptionalByReservationId(reservation.getId()).map(transaction -> {
        switch(reservation.getPaymentMethod()) {
            case PAYPAL:
                return new TransactionAndPaymentInfo(reservation.getPaymentMethod(), transaction, paypalManager.getInfo(transaction, event).orElse(null));
            case STRIPE:
                return new TransactionAndPaymentInfo(reservation.getPaymentMethod(), transaction, stripeManager.getInfo(transaction, event).orElse(null));
            default:
                return new TransactionAndPaymentInfo(reservation.getPaymentMethod(), transaction, new PaymentInformation(reservation.getPaidAmount(), null, String.valueOf(transaction.getGatewayFee()), String.valueOf(transaction.getPlatformFee())));
        }
    });
    maybeTransaction.ifPresent(info -> {
        try {
            Transaction transaction = info.getTransaction();
            String transactionId = transaction.getTransactionId();
            PaymentInformation paymentInformation = info.getPaymentInformation();
            if (paymentInformation != null) {
                transactionRepository.updateFees(transactionId, reservation.getId(), safeParseLong(paymentInformation.getPlatformFee()), safeParseLong(paymentInformation.getFee()));
            }
        } catch (Exception e) {
            log.warn("cannot update fees", e);
        }
    });
    return maybeTransaction.orElseGet(() -> new TransactionAndPaymentInfo(reservation.getPaymentMethod(), null, new PaymentInformation(reservation.getPaidAmount(), null, null, null)));
}
Also used : Transaction(alfio.model.transaction.Transaction) StripeException(com.stripe.exception.StripeException) PayPalRESTException(com.paypal.base.rest.PayPalRESTException)

Example 3 with Transaction

use of alfio.model.transaction.Transaction in project alf.io by alfio-event.

the class EventApiController method exportLines.

private Stream<String[]> exportLines(String eventName, Principal principal, List<String> fields, Map<Integer, TicketCategory> categoriesMap, ZoneId eventZoneId) {
    var username = principal.getName();
    var eInvoicingEnabled = configurationManager.isItalianEInvoicingEnabled(eventManager.getEventAndOrganizationId(eventName, username));
    return eventManager.findAllConfirmedTicketsForCSV(eventName, username).stream().map(trs -> {
        Ticket t = trs.getTicket();
        var currencyCode = t.getCurrencyCode();
        TicketReservation reservation = trs.getTicketReservation();
        List<String> line = new ArrayList<>();
        if (fields.contains("ID")) {
            line.add(t.getUuid());
        }
        if (fields.contains("Category")) {
            line.add(categoriesMap.get(t.getCategoryId()).getName());
        }
        if (fields.contains("Event")) {
            line.add(eventName);
        }
        if (fields.contains("Status")) {
            line.add(t.getStatus().toString());
        }
        if (fields.contains("OriginalPrice")) {
            line.add(MonetaryUtil.centsToUnit(t.getSrcPriceCts(), currencyCode).toString());
        }
        if (fields.contains("PaidPrice")) {
            line.add(MonetaryUtil.centsToUnit(t.getFinalPriceCts(), currencyCode).toString());
        }
        if (fields.contains("Discount")) {
            line.add(MonetaryUtil.centsToUnit(t.getDiscountCts(), currencyCode).toString());
        }
        if (fields.contains("VAT")) {
            line.add(MonetaryUtil.centsToUnit(t.getVatCts(), currencyCode).toString());
        }
        if (fields.contains("ReservationID")) {
            line.add(t.getTicketsReservationId());
        }
        if (fields.contains("Full Name")) {
            line.add(t.getFullName());
        }
        if (fields.contains("First Name")) {
            line.add(t.getFirstName());
        }
        if (fields.contains("Last Name")) {
            line.add(t.getLastName());
        }
        if (fields.contains("E-Mail")) {
            line.add(t.getEmail());
        }
        if (fields.contains("Locked")) {
            line.add(String.valueOf(t.getLockedAssignment()));
        }
        if (fields.contains("Language")) {
            line.add(String.valueOf(t.getUserLanguage()));
        }
        if (fields.contains("Confirmation")) {
            line.add(reservation.getConfirmationTimestamp().withZoneSameInstant(eventZoneId).toString());
        }
        if (fields.contains("Billing Address")) {
            line.add(reservation.getBillingAddress());
        }
        if (fields.contains("Country Code")) {
            line.add(reservation.getVatCountryCode());
        }
        boolean paymentIdRequested = fields.contains("Payment ID");
        boolean paymentGatewayRequested = fields.contains(PAYMENT_METHOD);
        if ((paymentIdRequested || paymentGatewayRequested)) {
            Optional<Transaction> transaction = trs.getTransaction();
            if (paymentIdRequested) {
                line.add(defaultString(transaction.map(Transaction::getPaymentId).orElse(null), transaction.map(Transaction::getTransactionId).orElse("")));
            }
            if (paymentGatewayRequested) {
                line.add(transaction.map(tr -> tr.getPaymentProxy().name()).orElse(""));
            }
        }
        if (eInvoicingEnabled) {
            var billingDetails = trs.getBillingDetails();
            var optionalInvoicingData = Optional.ofNullable(billingDetails.getInvoicingAdditionalInfo()).map(TicketReservationInvoicingAdditionalInfo::getItalianEInvoicing);
            if (fields.contains(FISCAL_CODE)) {
                line.add(optionalInvoicingData.map(ItalianEInvoicing::getFiscalCode).orElse(""));
            }
            if (fields.contains(REFERENCE_TYPE)) {
                line.add(optionalInvoicingData.map(ItalianEInvoicing::getReferenceTypeAsString).orElse(""));
            }
            if (fields.contains("Addressee Code")) {
                line.add(optionalInvoicingData.map(ItalianEInvoicing::getAddresseeCode).orElse(""));
            }
            if (fields.contains("PEC")) {
                line.add(optionalInvoicingData.map(ItalianEInvoicing::getPec).orElse(""));
            }
        }
        // obviously not optimized
        Map<String, String> additionalValues = ticketFieldRepository.findAllValuesForTicketId(t.getId());
        Predicate<String> contains = FIXED_FIELDS::contains;
        fields.stream().filter(contains.negate()).filter(f -> f.startsWith(CUSTOM_FIELDS_PREFIX)).forEachOrdered(field -> {
            String customFieldName = field.substring(CUSTOM_FIELDS_PREFIX.length());
            line.add(additionalValues.getOrDefault(customFieldName, "").replace("\"", ""));
        });
        return line.toArray(new String[0]);
    });
}
Also used : EventDescriptionRepository(alfio.repository.EventDescriptionRepository) alfio.manager(alfio.manager) PaymentProxy(alfio.model.transaction.PaymentProxy) TemplateProcessor(alfio.controller.support.TemplateProcessor) SneakyThrows(lombok.SneakyThrows) ZonedDateTime(java.time.ZonedDateTime) AlfioMetadata(alfio.model.metadata.AlfioMetadata) StringUtils(org.apache.commons.lang3.StringUtils) BigDecimal(java.math.BigDecimal) Pair(org.apache.commons.lang3.tuple.Pair) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SponsorScanRepository(alfio.repository.SponsorScanRepository) Triple(org.apache.commons.lang3.tuple.Triple) ZipEntry(java.util.zip.ZipEntry) PageAndContent(alfio.controller.api.support.PageAndContent) Organization(alfio.model.user.Organization) Predicate(java.util.function.Predicate) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) DynamicFieldTemplateRepository(alfio.repository.DynamicFieldTemplateRepository) Role(alfio.model.user.Role) Principal(java.security.Principal) Stream(java.util.stream.Stream) alfio.model(alfio.model) StringUtils.defaultString(org.apache.commons.lang3.StringUtils.defaultString) LocalDate(java.time.LocalDate) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) alfio.model.modification(alfio.model.modification) ValidationResult(alfio.model.result.ValidationResult) ZipOutputStream(java.util.zip.ZipOutputStream) Transaction(alfio.model.transaction.Transaction) DataAccessException(org.springframework.dao.DataAccessException) Errors(org.springframework.validation.Errors) java.util(java.util) TicketHelper(alfio.controller.api.support.TicketHelper) ConfigurationLevel(alfio.manager.system.ConfigurationLevel) CsvException(com.opencsv.exceptions.CsvException) Getter(lombok.Getter) EventListItem(alfio.controller.api.support.EventListItem) CSVReader(com.opencsv.CSVReader) ConfigurationManager(alfio.manager.system.ConfigurationManager) AlfioScriptingException(alfio.extension.exception.AlfioScriptingException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) alfio.util(alfio.util) CollectionUtils(org.apache.commons.collections4.CollectionUtils) TicketFieldRepository(alfio.repository.TicketFieldRepository) HttpServletRequest(javax.servlet.http.HttpServletRequest) StreamUtils(org.springframework.util.StreamUtils) OutputStream(java.io.OutputStream) ItalianEInvoicing(alfio.model.TicketReservationInvoicingAdditionalInfo.ItalianEInvoicing) UTF_8(java.nio.charset.StandardCharsets.UTF_8) HttpServletResponse(javax.servlet.http.HttpServletResponse) User(alfio.model.user.User) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Validator(alfio.util.Validator) HttpStatus(org.springframework.http.HttpStatus) Collectors.toList(java.util.stream.Collectors.toList) Validate(org.apache.commons.lang3.Validate) ChronoUnit(java.time.temporal.ChronoUnit) ExtensionCapability(alfio.manager.support.extension.ExtensionCapability) UserManager(alfio.manager.user.UserManager) DateTimeFormatter(java.time.format.DateTimeFormatter) Data(lombok.Data) Log4j2(lombok.extern.log4j.Log4j2) ResponseEntity(org.springframework.http.ResponseEntity) Wrappers.optionally(alfio.util.Wrappers.optionally) I18nManager(alfio.manager.i18n.I18nManager) AllArgsConstructor(lombok.AllArgsConstructor) ConfigurationKeys(alfio.model.system.ConfigurationKeys) StringUtils.defaultString(org.apache.commons.lang3.StringUtils.defaultString) Transaction(alfio.model.transaction.Transaction) ItalianEInvoicing(alfio.model.TicketReservationInvoicingAdditionalInfo.ItalianEInvoicing)

Example 4 with Transaction

use of alfio.model.transaction.Transaction in project alf.io by alfio-event.

the class BaseStripeManager method refund.

// https://stripe.com/docs/api#create_refund
boolean refund(Transaction transaction, PurchaseContext purchaseContext, Integer amountToRefund) {
    Optional<Integer> amount = Optional.ofNullable(amountToRefund);
    String chargeId = transaction.getTransactionId();
    try {
        String amountOrFull = amount.map(p -> MonetaryUtil.formatCents(p, transaction.getCurrency())).orElse("full");
        log.info("Stripe: trying to do a refund for payment {} with amount: {}", chargeId, amountOrFull);
        Map<String, Object> params = new HashMap<>();
        params.put("charge", chargeId);
        amount.ifPresent(a -> params.put("amount", a));
        if (transaction.getPlatformFee() > 0 && isConnectEnabled(new PaymentContext(purchaseContext))) {
            params.put("refund_application_fee", true);
        }
        Optional<RequestOptions> requestOptionsOptional = options(purchaseContext);
        if (requestOptionsOptional.isPresent()) {
            RequestOptions options = requestOptionsOptional.get();
            Refund r = Refund.create(params, options);
            boolean pending = PENDING.equals(r.getStatus());
            if (SUCCEEDED.equals(r.getStatus()) || pending) {
                log.info("Stripe: refund for payment {} {} for amount: {}", chargeId, pending ? "registered" : "executed with success", amountOrFull);
                return true;
            } else {
                log.warn("Stripe: was not able to refund payment with id {}, returned status is not 'succeded' but {}", chargeId, r.getStatus());
                return false;
            }
        }
        return false;
    } catch (StripeException e) {
        log.warn("Stripe: was not able to refund payment with id " + chargeId, e);
        return false;
    }
}
Also used : Transaction(alfio.model.transaction.Transaction) RequestOptions(com.stripe.net.RequestOptions) java.util(java.util) PaymentProxy(alfio.model.transaction.PaymentProxy) PaymentResult(alfio.manager.support.PaymentResult) PurchaseContext(alfio.model.PurchaseContext) PurchaseContextType(alfio.model.PurchaseContext.PurchaseContextType) UnaryOperator(java.util.function.UnaryOperator) ConfigurationManager(alfio.manager.system.ConfigurationManager) PaymentInformation(alfio.model.PaymentInformation) Charge(com.stripe.model.Charge) Profiles(org.springframework.core.env.Profiles) Configurable(alfio.model.Configurable) Refund(com.stripe.model.Refund) TicketRepository(alfio.repository.TicketRepository) Predicate(java.util.function.Predicate) FeeCalculator(alfio.manager.support.FeeCalculator) PaymentMethod(alfio.model.transaction.PaymentMethod) Stripe(com.stripe.Stripe) ErrorsCode(alfio.util.ErrorsCode) ConfigurationRepository(alfio.repository.system.ConfigurationRepository) PaymentContext(alfio.model.transaction.PaymentContext) MonetaryUtil(alfio.util.MonetaryUtil) Environment(org.springframework.core.env.Environment) UserManager(alfio.manager.user.UserManager) Log4j2(lombok.extern.log4j.Log4j2) ConfigurationPathLevel(alfio.model.system.ConfigurationPathLevel) com.stripe.exception(com.stripe.exception) AllArgsConstructor(lombok.AllArgsConstructor) ConfigurationKeys(alfio.model.system.ConfigurationKeys) BalanceTransaction(com.stripe.model.BalanceTransaction) Webhook(com.stripe.net.Webhook) RequestOptions(com.stripe.net.RequestOptions) PaymentContext(alfio.model.transaction.PaymentContext) Refund(com.stripe.model.Refund)

Aggregations

Transaction (alfio.model.transaction.Transaction)4 ConfigurationManager (alfio.manager.system.ConfigurationManager)2 UserManager (alfio.manager.user.UserManager)2 ConfigurationKeys (alfio.model.system.ConfigurationKeys)2 PaymentProxy (alfio.model.transaction.PaymentProxy)2 EventListItem (alfio.controller.api.support.EventListItem)1 PageAndContent (alfio.controller.api.support.PageAndContent)1 TicketHelper (alfio.controller.api.support.TicketHelper)1 TemplateProcessor (alfio.controller.support.TemplateProcessor)1 AlfioScriptingException (alfio.extension.exception.AlfioScriptingException)1 alfio.manager (alfio.manager)1 I18nManager (alfio.manager.i18n.I18nManager)1 FeeCalculator (alfio.manager.support.FeeCalculator)1 PaymentResult (alfio.manager.support.PaymentResult)1 ExtensionCapability (alfio.manager.support.extension.ExtensionCapability)1 ConfigurationLevel (alfio.manager.system.ConfigurationLevel)1 alfio.model (alfio.model)1 Configurable (alfio.model.Configurable)1 PaymentInformation (alfio.model.PaymentInformation)1 PurchaseContext (alfio.model.PurchaseContext)1