Search in sources :

Example 6 with Organization

use of alfio.model.user.Organization in project alf.io by alfio-event.

the class NotificationManager method sendTicketByEmail.

public void sendTicketByEmail(Ticket ticket, Event event, Locale locale, PartialTicketTextGenerator textBuilder, TicketReservation reservation, TicketCategory ticketCategory) throws IOException {
    Organization organization = organizationRepository.getById(event.getOrganizationId());
    List<Mailer.Attachment> attachments = new ArrayList<>();
    attachments.add(CustomMessageManager.generateTicketAttachment(ticket, reservation, ticketCategory, organization));
    String encodedAttachments = encodeAttachments(attachments.toArray(new Mailer.Attachment[attachments.size()]));
    String subject = messageSource.getMessage("ticket-email-subject", new Object[] { event.getDisplayName() }, locale);
    String text = textBuilder.generate(ticket);
    String checksum = calculateChecksum(ticket.getEmail(), encodedAttachments, subject, text);
    String recipient = ticket.getEmail();
    // TODO handle HTML
    tx.execute(status -> emailMessageRepository.insert(event.getId(), recipient, null, subject, text, encodedAttachments, checksum, ZonedDateTime.now(UTC)));
}
Also used : Organization(alfio.model.user.Organization)

Example 7 with Organization

use of alfio.model.user.Organization in project alf.io by alfio-event.

the class PassBookManager method getPassBook.

byte[] getPassBook(Map<String, String> model) {
    try {
        Ticket ticket = Json.fromJson(model.get("ticket"), Ticket.class);
        int eventId = ticket.getEventId();
        Event event = eventRepository.findById(eventId);
        Organization organization = organizationRepository.getById(Integer.valueOf(model.get("organizationId"), 10));
        int organizationId = organization.getId();
        Function<ConfigurationKeys, Configuration.ConfigurationPathKey> partial = Configuration.from(organizationId, eventId);
        Map<ConfigurationKeys, Optional<String>> pbookConf = configurationManager.getStringConfigValueFrom(partial.apply(ConfigurationKeys.PASSBOOK_TYPE_IDENTIFIER), partial.apply(ConfigurationKeys.PASSBOOK_KEYSTORE), partial.apply(ConfigurationKeys.PASSBOOK_KEYSTORE_PASSWORD), partial.apply(ConfigurationKeys.PASSBOOK_TEAM_IDENTIFIER));
        // check if all are set
        if (pbookConf.values().stream().anyMatch(o -> !o.isPresent())) {
            log.trace("Cannot generate Passbook. Missing configuration keys, check if all 4 are presents");
            return null;
        }
        // 
        String teamIdentifier = pbookConf.get(ConfigurationKeys.PASSBOOK_TEAM_IDENTIFIER).orElseThrow(IllegalStateException::new);
        String typeIdentifier = pbookConf.get(ConfigurationKeys.PASSBOOK_TYPE_IDENTIFIER).orElseThrow(IllegalStateException::new);
        byte[] keystoreRaw = Base64.getDecoder().decode(pbookConf.get(ConfigurationKeys.PASSBOOK_KEYSTORE).orElseThrow(IllegalStateException::new));
        String keystorePwd = pbookConf.get(ConfigurationKeys.PASSBOOK_KEYSTORE_PASSWORD).orElseThrow(IllegalStateException::new);
        // ugly, find an alternative way?
        Optional<KeyStore> ksJks = loadKeyStore(keystoreRaw);
        if (ksJks.isPresent()) {
            return buildPass(ticket, event, organization, teamIdentifier, typeIdentifier, keystorePwd, ksJks.get());
        } else {
            log.warn("Cannot generate Passbook. Not able to load keystore. Please check configuration.");
            return null;
        }
    } catch (Exception ex) {
        log.warn("Got Exception while generating Passbook. Please check configuration.", ex);
        return null;
    }
}
Also used : Ticket(alfio.model.Ticket) ConfigurationKeys(alfio.model.system.ConfigurationKeys) Organization(alfio.model.user.Organization) KeyStore(java.security.KeyStore) PassSigningException(com.ryantenney.passkit4j.sign.PassSigningException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) Event(alfio.model.Event)

Example 8 with Organization

use of alfio.model.user.Organization in project alf.io by alfio-event.

the class TicketReservationManager method sendReminderForOfflinePaymentsToEventManagers.

// called each hour
void sendReminderForOfflinePaymentsToEventManagers() {
    eventRepository.findAllActives(ZonedDateTime.now(Clock.systemUTC())).stream().filter(event -> {
        ZonedDateTime dateTimeForEvent = ZonedDateTime.now(event.getZoneId());
        // only for the events at 5:00 local time
        return dateTimeForEvent.truncatedTo(ChronoUnit.HOURS).getHour() == 5;
    }).forEachOrdered(event -> {
        ZonedDateTime dateTimeForEvent = ZonedDateTime.now(event.getZoneId()).truncatedTo(ChronoUnit.DAYS).plusDays(1);
        List<TicketReservationInfo> reservations = ticketReservationRepository.findAllOfflinePaymentReservationWithExpirationBefore(dateTimeForEvent, event.getId());
        log.info("for event {} there are {} pending offline payments to handle", event.getId(), reservations.size());
        if (!reservations.isEmpty()) {
            Organization organization = organizationRepository.getById(event.getOrganizationId());
            List<String> cc = notificationManager.getCCForEventOrganizer(event);
            String subject = String.format("There are %d pending offline payments that will expire in event: %s", reservations.size(), event.getDisplayName());
            String baseUrl = configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), BASE_URL));
            Map<String, Object> model = TemplateResource.prepareModelForOfflineReservationExpiringEmailForOrganizer(event, reservations, baseUrl);
            notificationManager.sendSimpleEmail(event, organization.getEmail(), cc, subject, () -> templateManager.renderTemplate(event, TemplateResource.OFFLINE_RESERVATION_EXPIRING_EMAIL_FOR_ORGANIZER, model, Locale.ENGLISH));
            extensionManager.handleOfflineReservationsWillExpire(event, reservations);
        }
    });
}
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) Organization(alfio.model.user.Organization) ZonedDateTime(java.time.ZonedDateTime)

Example 9 with Organization

use of alfio.model.user.Organization in project alf.io by alfio-event.

the class TicketReservationManager method releaseTicket.

public void releaseTicket(Event event, TicketReservation ticketReservation, final Ticket ticket) {
    TicketCategory category = ticketCategoryRepository.getByIdAndActive(ticket.getCategoryId(), event.getId());
    if (!CategoryEvaluator.isTicketCancellationAvailable(ticketCategoryRepository, ticket)) {
        throw new IllegalStateException("Cannot release reserved tickets");
    }
    String reservationId = ticketReservation.getId();
    // #365 - reset UUID when releasing a ticket
    int result = ticketRepository.releaseTicket(reservationId, UUID.randomUUID().toString(), event.getId(), ticket.getId());
    Validate.isTrue(result == 1, String.format("Expected 1 row to be updated, got %d", result));
    if (category.isAccessRestricted() || !category.isBounded()) {
        ticketRepository.unbindTicketsFromCategory(event.getId(), category.getId(), singletonList(ticket.getId()));
    }
    Organization organization = organizationRepository.getById(event.getOrganizationId());
    Map<String, Object> model = TemplateResource.buildModelForTicketHasBeenCancelled(organization, event, ticket);
    Locale locale = Locale.forLanguageTag(Optional.ofNullable(ticket.getUserLanguage()).orElse("en"));
    notificationManager.sendSimpleEmail(event, ticket.getEmail(), messageSource.getMessage("email-ticket-released.subject", new Object[] { event.getDisplayName() }, locale), () -> templateManager.renderTemplate(event, TemplateResource.TICKET_HAS_BEEN_CANCELLED, model, locale));
    String ticketCategoryDescription = ticketCategoryDescriptionRepository.findByTicketCategoryIdAndLocale(category.getId(), ticket.getUserLanguage()).orElse("");
    List<AdditionalServiceItem> additionalServiceItems = additionalServiceItemRepository.findByReservationUuid(reservationId);
    Map<String, Object> adminModel = TemplateResource.buildModelForTicketHasBeenCancelledAdmin(organization, event, ticket, ticketCategoryDescription, additionalServiceItems, asi -> additionalServiceTextRepository.findByLocaleAndType(asi.getAdditionalServiceId(), locale.getLanguage(), AdditionalServiceText.TextType.TITLE));
    notificationManager.sendSimpleEmail(event, organization.getEmail(), messageSource.getMessage("email-ticket-released.admin.subject", new Object[] { ticket.getId(), event.getDisplayName() }, locale), () -> templateManager.renderTemplate(event, TemplateResource.TICKET_HAS_BEEN_CANCELLED_ADMIN, adminModel, locale));
    int deletedValues = ticketFieldRepository.deleteAllValuesForTicket(ticket.getId());
    log.debug("deleting {} field values for ticket {}", deletedValues, ticket.getId());
    auditingRepository.insert(reservationId, null, event.getId(), Audit.EventType.CANCEL_TICKET, new Date(), Audit.EntityType.TICKET, Integer.toString(ticket.getId()));
    if (ticketRepository.countTicketsInReservation(reservationId) == 0 && !transactionRepository.loadOptionalByReservationId(reservationId).isPresent()) {
        deleteReservation(event, reservationId, false);
        auditingRepository.insert(reservationId, null, event.getId(), Audit.EventType.CANCEL_RESERVATION, new Date(), Audit.EntityType.RESERVATION, reservationId);
    } else {
        extensionManager.handleTicketCancelledForEvent(event, Collections.singletonList(ticket.getUuid()));
    }
}
Also used : Organization(alfio.model.user.Organization)

Example 10 with Organization

use of alfio.model.user.Organization in project alf.io by alfio-event.

the class TicketReservationManager method markExpiredInPaymentReservationAsStuck.

/**
 * Finds all the reservations that are "stuck" in payment status.
 * This could happen when there is an internal error after a successful credit card charge.
 *
 * @param expirationDate expiration date
 */
public void markExpiredInPaymentReservationAsStuck(Date expirationDate) {
    List<String> stuckReservations = ticketReservationRepository.findStuckReservations(expirationDate);
    if (!stuckReservations.isEmpty()) {
        ticketReservationRepository.updateReservationsStatus(stuckReservations, TicketReservationStatus.STUCK.name());
        Map<Integer, List<ReservationIdAndEventId>> reservationsGroupedByEvent = ticketReservationRepository.getReservationIdAndEventId(stuckReservations).stream().collect(Collectors.groupingBy(ReservationIdAndEventId::getEventId));
        reservationsGroupedByEvent.forEach((eventId, reservationIds) -> {
            Event event = eventRepository.findById(eventId);
            Organization organization = organizationRepository.getById(event.getOrganizationId());
            notificationManager.sendSimpleEmail(event, organization.getEmail(), STUCK_TICKETS_SUBJECT, () -> String.format(STUCK_TICKETS_MSG, event.getShortName()));
            extensionManager.handleStuckReservations(event, reservationIds.stream().map(ReservationIdAndEventId::getId).collect(toList()));
        });
    }
}
Also used : Organization(alfio.model.user.Organization) Collections.singletonList(java.util.Collections.singletonList) Arrays.asList(java.util.Arrays.asList)

Aggregations

Organization (alfio.model.user.Organization)30 Event (alfio.model.Event)13 TicketCategory (alfio.model.TicketCategory)7 Ticket (alfio.model.Ticket)6 Triple (org.apache.commons.lang3.tuple.Triple)6 TicketReservation (alfio.model.TicketReservation)4 java.util (java.util)4 Collectors (java.util.stream.Collectors)4 Log4j2 (lombok.extern.log4j.Log4j2)4 Component (org.springframework.stereotype.Component)4 DateTimeModification (alfio.model.modification.DateTimeModification)3 LocationDescriptor (alfio.model.modification.support.LocationDescriptor)3 ZonedDateTime (java.time.ZonedDateTime)3 Collections.singletonList (java.util.Collections.singletonList)3 Transactional (org.springframework.transaction.annotation.Transactional)3 EventManager (alfio.manager.EventManager)2 NotificationManager (alfio.manager.NotificationManager)2 TicketReservationManager (alfio.manager.TicketReservationManager)2 Mailer (alfio.manager.system.Mailer)2 alfio.model (alfio.model)2