Ejemplo n.º 1
0
 def test_should_create_attendee_forms(self):
     """Method to test custom forms for attendees of an event."""
     with app.test_request_context():
         event = EventFactoryBasic()
         save_to_db(event)
         create_custom_forms_for_attendees(event)
         self.assertEqual(get_count(CustomForms.query), 3)
Ejemplo n.º 2
0
    def charge_stripe_order_payment(order, token_id):
        order.stripe_token = token_id
        save_to_db(order)
        charge = StripePaymentsManager.capture_payment(order)

        if charge:
            order.paid_via = 'stripe'
            order.payment_mode = charge.source.object
            order.brand = charge.source.brand
            order.exp_month = charge.source.exp_month
            order.exp_year = charge.source.exp_year
            order.last4 = charge.source.last4
            order.transaction_id = charge.id
            order.status = 'completed'
            order.completed_at = datetime.utcnow()
            save_to_db(order)

            invoice_id = order.get_invoice_number()
            order_url = make_frontend_url(path="/{identifier}/view/".format(identifier=order.identifier))
            # send_email_for_after_purchase(order.user.email, invoice_id, order_url, order.event.name,
                                          # order.event.organizer_name)
            # send_notif_for_after_purchase(order.user, invoice_id, order_url)

            return True, order
        else:
            return False, 'Error'
Ejemplo n.º 3
0
    def charge_paypal_order_payment(order):
        payment_details = PayPalPaymentsManager.get_approved_payment_details(order)
        if 'PAYERID' in payment_details:
            capture_result = PayPalPaymentsManager.capture_payment(order, payment_details['PAYERID'])
            if capture_result['ACK'] == 'Success':
                order.paid_via = 'paypal'
                order.status = 'completed'
                order.transaction_id = capture_result['PAYMENTINFO_0_TRANSACTIONID']
                order.completed_at = datetime.utcnow()
                save_to_db(order)

                invoice_id = order.get_invoice_number()
                order_url = make_frontend_url(path="/{identifier}/view/".format(identifier=order.identifier))

                # trigger_after_purchase_notifications(order.user.email, order.event_id, order.event, invoice_id,
                # order_url)
                # send_email_for_after_purchase(order.user.email, invoice_id, order_url, order.event.name,
                # order.event.organizer_name)
                # send_notif_for_after_purchase(order.user, invoice_id, order_url)

                return True, order
            else:
                return False, capture_result['L_SHORTMESSAGE0']
        else:
            return False, 'Payer ID missing. Payment flow tampered.'
Ejemplo n.º 4
0
def change_password():
    old_password = request.json['data']['old-password']
    new_password = request.json['data']['new-password']

    try:
        user = User.query.filter_by(id=current_user.id).one()
    except NoResultFound:
        return abort(
            make_response(jsonify(error="User not found"), 404)
        )
    else:
        if user.is_correct_password(old_password):

            user.password = new_password
            save_to_db(user)
            send_email_with_action(user, PASSWORD_CHANGE,
                                   app_name=get_settings()['app_name'])
            send_notification_with_action(user, PASSWORD_CHANGE_NOTIF,
                                   app_name=get_settings()['app_name'])
        else:
            return abort(
                make_response(jsonify(error="Wrong Password"), 400)
            )

    return jsonify({
        "id": user.id,
        "email": user.email,
        "name": user.fullname if user.fullname else None,
        "password-changed": True
    })
Ejemplo n.º 5
0
def export_pentabarf_task(self, event_id, temp=True):
    event = safe_query(db, Event, 'id', event_id, 'event_id')

    try:
        if temp:
            filedir = os.path.join(current_app.config.get('BASE_DIR'), 'static/uploads/temp/' + event_id + '/')
        else:
            filedir = os.path.join(current_app.config.get('BASE_DIR'), 'static/uploads/' + event_id + '/')

        if not os.path.isdir(filedir):
            os.makedirs(filedir)
        filename = "pentabarf.xml"
        file_path = os.path.join(filedir, filename)
        with open(file_path, "w") as temp_file:
            temp_file.write(str(PentabarfExporter.export(event_id), 'utf-8'))
        pentabarf_file = UploadedFile(file_path=file_path, filename=filename)
        if temp:
            pentabarf_url = upload(pentabarf_file, UPLOAD_PATHS['exports-temp']['pentabarf'].format(event_id=event_id))
        else:
            pentabarf_url = upload(pentabarf_file, UPLOAD_PATHS['exports']['pentabarf'].format(event_id=event_id))
        result = {
            'download_url': pentabarf_url
        }
        if not temp:
            event.pentabarf_url = pentabarf_url
            save_to_db(event)

    except Exception as e:
        print(traceback.format_exc())
        result = {'__error': True, 'result': str(e)}

    return result
    def after_create_object(self, role_invite, data, view_kwargs):
        """
        after create object method for role invite links
        :param role_invite:
        :param data:
        :param view_kwargs:
        :return:
        """
        user = User.query.filter_by(email=role_invite.email).first()
        if 'status' in data and data['status'] == 'accepted':
            role = Role.query.filter_by(name=role_invite.role_name).first()
            event = Event.query.filter_by(id=role_invite.event_id).first()
            uer = UsersEventsRoles.query.filter_by(user=user).filter_by(
                event=event).filter_by(role=role).first()
            if not uer:
                uer = UsersEventsRoles(user, event, role)
                save_to_db(uer, 'Role Invite accepted')

        event = Event.query.filter_by(id=role_invite.event_id).first()
        frontend_url = get_settings()['frontend_url']
        link = "{}/events/{}/role-invites/{}" \
            .format(frontend_url, event.id, role_invite.hash)

        send_email_role_invite(role_invite.email, role_invite.role_name, event.name, link)
        if user:
            send_notif_event_role(user, role_invite.role_name, event.name, link, event.id)
Ejemplo n.º 7
0
 def test_is_coorganizer_endpoint_related_to_event(self):
     with app.test_request_context(headers=self.auth, method="POST"):
         uer, is_created = get_or_create(UsersEventsRoles,
                                         user_id=1,
                                         event_id=1)
         uer.role_id = 2
         save_to_db(uer)
         self.assertTrue(has_access('is_coorganizer', event_id=1))
Ejemplo n.º 8
0
def update_import_job(task, result, result_status):
    """update import job status"""
    ij = ImportJob.query.filter_by(task=task).first()
    if not ij:
        return
    ij.result = result
    ij.result_status = result_status
    save_to_db(ij, 'Import job updated')
def update_import_job(task, result, result_status):
    """update import job status"""
    ij = ImportJob.query.filter_by(task=task).first()
    if not ij:
        return
    ij.result = result
    ij.result_status = result_status
    save_to_db(ij, 'Import job updated')
Ejemplo n.º 10
0
    def test_safe_query(self):
        """Method to test the function safe_query"""

        with app.test_request_context():
            event = EventFactoryBasic()
            save_to_db(event)
            obj = safe_query(db, Event, 'id', event.id, 'event_id')
            self.assertEqual(obj.name, event.name)
Ejemplo n.º 11
0
    def test_save_to_db(self):
        """Method to test the function save_to_db"""

        with app.test_request_context():
            obj = EventFactoryBasic()
            save_to_db(obj)
            event = db.session.query(Event).filter(Event.id == obj.id).first()
            self.assertEqual(obj.name, event.name)
Ejemplo n.º 12
0
 def test_is_registrar(self):
     with app.test_request_context(headers=self.auth, method="POST"):
         uer, is_created = get_or_create(UsersEventsRoles,
                                         user_id=1,
                                         event_id=1)
         uer.role_id = 6
         save_to_db(uer)
         self.assertTrue(has_access('is_registrar', event_id=1))
 def after_delete_object(self, stripe_authorization, view_kwargs):
     """Make work after delete object
     :param stripe_authorization: stripe authorization.
     :param dict view_kwargs: kwargs from the resource view
     """
     event = stripe_authorization.event
     event.is_stripe_linked = False
     save_to_db(event)
Ejemplo n.º 14
0
    def test_modify_email_for_user_to_be_deleted(self):
        """Method to test modification of email for user to be deleted"""

        with self.app.test_request_context():
            user = create_user(email="*****@*****.**", password="******")
            save_to_db(user)
            modified_user = modify_email_for_user_to_be_deleted(user)
            self.assertEqual("*****@*****.**", modified_user.email)
    def test_is_registrar(self):
        """Method to test whether a user is registrar of an event or not"""

        with app.test_request_context(headers=self.auth, method="POST"):
            uer, is_created = get_or_create(UsersEventsRoles, user_id=1, event_id=1)
            uer.role_id = 6
            save_to_db(uer)
            self.assertTrue(has_access('is_registrar', event_id=1))
Ejemplo n.º 16
0
def accept_invite():
    token = request.json['data']['token']
    try:
        role_invite = RoleInvite.query.filter_by(hash=token).one()
    except NoResultFound:
        raise NotFoundError({'source': ''}, 'Role Invite Not Found')
    else:
        try:
            user = User.query.filter_by(email=role_invite.email).first()
        except NoResultFound:
            raise NotFoundError(
                {'source': ''}, 'User corresponding to role invite not Found'
            )
        try:
            role = Role.query.filter_by(name=role_invite.role_name).first()
        except NoResultFound:
            raise NotFoundError(
                {'source': ''}, 'Role corresponding to role invite not Found'
            )
        event = Event.query.filter_by(id=role_invite.event_id).first()
        uer = (
            UsersEventsRoles.query.filter_by(user=user)
            .filter_by(event=event)
            .filter_by(role=role)
            .first()
        )

        if not uer:
            if role_invite.role_name == 'owner':
                past_owner = UsersEventsRoles.query.filter_by(
                    event=event, role=role
                ).first()
                oldrole = Role.query.filter_by(name='organizer').first()
                prevuser = User.query.filter_by(id=past_owner.user_id).first()
                if past_owner:
                    delete_previous_uer(past_owner)
                    puer = UsersEventsRoles(user=prevuser, event=event, role=oldrole)
                    save_to_db(puer, 'User Event Role changed')
            role_invite.status = "accepted"
            save_to_db(role_invite, 'Role Invite Accepted')
            # reset the group of event
            event.group_id = None
            save_to_db(event, 'Group ID Removed')
            uer = UsersEventsRoles(user=user, event=event, role=role)
            save_to_db(uer, 'User Event Role Created')
            if not user.is_verified:
                user.is_verified = True
                save_to_db(user, 'User verified')

    return jsonify(
        {
            "email": user.email,
            "event": role_invite.event_id,
            "event_identifier": role_invite.event.identifier,
            "name": user.fullname if user.fullname else None,
            "role": uer.role.name,
        }
    )
Ejemplo n.º 17
0
def create_order():
    data, errors = OrderAmountInputSchema().load(request.get_json())
    if errors:
        return make_response(jsonify(errors), 422)

    tickets_dict = data['tickets']
    order_amount = calculate_order_amount(tickets_dict, data.get('discount_code'))
    ticket_ids = {ticket['id'] for ticket in tickets_dict}
    ticket_map = {int(ticket['id']): ticket for ticket in tickets_dict}
    tickets = (
        Ticket.query.filter_by(deleted_at=None).filter(Ticket.id.in_(ticket_ids)).all()
    )

    if not tickets:
        raise UnprocessableEntityError(
            {'source': 'tickets'},
            "Tickets missing in Order request",
        )

    event = tickets[0].event

    try:
        attendees = []
        for ticket in tickets:
            for _ in range(ticket_map[ticket.id]['quantity']):
                ticket.raise_if_unavailable()
                attendees.append(
                    TicketHolder(firstname='', lastname='', ticket=ticket, event=event)
                )
                db.session.commit()
    except Exception as e:
        db.session.rollback()
        raise e

    validate_attendees({attendee.id for attendee in attendees})

    if data.get('amount') is not None and (
        current_user.is_staff or has_access('is_coorganizer', event_id=event.id)
    ):
        # If organizer or admin has overrided the amount of order
        order_amount['total'] = data['amount']

    order = Order(
        amount=order_amount['total'],
        event=event,
        discount_code_id=data.get('discount_code'),
        ticket_holders=attendees,
    )
    db.session.commit()
    order.populate_and_save()

    order_tickets = OrderTicket.query.filter_by(order_id=order.id).all()
    for order_ticket in order_tickets:
        ticket_info = ticket_map[order_ticket.ticket.id]
        order_ticket.price = ticket_info.get('price')
        save_to_db(order_ticket)
    
    return OrderSchema().dump(order)
Ejemplo n.º 18
0
def send_event_fee_notification():
    from app.instance import current_app as app
    with app.app_context():
        events = Event.query.filter_by(deleted_at=None,
                                       state='published').all()
        for event in events:
            latest_invoice = EventInvoice.query.filter_by(
                event_id=event.id).order_by(
                    EventInvoice.created_at.desc()).first()

            if latest_invoice:
                orders = Order.query \
                    .filter_by(event_id=event.id) \
                    .filter_by(status='completed') \
                    .filter(Order.completed_at > latest_invoice.created_at).all()
            else:
                orders = Order.query.filter_by(event_id=event.id).filter_by(
                    status='completed').all()

            fee_total = 0
            for order in orders:
                for ticket in order.tickets:
                    if order.paid_via != 'free' and order.amount > 0 and ticket.price > 0:
                        fee = ticket.price * (
                            get_fee(event.payment_country,
                                    order.event.payment_currency) / 100.0)
                        fee_total += fee

            if fee_total > 0:
                owner = get_user_event_roles_by_role_name(event.id,
                                                          'owner').first()
                new_invoice = EventInvoice(amount=fee_total,
                                           event_id=event.id,
                                           user_id=owner.user.id)

                if event.discount_code_id and event.discount_code:
                    r = relativedelta(datetime.datetime.utcnow(),
                                      event.created_at)
                    if r <= event.discount_code.valid_till:
                        new_invoice.amount = fee_total - \
                            (fee_total * (event.discount_code.value / 100.0))
                        new_invoice.discount_code_id = event.discount_code_id

                save_to_db(new_invoice)
                prev_month = monthdelta(new_invoice.created_at, 1).strftime(
                    "%b %Y")  # Displayed as Aug 2016
                app_name = get_settings()['app_name']
                frontend_url = get_settings()['frontend_url']
                link = '{}/invoices/{}'.format(frontend_url,
                                               new_invoice.identifier)
                send_email_for_monthly_fee_payment(new_invoice.user.email,
                                                   event.name, prev_month,
                                                   new_invoice.amount,
                                                   app_name, link)
                send_notif_monthly_fee_payment(new_invoice.user, event.name,
                                               prev_month, new_invoice.amount,
                                               app_name, link,
                                               new_invoice.event_id)
Ejemplo n.º 19
0
def send_notification(user, action, title, message):
    if not current_app.config['TESTING']:
        notification = Notification(user_id=user.id,
                                    title=title,
                                    message=message,
                                    action=action
                                    )
        save_to_db(notification, msg="Notification saved")
        record_activity('notification_event', user=user, action=action, title=title)
Ejemplo n.º 20
0
def create_user(email, password, is_verified=True):
    """
    Registers the user but not logs in
    """
    user = User(email=email,
                password=password,
                is_verified=is_verified)
    save_to_db(user, "User created")
    return user
Ejemplo n.º 21
0
    def test_is_registrar(self):
        """Method to test whether a user is registrar of an event or not"""

        with self.app.test_request_context(headers=self.auth, method="POST"):
            uer = UsersEventsRolesSubFactory(user_id=1,
                                             event_id=1,
                                             role__name='registrar')
            save_to_db(uer)
            assert has_access('is_registrar', event_id=1)
def send_monthly_event_invoice():
    from app.instance import current_app as app

    with app.app_context():
        events = Event.query.filter_by(deleted_at=None,
                                       state='published').all()
        for event in events:
            # calculate net & gross revenues
            user = event.owner
            admin_info = get_settings()
            currency = event.payment_currency
            try:
                ticket_fee_object = (db.session.query(TicketFees).filter_by(
                    currency=currency).one())
            except NoResultFound:
                logger.error('Ticket Fee not found for event id {id}'.format(
                    id=event.id))
                continue

            ticket_fee_percentage = ticket_fee_object.service_fee
            ticket_fee_maximum = ticket_fee_object.maximum_fee
            orders = Order.query.filter_by(event=event).all()
            gross_revenue = event.calc_monthly_revenue()
            invoice_amount = gross_revenue * (ticket_fee_percentage / 100)
            if invoice_amount > ticket_fee_maximum:
                invoice_amount = ticket_fee_maximum
            net_revenue = gross_revenue - invoice_amount
            payment_details = {
                'tickets_sold': event.tickets_sold,
                'gross_revenue': gross_revenue,
                'net_revenue': net_revenue,
                'amount_payable': invoice_amount,
            }
            # save invoice as pdf
            pdf = create_save_pdf(
                render_template(
                    'pdf/event_invoice.html',
                    orders=orders,
                    user=user,
                    admin_info=admin_info,
                    currency=currency,
                    event=event,
                    ticket_fee_object=ticket_fee_object,
                    payment_details=payment_details,
                    net_revenue=net_revenue,
                ),
                UPLOAD_PATHS['pdf']['event_invoice'],
                dir_path='/static/uploads/pdf/event_invoices/',
                identifier=event.identifier,
            )
            # save event_invoice info to DB

            event_invoice = EventInvoice(amount=invoice_amount,
                                         invoice_pdf_url=pdf,
                                         event_id=event.id)
            save_to_db(event_invoice)
Ejemplo n.º 23
0
def create_onsite_attendees_for_order(data):
    """
    Creates on site ticket holders for an order and adds it into the request data.
    :param data: data initially passed in the POST request for order.
    :return:
    """
    on_site_tickets = data.get('on_site_tickets')

    if not on_site_tickets:
        raise UnprocessableEntity(
            {'pointer': 'data/attributes/on_site_tickets'},
            'on_site_tickets info missing')

    data['ticket_holders'] = []

    for on_site_ticket in on_site_tickets:
        ticket_id = on_site_ticket['id']
        quantity = int(on_site_ticket['quantity'])

        ticket = safe_query_without_soft_deleted_entries(
            db, Ticket, 'id', ticket_id, 'ticket_id')

        ticket_sold_count = get_count(
            db.session.query(TicketHolder.id).filter_by(ticket_id=int(
                ticket.id),
                                                        deleted_at=None))

        # Check if the ticket is already sold out or not.
        if ticket_sold_count + quantity > ticket.quantity:
            # delete the already created attendees.
            for holder in data['ticket_holders']:
                ticket_holder = db.session.query(TicketHolder).filter(
                    id == int(holder)).one()
                db.session.delete(ticket_holder)
                try:
                    db.session.commit()
                except Exception as e:
                    logging.error('DB Exception! %s' % e)
                    db.session.rollback()

            raise ConflictException(
                {'pointer': '/data/attributes/on_site_tickets'},
                "Ticket with id: {} already sold out. You can buy at most {} tickets"
                .format(ticket_id, ticket.quantity - ticket_sold_count))

        for _ in range(1, quantity):
            ticket_holder = TicketHolder(firstname='onsite',
                                         lastname='attendee',
                                         email='*****@*****.**',
                                         ticket_id=ticket.id,
                                         event_id=data.get('event'))
            save_to_db(ticket_holder)
            data['ticket_holders'].append(ticket_holder.id)

    # delete from the data.
    del data['on_site_tickets']
def send_event_fee_notification():
    from app import current_app as app
    with app.app_context():
        events = Event.query.all()
        for event in events:
            latest_invoice = EventInvoice.query.filter_by(
                event_id=event.id).order_by(EventInvoice.created_at.desc()).first()

            if latest_invoice:
                orders = Order.query \
                    .filter_by(event_id=event.id) \
                    .filter_by(status='completed') \
                    .filter(Order.completed_at > latest_invoice.created_at).all()
            else:
                orders = Order.query.filter_by(
                    event_id=event.id).filter_by(status='completed').all()

            fee_total = 0
            for order in orders:
                for order_ticket in order.tickets:
                    ticket = safe_query(db, Ticket, 'id', order_ticket.ticket_id, 'ticket_id')
                    if order.paid_via != 'free' and order.amount > 0 and ticket.price > 0:
                        fee = ticket.price * (get_fee(order.event.payment_currency) / 100.0)
                        fee_total += fee

            if fee_total > 0:
                organizer = get_user_event_roles_by_role_name(event.id, 'organizer').first()
                new_invoice = EventInvoice(
                    amount=fee_total, event_id=event.id, user_id=organizer.user.id)

                if event.discount_code_id and event.discount_code:
                    r = relativedelta(datetime.utcnow(), event.created_at)
                    if r <= event.discount_code.valid_till:
                        new_invoice.amount = fee_total - \
                            (fee_total * (event.discount_code.value / 100.0))
                        new_invoice.discount_code_id = event.discount_code_id

                save_to_db(new_invoice)
                prev_month = monthdelta(new_invoice.created_at, 1).strftime(
                    "%b %Y")  # Displayed as Aug 2016
                app_name = get_settings()['app_name']
                frontend_url = get_settings()['frontend_url']
                link = '{}/invoices/{}'.format(frontend_url, new_invoice.identifier)
                send_email_for_monthly_fee_payment(new_invoice.user.email,
                                                   event.name,
                                                   prev_month,
                                                   new_invoice.amount,
                                                   app_name,
                                                   link)
                send_notif_monthly_fee_payment(new_invoice.user,
                                               event.name,
                                               prev_month,
                                               new_invoice.amount,
                                               app_name,
                                               link,
                                               new_invoice.event_id)
Ejemplo n.º 25
0
    def test_is_track_organizer(self):
        """Method to test whether a user is track organizer of an event or not"""

        with app.test_request_context(headers=self.auth, method="POST"):
            uer, is_created = get_or_create(UsersEventsRoles,
                                            user_id=1,
                                            event_id=1)
            uer.role_id = 4
            save_to_db(uer)
            self.assertTrue(has_access('is_moderator', event_id=1))
Ejemplo n.º 26
0
 def used_payment(payment_id, order):
     """
     Function to check for recycling of payment IDs
     """
     if Order.query.filter(Order.paypal_token == payment_id).first() is None:
         order.paypal_token = payment_id
         save_to_db(order)
         return False
     else:
         return True
 def test_export(self):
     """Test to check event contents in pentabarfxml format"""
     with app.test_request_context():
         test_event = EventFactoryBasic()
         save_to_db(test_event)
         pentabarf_export = PentabarfExporter()
         pentabarf_string = pentabarf_export.export(test_event.id)
         pentabarf_original = fromstring(pentabarf_string)
         self.assertEqual(fromstring(tostring(pentabarf_original))[0][0].text, "example")
         self.assertEqual(fromstring(tostring(pentabarf_original))[0][1].text, "2099-12-13")
Ejemplo n.º 28
0
    def test_save_to_db(self):
        """Check DBHelper: save to db"""
        with app.test_request_context():
            with mixer.ctx(commit=False):
                mixer.init_app(app)
                obj = mixer.blend(User)

            save_to_db(obj)
            user = db.session.query(User).filter(User.id == obj.id).first()
            self.assertEqual(obj.name, user.name)
Ejemplo n.º 29
0
 def after_update_object(self, role_invite, data, view_kwargs):
     user = User.query.filter_by(email=role_invite.email).first()
     if 'status' in data and data['status'] == 'accepted':
         role = Role.query.filter_by(name=role_invite.role_name).first()
         event = Event.query.filter_by(id=role_invite.event_id).first()
         uer = UsersEventsRoles.query.filter_by(user=user).filter_by(
             event=event).filter_by(role=role).first()
         if not uer:
             uer = UsersEventsRoles(user, event, role)
             save_to_db(uer, 'Role Invite accepted')
Ejemplo n.º 30
0
def change_session_state_on_event_completion():
    from app import current_app as app
    with app.app_context():
        sessions_to_be_changed = Session.query.join(Event).filter(Session.state == 'pending')\
                                 .filter(Event.ends_at < datetime.datetime.now())
        for session in sessions_to_be_changed:
            session.state = 'rejected'
            save_to_db(
                session,
                'Changed {} session state to rejected'.format(session.title))
Ejemplo n.º 31
0
 def after_update_object(self, role_invite, data, view_kwargs):
     user = User.query.filter_by(email=role_invite.email).first()
     if 'status' in data and data['status'] == 'accepted':
         role = Role.query.filter_by(name=role_invite.role_name).first()
         event = Event.query.filter_by(id=role_invite.event_id).first()
         uer = UsersEventsRoles.query.filter_by(user=user).filter_by(
             event=event).filter_by(role=role).first()
         if not uer:
             uer = UsersEventsRoles(user, event, role)
             save_to_db(uer, 'Role Invite accepted')
Ejemplo n.º 32
0
    def after_update_object(self, session, data, view_kwargs):
        """ Send email if session accepted or rejected """

        if ('state' in data and data.get('send_email', None) and
            (session.state == 'accepted' or session.state == 'rejected')):

            event = session.event
            # Email for speaker
            speakers = session.speakers
            for speaker in speakers:
                frontend_url = get_settings()['frontend_url']
                link = "{}/events/{}/sessions/{}".format(
                    frontend_url, event.identifier, session.id)
                if not speaker.is_email_overridden:
                    send_email_session_accept_reject(speaker.email, session,
                                                     link)
                    send_notif_session_accept_reject(speaker, session.title,
                                                     session.state, link,
                                                     session.id)

            # Email for owner
            if session.event.get_owner():
                owner = session.event.get_owner()
                owner_email = owner.email
                frontend_url = get_settings()['frontend_url']
                link = "{}/events/{}/sessions/{}".format(
                    frontend_url, event.identifier, session.id)
                send_email_session_accept_reject(owner_email, session, link)
                send_notif_session_accept_reject(owner, session.title,
                                                 session.state, link,
                                                 session.id)
        if 'state' in data:
            entry_count = SessionsSpeakersLink.query.filter_by(
                session_id=session.id)
            if entry_count.count() == 0:
                is_patch_request = False
            else:
                is_patch_request = True

            if is_patch_request:
                for focus_session in entry_count:
                    focus_session.session_state = session.state
                db.session.commit()
            else:
                current_session = Session.query.filter_by(
                    id=session.id).first()
                for speaker in current_session.speakers:
                    session_speaker_link = SessionsSpeakersLink(
                        session_state=session.state,
                        session_id=session.id,
                        event_id=session.event.id,
                        speaker_id=speaker.id,
                    )
                    save_to_db(session_speaker_link,
                               "Session Speaker Link Saved")
Ejemplo n.º 33
0
 def before_get(self, args, kwargs):
     events = Event.query.all()
     for event in events:
         sales = summary(event)
         event.completed_order_sales = sales['completed']['sales_total']
         event.placed_order_sales = sales['placed']['sales_total']
         event.pending_order_sales = sales['pending']['sales_total']
         event.completed_order_tickets = sales['completed']['ticket_count']
         event.placed_order_tickets = sales['placed']['ticket_count']
         event.pending_order_tickets = sales['pending']['ticket_count']
         save_to_db(event)
def send_notification(user, action, title, message):
    if not current_app.config['TESTING']:
        notification = Notification(user_id=user.id,
                                    title=title,
                                    message=message,
                                    action=action)
        save_to_db(notification, msg="Notification saved")
        record_activity('notification_event',
                        user=user,
                        action=action,
                        title=title)
Ejemplo n.º 35
0
def sponsor_logos_url_task(self, event_id):
    sponsors = Sponsor.query.filter_by(event_id=event_id, deleted_at=None).all()
    for sponsor in sponsors:
        try:
            logging.info('Sponsor logo url generation task started {}'.format(sponsor.logo_url))
            new_logo_url = create_save_resized_image(image_file=sponsor.logo_url, resize=False)
            sponsor.logo_url = new_logo_url
            save_to_db(sponsor)
            logging.info('Sponsor logo url successfully generated')
        except(urllib.error.HTTPError, urllib.error.URLError):
            logging.exception('Error encountered while logo generation')
def get_event_exported_actions(download_url):
    """
    Get the actions associated with a notification about an event being successfully exported.
    :param download_url: download url of the event.
    :return: actions.
    """
    download_action = NotificationAction(subject='event-export',
                                         link=download_url,
                                         action_type='download')
    save_to_db(download_action)
    return [download_action]
 def after_create_object(self, stripe_authorization, data, view_kwargs):
     """
     after create object method for StripeAuthorizationListPost Class
     :param stripe_authorization: Stripe authorization created from mashmallow_jsonapi
     :param data:
     :param view_kwargs:
     :return:
     """
     event = db.session.query(Event).filter_by(id=int(data['event'])).one()
     event.is_stripe_linked = True
     save_to_db(event)
def get_ticket_purchased_attendee_notification_actions(pdf_url):
    """
    Get the actions associated with a notification of tickets purchased for an attendee that is not the buyer.
    :param pdf_url:
    :return: actions
    """
    view_ticket_action = NotificationAction(subject='tickets-pdf',
                                            link=pdf_url,
                                            action_type='view')
    save_to_db(view_ticket_action)
    return [view_ticket_action]
Ejemplo n.º 39
0
 def test_export(self):
     """Test to check event contents in xCal format"""
     with self.app.test_request_context():
         test_event = EventFactoryBasic()
         save_to_db(test_event)
         xcal = XCalExporter()
         xcal_string = xcal.export(test_event.id)
         xcal_original = fromstring(xcal_string)
         assert fromstring(tostring(xcal_original))[0][3].text == "example"
         assert fromstring(tostring(xcal_original))[0][2].text == \
             "Schedule for sessions at example"
 def after_create_object(self, stripe_authorization, data, view_kwargs):
     """
     after create object method for StripeAuthorizationListPost Class
     :param stripe_authorization: Stripe authorization created from mashmallow_jsonapi
     :param data:
     :param view_kwargs:
     :return:
     """
     event = db.session.query(Event).filter_by(id=int(data['event'])).one()
     event.is_stripe_linked = True
     save_to_db(event)
Ejemplo n.º 41
0
    def test_get_or_create(self):
        with app.test_request_context():
            event = EventFactoryBasic()
            save_to_db(event)
            obj, is_created = get_or_create(Event, name=event.name)
            self.assertEqual(event.id, obj.id)
            self.assertFalse(is_created)

            obj, is_created = get_or_create(Event, name="new event", starts_at=event.starts_at, ends_at=event.ends_at)
            self.assertNotEqual(event.id, obj.id)
            self.assertTrue(is_created)
Ejemplo n.º 42
0
 def test_export(self):
     """Test to check event contents in pentabarfxml format"""
     with self.app.test_request_context():
         test_event = EventFactoryBasic()
         save_to_db(test_event)
         pentabarf_export = PentabarfExporter()
         pentabarf_string = pentabarf_export.export(test_event.id)
         pentabarf_original = fromstring(pentabarf_string)
         self.assertEqual(pentabarf_original.find('conference/title').text, "example")
         self.assertEqual(
             pentabarf_original.find('conference/start').text, "2099-12-13"
         )
Ejemplo n.º 43
0
def resize_speaker_images_task(self, speaker_id, photo_url):
    speaker = safe_query(db, Speaker, 'id', speaker_id, 'speaker_id')
    try:
        logging.info('Speaker image resizing tasks started for speaker with id {}'.format(speaker_id))
        uploaded_images = create_save_image_sizes(photo_url, 'speaker-image', speaker_id)
        speaker.small_image_url = uploaded_images['small_image_url']
        speaker.thumbnail_image_url = uploaded_images['thumbnail_image_url']
        speaker.icon_image_url = uploaded_images['icon_image_url']
        save_to_db(speaker)
        logging.info('Resized images saved successfully for speaker with id: {}'.format(speaker_id))
    except (urllib.error.HTTPError, urllib.error.URLError):
        logging.exception('Error encountered while generating resized images for event with id: {}'.format(speaker_id))
Ejemplo n.º 44
0
def resize_event_images_task(self, event_id, original_image_url):
    event = safe_query(db, Event, 'id', event_id, 'event_id')
    try:
        logging.info('Event image resizing tasks started {}'.format(original_image_url))
        uploaded_images = create_save_image_sizes(original_image_url, 'event-image', event.id)
        event.large_image_url = uploaded_images['large_image_url']
        event.thumbnail_image_url = uploaded_images['thumbnail_image_url']
        event.icon_image_url = uploaded_images['icon_image_url']
        save_to_db(event)
        logging.info('Resized images saved successfully for event with id: {}'.format(event_id))
    except (urllib.error.HTTPError, urllib.error.URLError):
        logging.exception('Error encountered while generating resized images for event with id: {}'.format(event_id))
Ejemplo n.º 45
0
def get_ticket_purchased_notification_actions(order_id, order_url):
    """
    Get the actions associated with a notification of tickets purchased.
    :param order_id: order id
    :param order_url: order invoice url.
    :return:
    """
    view_order_invoice_action = NotificationAction(
        subject='order', link=order_url, subject_id=order_id, action_type='view'
    )
    save_to_db(view_order_invoice_action)
    return [view_order_invoice_action]
def get_event_exported_actions(download_url):
    """
    Get the actions associated with a notification about an event being successfully exported.
    :param download_url: download url of the event.
    :return: actions.
    """
    download_action = NotificationAction(
        subject='event-export',
        link=download_url,
        action_type='download'
    )
    save_to_db(download_action)
    return [download_action]
def get_ticket_purchased_attendee_notification_actions(pdf_url):
    """
    Get the actions associated with a notification of tickets purchased for an attendee that is not the buyer.
    :param pdf_url:
    :return: actions
    """
    view_ticket_action = NotificationAction(
        subject='tickets-pdf',
        link=pdf_url,
        action_type='view'
    )
    save_to_db(view_ticket_action)
    return [view_ticket_action]
Ejemplo n.º 48
0
def create_onsite_attendees_for_order(data):
    """
    Creates on site ticket holders for an order and adds it into the request data.
    :param data: data initially passed in the POST request for order.
    :return:
    """
    on_site_tickets = data.get('on_site_tickets')

    if not on_site_tickets:
        raise UnprocessableEntity({'pointer': 'data/attributes/on_site_tickets'}, 'on_site_tickets info missing')

    data['ticket_holders'] = []

    for on_site_ticket in on_site_tickets:
        ticket_id = on_site_ticket['id']
        quantity = int(on_site_ticket['quantity'])

        ticket = safe_query_without_soft_deleted_entries(db, Ticket, 'id', ticket_id, 'ticket_id')

        ticket_sold_count = get_count(db.session.query(TicketHolder.id).
                                      filter_by(ticket_id=int(ticket.id), deleted_at=None))

        # Check if the ticket is already sold out or not.
        if ticket_sold_count + quantity > ticket.quantity:
            # delete the already created attendees.
            for holder in data['ticket_holders']:
                ticket_holder = db.session.query(TicketHolder).filter(id == int(holder)).one()
                db.session.delete(ticket_holder)
                try:
                    db.session.commit()
                except Exception as e:
                    logging.error('DB Exception! %s' % e)
                    db.session.rollback()

            raise ConflictException(
                {'pointer': '/data/attributes/on_site_tickets'},
                "Ticket with id: {} already sold out. You can buy at most {} tickets".format(ticket_id,
                                                                                             ticket.quantity -
                                                                                             ticket_sold_count)
            )

        for _ in range(1, quantity):
            ticket_holder = TicketHolder(firstname='onsite', lastname='attendee', email='*****@*****.**',
                                         ticket_id=ticket.id, event_id=data.get('event'))
            save_to_db(ticket_holder)
            data['ticket_holders'].append(ticket_holder.id)

    # delete from the data.
    del data['on_site_tickets']
def get_ticket_purchased_organizer_notification_actions(order_id, order_url):
    """
    Get the actions associated with a notification of tickets purchased for the event organizer.
    :param order_id: order id
    :param order_url: order url
    :return: actions
    """
    view_ticket_action = NotificationAction(
        subject='order',
        subject_id=order_id,
        link=order_url,
        action_type='view'
    )
    save_to_db(view_ticket_action)
    return [view_ticket_action]
def get_event_imported_actions(event_id, event_url):
    """
    Get the actions associated with a notification about an event being successfully imported.
    :param event_id: id of the event.
    :param event_url: url of the event.
    :return: actions
    """
    view_event_action = NotificationAction(
        subject='event',  # subject is still 'event' since the action will be to view the imported event.
        link=event_url,
        subject_id=event_id,
        action_type='view'
    )
    save_to_db(view_event_action)
    return [view_event_action]
def get_session_accept_reject_notification_actions(session_id, link):
    """
    Get the actions associated with a notification of a session getting accepted/rejected.
    :param session_id: id of the session.
    :param link: link to view the session.
    :return: actions
    """
    view_session_action = NotificationAction(
        subject='session',
        link=link,
        subject_id=session_id,
        action_type='view'
    )
    save_to_db(view_session_action)
    return [view_session_action]
def get_next_event_notification_actions(event_id, link):
    """
    Get the actions associated with a notification of next event.
    :param event_id: id of the event.
    :param link: link to view the event.
    :return: actions
    """
    view_event_action = NotificationAction(
        subject='event',
        link=link,
        subject_id=event_id,
        action_type='view'
    )
    save_to_db(view_event_action)
    return [view_event_action]
def get_event_published_notification_actions(event_id, event_link):
    """
    Get the actions associated with a notification of an event getting published.
    :param event_id: event id
    :param event_link: event url
    :return: actions
    """
    view_event_action = NotificationAction(
        subject='event',
        subject_id=event_id,
        link=event_link,
        action_type='view'
    )
    save_to_db(view_event_action)
    return [view_event_action]
Ejemplo n.º 54
0
def set_expiry_for_order(order, override=False):
    """
    Expire the order after the time slot(10 minutes) if the order is pending.
    Also expires the order if we want to expire an order regardless of the state and time.
    :param order: Order to be expired.
    :param override: flag to force expiry.
    :return:
    """
    if order and not order.paid_via and (override or (order.status == 'pending' and (
                order.created_at +
                timedelta(minutes=order.event.order_expiry_time)) < datetime.now(timezone.utc))):
            order.status = 'expired'
            delete_related_attendees_for_order(order)
            save_to_db(order)
    return order
def get_monthly_payment_follow_up_notification_actions(event_id, payment_url):
    """
    Get the actions associated with a follow up notification of monthly payments.
    :param event_id: id of the event.
    :param payment_url: url to view invoice.
    :return: actions
    """
    view_invoice_action = NotificationAction(
        subject='invoice',
        link=payment_url,
        subject_id=event_id,
        action_type='view'
    )
    save_to_db(view_invoice_action)
    return [view_invoice_action]
def get_event_role_notification_actions(event_id, invitation_link):
    """
    Get the actions associated with a notification of an event role.
    :param event_id: ID of the event.
    :param invitation_link: link for invitation.
    :return: actions
    """
    accept_event_role_action = NotificationAction(
        subject='event-role',
        subject_id=event_id,
        link=invitation_link,
        action_type='view'
    )
    save_to_db(accept_event_role_action)
    return [accept_event_role_action]
def get_ticket_purchased_notification_actions(order_id, order_url):
    """
    Get the actions associated with a notification of tickets purchased.
    :param order_id: order id
    :param order_url: order invoice url.
    :return:
    """
    view_order_invoice_action = NotificationAction(
        subject='order',
        link=order_url,
        subject_id=order_id,
        action_type='view'
    )
    save_to_db(view_order_invoice_action)
    return [view_order_invoice_action]
Ejemplo n.º 58
0
 def after_create_object(self, event, data, view_kwargs):
     """
     after create method to save roles for users
     :param event:
     :param data:
     :param view_kwargs:
     :return:
     """
     role = Role.query.filter_by(name=ORGANIZER).first()
     user = User.query.filter_by(id=view_kwargs['user_id']).first()
     uer = UsersEventsRoles(user, event, role)
     save_to_db(uer, 'Event Saved')
     if data.get('original_image_url'):
         uploaded_images = create_save_image_sizes(data['original_image_url'], 'event', event.id)
         self.session.query(Event).filter_by(id=event.id).update(uploaded_images)
         self.session.commit()
Ejemplo n.º 59
0
    def get_checkout_url(order, currency=None, credentials=None):
        if not credentials:
            credentials = PayPalPaymentsManager.get_credentials(order.event)

        if not credentials:
            raise Exception('PayPal credentials have not be set correctly')

        if current_app.config['TESTING']:
            return credentials['CHECKOUT_URL']

        currency = order.event.payment_currency if not currency and order.event.payment_currency != "" else "USD"
        data = {
            'USER': credentials['USER'],
            'PWD': credentials['PWD'],
            'SIGNATURE': credentials['SIGNATURE'],
            'SUBJECT': credentials['EMAIL'],

            'METHOD': 'SetExpressCheckout',
            'VERSION': PayPalPaymentsManager.api_version,
            'PAYMENTREQUEST_0_PAYMENTACTION': 'SALE',
            'PAYMENTREQUEST_0_AMT': order.amount,
            'PAYMENTREQUEST_0_CURRENCYCODE': currency,
            'RETURNURL': make_frontend_url(path='/orders/{identifier}/payment/success'.
                                           format(identifier=order.identifier)),
            'CANCELURL': make_frontend_url(path='/orders/{identifier}/payment/cancelled'.
                                           format(identifier=order.identifier))
        }

        count = 1

        if type(order) is Order:
            for ticket_order in order.order_tickets:
                data['L_PAYMENTREQUEST_' + str(count) + '_NAMEm'] = ticket_order.ticket.name
                data['L_PAYMENTREQUEST_' + str(count) + '_QTYm'] = ticket_order.quantity
                data['L_PAYMENTREQUEST_' + str(count) + '_AMTm'] = ticket_order.ticket.price
                count += 1

        response = requests.post(credentials['SERVER'], data=data)
        if 'TOKEN' not in dict(urlparse.parse_qsl(response.text)):
            raise Exception('PayPal Token could not be retrieved')
        token = dict(urlparse.parse_qsl(response.text))['TOKEN']
        order.paypal_token = token
        save_to_db(order)
        return credentials['CHECKOUT_URL'] + "?" + urlencode({
            'cmd': '_express-checkout',
            'token': token
        })
def create_export_job(task_id, event_id):
    """
    Create export job for an export that is going to start
    """
    export_job = ExportJob.query.filter_by(event_id=event_id).first()
    task_url = url_for('tasks.celery_task', task_id=task_id)
    if export_job:

        export_job.task = task_url
        export_job.user_email = current_identity.email
        export_job.event = Event.query.get(event_id)
        export_job.starts_at = datetime.now(pytz.utc)
    else:
        export_job = ExportJob(
            task=task_url, user_email=current_identity.email,
            event=Event.query.get(event_id)
        )
    save_to_db(export_job, 'ExportJob saved')