def test_wrong_form_config(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event saved")
         url = url_for('event_sessions.create_view', event_id=event.id)
         rv = self.app.get(url, follow_redirects=True)
         self.assertFalse("incorrectly configured" in rv.data, msg=rv.data)
 def test_scheduler_publish(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event saved")
         rv = self.app.get(url_for('event_scheduler.publish', event_id=event.id), follow_redirects=True)
         event = DataGetter.get_event(event.id)
         self.assertTrue(event.schedule_published_on is not None, msg=rv.data)
def send_event_fee_notification():
    with app.app_context():
        events = Event.query.all()
        for event in events:
            latest_invoice = EventInvoice.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 = TicketingManager.get_ticket(order_ticket.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)
                        fee_total += fee

            if fee_total > 0:
                new_invoice = EventInvoice(amount=fee_total, event_id=event.id, user_id=event.creator_id)
                save_to_db(new_invoice)
                prev_month = monthdelta(new_invoice.created_at, 1).strftime("%b %Y")  # Displayed as Aug 2016
                send_email_for_monthly_fee_payment(new_invoice.user.email,
                                                   event.name,
                                                   prev_month,
                                                   new_invoice.amount,
                                                   url_for('event_invoicing.view_invoice',
                                                           invoice_identifier=new_invoice.identifier, _external=True))
 def test_session_delete(self):
     with app.test_request_context():
         session = ObjectMother.get_session()
         save_to_db(session, "Session Saved")
         url = url_for('event_sessions.delete_session', event_id=1, session_id=session.id)
         rv = self.app.get(url, follow_redirects=True)
         self.assertTrue("deleted" in rv.data, msg=rv.data)
Ejemplo n.º 5
0
def publish_event(event_id):
    event = DataGetter.get_event(event_id)
    if string_empty(event.location_name):
        flash(
            "Your event was saved. To publish your event please review the highlighted fields below.",
            "warning")
        return redirect(url_for('.edit_view',
                                event_id=event.id) + "#highlight=location_name")
    if not current_user.can_publish_event():
        flash("You don't have permission to publish event.")
        return redirect(url_for('.details_view', event_id=event_id))
    event.state = 'Published'
    save_to_db(event, 'Event Published')
    organizers = DataGetter.get_user_event_roles_by_role_name(event_id, 'organizer')
    speakers = DataGetter.get_user_event_roles_by_role_name(event_id, 'speaker')
    link = url_for('.details_view', event_id=event_id, _external=True)

    for organizer in organizers:
        send_event_publish(organizer.user.email, event.name, link)
    for speaker in speakers:
        send_event_publish(speaker.user.email, event.name, link)

    record_activity('publish_event', event_id=event.id, status='published')
    flash("Your event has been published.", "success")
    return redirect(url_for('.details_view', event_id=event_id))
Ejemplo n.º 6
0
def unpublish_event(event_id):
    event = DataGetter.get_event(event_id)
    event.state = 'Draft'
    save_to_db(event, 'Event Unpublished')
    record_activity('publish_event', event_id=event.id, status='un-published')
    flash("Your event has been unpublished.", "warning")
    return redirect(url_for('.details_view', event_id=event_id))
def withdraw_session_view(session_id):
    session = DataGetter.get_sessions_of_user_by_id(session_id)
    session.in_trash = True
    session.trash_date = datetime.now()
    save_to_db(session)
    flash("The session has been withdrawn", "success")
    return redirect(url_for('.display_my_sessions_view', session_id=session_id))
 def test_speakers_list(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event saved")
         url = url_for('event_speakers.index_view', event_id=event.id)
         rv = self.app.get(url, follow_redirects=True)
         self.assertTrue("Speakers" in rv.data, msg=rv.data)
 def test_unpublished_event_view_attempt(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event Saved")
         rv = self.app.get(url_for('event_detail.display_event_detail_home', identifier=event.identifier),
                           follow_redirects=True)
         self.assertEqual(rv.status_code, 404)
Ejemplo n.º 10
0
 def test_event_delete(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event saved")
         url = url_for('events.trash_view', event_id=event.id)
         rv = self.app.get(url, follow_redirects=True)
         self.assertTrue("Your event has been deleted" in rv.data, msg=rv.data)
Ejemplo n.º 11
0
    def charge_stripe_order_payment(form):
        order = TicketingManager.get_and_set_expiry(form['identifier'])
        order.stripe_token = form['stripe_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 = url_for('ticketing.view_order_after_payment',
                                order_identifier=order.identifier,
                                _external=True)
            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, 'Error'
Ejemplo n.º 12
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 = url_for('ticketing.view_order_after_payment',
                                    order_identifier=order.identifier,
                                    _external=True)
                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.º 13
0
    def create_edit_discount_code(form, discount_code_id=None):
        if not discount_code_id:
            discount_code = DiscountCode()
        else:
            discount_code = InvoicingManager.get_discount_code(discount_code_id)
        discount_code.code = form.get('code')
        discount_code.value = form.get('value')
        discount_code.type = 'percent'
        discount_code.max_quantity = form.get('max_quantity', None)
        discount_code.tickets_number = form.get('tickets_number')
        discount_code.used_for = EVENT
        discount_code.marketer_id = form.get('marketer')
        discount_code.is_active = form.get('status', 'in_active') == 'active'

        if discount_code.max_quantity == "":
            discount_code.max_quantity = None

        try:
            discount_code.valid_from = datetime.strptime(form.get('start_date', None) + ' ' +
                                                         form.get('start_time', None), '%m/%d/%Y %H:%M')
        except:
            discount_code.valid_from = None

        try:
            discount_code.valid_till = datetime.strptime(form.get('end_date', None) + ' ' +
                                                         form.get('end_time', None), '%m/%d/%Y %H:%M')
        except:
            discount_code.valid_till = None

        save_to_db(discount_code)

        return discount_code
Ejemplo n.º 14
0
 def test_events_edit(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event saved")
         custom_forms = ObjectMother.get_custom_form(event.id)
         save_to_db(custom_forms, "Custom forms saved")
         url = url_for('events.edit_view', event_id=event.id)
         data = POST_EVENT_DATA.copy()
         del data['copyright']
         data['sponsors_state'] = 'on'
         data['sponsors[name]'] = ['Sponsor 1', 'Sponsor 2']
         data['sponsors[type]'] = ['Gold', 'Silver']
         data['sponsors[url]'] = ["", ""]
         data['sponsors[description]'] = ["", ""]
         data['sponsors[level]'] = ["", ""]
         data['name'] = 'EditTestName'
         data['start_date'] = '07/04/2016'
         data['start_time'] = '19:00'
         data['has_session_speakers'] = 'yes'
         data['end_date'] = '07/04/2016'
         data['end_time'] = '22:00'
         data['has_session_speakers'] = 'no'
         data['custom_form[name]'] = ['session_form', 'speaker_form']
         data['custom_form[value]'] = [custom_forms.session_form, custom_forms.speaker_form]
         data = ImmutableMultiDict(data)
         rv = self.app.post(url, follow_redirects=True, buffered=True, content_type='multipart/form-data',
                            data=data)
         self.assertTrue('EditTestName' in rv.data, msg=rv.data)
         self.assertTrue(data['sponsors[name]'] in rv.data, msg=rv.data)
def save_custom_forms(data, event_id):
    custom_forms = DataGetter.get_custom_form_elements(event_id)
    if not custom_forms:
        custom_forms = CustomForms(event_id=event_id)
    custom_forms.session_form = json.dumps(data['session'])
    custom_forms.speaker_form = json.dumps(data['speaker'])
    save_to_db(custom_forms)
Ejemplo n.º 16
0
def withdraw_session_view(session_id):
    session = DataGetter.get_sessions_of_user_by_id(session_id)
    session.deleted_at = datetime.now()
    sessions_modified.send(current_app._get_current_object(), event_id=session.event_id)
    save_to_db(session)
    flash("The session has been withdrawn", "success")
    return redirect(url_for('.display_my_sessions_view', session_id=session_id))
Ejemplo n.º 17
0
    def initiate_invoice_payment(form):
        identifier = form['identifier']
        email = form['email']

        invoice = InvoicingManager.get_invoice_by_identifier(identifier)
        if invoice:
            user = invoice.user
            if invoice.amount > 0 \
                and (not invoice.paid_via
                     or (invoice.paid_via
                         and (invoice.paid_via == 'stripe'
                              or invoice.paid_via == 'paypal'))):

                country = form['country']
                address = form['address']
                city = form['city']
                state = form['state']
                zipcode = form['zipcode']
                invoice.address = address
                invoice.city = city
                invoice.state = state
                invoice.country = country
                invoice.zipcode = zipcode
                invoice.status = 'initialized'
            else:
                invoice.status = 'completed'
                invoice.completed_at = datetime.utcnow()
                if not invoice.paid_via:
                    invoice.paid_via = 'free'
            save_to_db(invoice)
            return invoice
        else:
            return False
def empty_trash():
    from app import current_app as app

    with app.app_context():
        events = Event.query.filter(Event.deleted_at.isnot(None)).all()
        users = User.query.filter(User.deleted_at.isnot(None)).all()
        sessions = Session.query.filter(Session.deleted_at.isnot(None)).all()
        pending_orders = Order.query.filter_by(status="pending")

        for event in events:
            if datetime.now() - event.deleted_at >= timedelta(days=30):
                DataManager.delete_event(event.id)

        for user in users:
            if datetime.now() - user.deleted_at >= timedelta(days=30):
                transaction = transaction_class(Event)
                transaction.query.filter_by(user_id=user.id).delete()
                delete_from_db(user, "User deleted permanently")

        for session_ in sessions:
            if datetime.now() - session_.deleted_at >= timedelta(days=30):
                delete_from_db(session_, "Session deleted permanently")

        for pending_order in pending_orders:
            if datetime.now() - pending_order.created_at >= timedelta(days=3):
                pending_order.status = "expired"
                save_to_db(pending_order, "Pending order expired.")
Ejemplo n.º 19
0
 def test_event_copy(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event saved")
         url = url_for('events.copy_event', event_id=event.id)
         rv = self.app.get(url, follow_redirects=True)
         self.assertTrue("Copy of event1" in rv.data, msg=rv.data)
 def test_unpublished_event_view_coc(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         event.state = "Published"
         save_to_db(event, "Event Saved")
         rv = self.app.get(url_for("event_detail.display_event_coc", event_id=event.id), follow_redirects=True)
         self.assertEqual(rv.status_code, 404)
    def initiate_order_payment(form):
        identifier = form['identifier']
        email = form['email']

        order = TicketingManager.get_and_set_expiry(identifier)

        if order:

            user = TicketingManager.get_or_create_user_by_email(email, form)
            order.user_id = user.id

            if order.amount > 0 \
                and (not order.paid_via
                     or (order.paid_via
                         and (order.paid_via == 'stripe'
                              or order.paid_via == 'paypal'))):

                country = form['country']
                address = form['address']
                city = form['city']
                state = form['state']
                zipcode = form['zipcode']
                order.address = address
                order.city = city
                order.state = state
                order.country = country
                order.zipcode = zipcode
                order.status = 'initialized'
            else:
                order.status = 'completed'
                order.completed_at = datetime.utcnow()
                if not order.paid_via:
                    order.paid_via = 'free'

            holders_firstnames = form.getlist('holders[firstname]')
            holders_lastnames = form.getlist('holders[lastname]')
            holders_ticket_ids = form.getlist('holders[ticket_id]')
            holders_emails = form.getlist('holders[email]')

            for i, firstname in enumerate(holders_firstnames):
                data = {
                    'firstname': firstname,
                    'lastname': holders_lastnames[i]
                }
                holder_user = TicketingManager.get_or_create_user_by_email(holders_emails[i], data)
                ticket_holder = TicketHolder(firstname=data['firstname'],
                                             lastname=data['lastname'],
                                             ticket_id=int(holders_ticket_ids[i]),
                                             email=holder_user.email, order_id=order.id)
                DataManager.add_attendee_role_to_event(holder_user, order.event_id)
                db.session.add(ticket_holder)

            # add attendee role to user
            DataManager.add_attendee_role_to_event(user, order.event_id)
            # save items
            save_to_db(order)
            return order
        else:
            return False
Ejemplo n.º 22
0
 def test_event_publish(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event saved")
         url = url_for('events.publish_event', event_id=event.id)
         rv = self.app.get(url, follow_redirects=True)
         event = DataGetter.get_event(event.id)
         self.assertEqual("Published", event.state, msg=event.state)
Ejemplo n.º 23
0
def set_role():
    """Set user role method"""
    id = request.args['id']
    role = request.args['roles']
    user = DataGetter.get_user(id)
    user.role = role
    save_to_db(user, "User Role updated")
    return redirect(url_for('.roles_manager'))
 def test_published_event_view_coc(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         event.state = "Published"
         event.code_of_conduct = "Test Code of Conduct"
         save_to_db(event, "Event Saved")
         rv = self.app.get(url_for("event_detail.display_event_coc", event_id=event.id), follow_redirects=True)
         self.assertTrue("Code of Conduct" in rv.data, msg=rv.data)
 def test_add_user_to_trash(self):
     user = User(password="******",
                 email="*****@*****.**",
                 in_trash=False)
     with app.test_request_context():
         save_to_db(user, "User saved")
         trash_user(1)
         self.assertEqual(user.in_trash, True)
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 test_published_event_view(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         event.state = 'Published'
         save_to_db(event, "Event Saved")
         rv = self.app.get(url_for('event_detail.display_event_detail_home', identifier=event.identifier),
                           follow_redirects=True)
         self.assertTrue("Open Event" in rv.data, msg=rv.data)
Ejemplo n.º 28
0
 def test_session_reject(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event Saved")
         session = ObjectMother.get_session()
         save_to_db(session, "Session Saved")
         url = url_for('event_sessions.reject_session', event_id=1, session_id=session.id)
         rv = self.app.get(url, follow_redirects=True)
         self.assertTrue("The session has been rejected" in rv.data, msg=rv.data)
 def test_basic_page(self):
     with app.test_request_context():
         page = Page(name='abc', url='abc')
         save_to_db(page)
         page2 = Page(name='def', url='http://def.com')
         save_to_db(page2)
     resp = self.app.get('/sitemaps/pages.xml.gz')
     #self.assertIn('localhost/abc', resp.data)
     self.assertIn('<loc>http://def.com', resp.data)
Ejemplo n.º 30
0
 def test_session_create(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event saved")
         custom_form = ObjectMother.get_custom_form(event.id)
         save_to_db(custom_form, "Custom form saved")
         url = url_for('event_sessions.create_view', event_id=event.id)
         rv = self.app.get(url, follow_redirects=True)
         self.assertTrue("Create Session" in rv.data, msg=rv.data)
Ejemplo n.º 31
0
 def test_add_microlocation_to_db(self):
     microlocation = ObjectMother.get_microlocation()
     with app.test_request_context():
         save_to_db(microlocation, "Microlocation saved")
         self.assertEqual(microlocation.id, 1)
         self.assertEqual(microlocation.event_id, 1)
Ejemplo n.º 32
0
def add_event_identifier():
    events = Event.query.all()
    for event in events:
        event.identifier = get_new_event_identifier()
        save_to_db(event)
    def index_view(self):
        if request.method == 'POST':
            if 'super_admin_email' in request.form:
                super_admin = DataGetter.get_super_admin_user()
                super_admin.email = request.form['super_admin_email']
                save_to_db(super_admin)
            if 'event-thumbnail_width' in request.form:
                im_size_profile = DataGetter.get_image_sizes_by_type(type='profile')
                im_size_event = DataGetter.get_image_sizes_by_type(type='event')
                if im_size_profile and im_size_event:
                    im_size_profile.full_width = request.form['profile-large_width']
                    im_size_profile.full_height = request.form['profile-large_width']
                    im_size_profile.full_aspect = request.form.get('profile-large_aspect', 'off')
                    im_size_profile.full_quality = request.form['profile-large_quality']
                    im_size_profile.icon_width = request.form['profile-icon_width']
                    im_size_profile.icon_height = request.form['profile-icon_width']
                    im_size_profile.icon_aspect = request.form.get('profile-icon_aspect', 'off')
                    im_size_profile.icon_quality = request.form['profile-icon_quality']
                    im_size_profile.thumbnail_width = request.form['profile-thumbnail_width']
                    im_size_profile.thumbnail_height = request.form['profile-thumbnail_width']
                    im_size_profile.thumbnail_aspect = request.form.get('profile-thumbnail_aspect', 'off')
                    im_size_profile.thumbnail_quality = request.form['profile-thumbnail_quality']
                    im_size_profile.logo_width = None
                    im_size_profile.logo_height = None
                    save_to_db(im_size_profile, "Image Sizes saved")
                    im_size_event.full_width = request.form['event-large_width']
                    im_size_event.full_height = request.form['event-large_height']
                    im_size_event.full_aspect = request.form.get('event-large_aspect', 'off')
                    im_size_event.full_quality = request.form['event-large_quality']
                    im_size_event.icon_width = request.form['event-icon_width']
                    im_size_event.icon_height = request.form['event-icon_height']
                    im_size_event.icon_aspect = request.form.get('event-icon_aspect', 'off')
                    im_size_event.icon_quality = request.form['event-icon_quality']
                    im_size_event.thumbnail_width = request.form['event-thumbnail_width']
                    im_size_event.thumbnail_height = request.form['event-thumbnail_height']
                    im_size_event.thumbnail_aspect = request.form.get('event-thumbnail_aspect', 'off')
                    im_size_event.thumbnail_quality = request.form['event-thumbnail_quality']
                    im_size_event.logo_width = request.form['logo_width']
                    im_size_event.logo_height = request.form['logo_height']
                    save_to_db(im_size_event, "Image Sizes saved")
                else:
                    all_im_sizes = DataGetter.get_image_sizes()
                    for sizes in all_im_sizes:
                        delete_from_db(sizes, 'Delete Image Sizes')

                    im_size = ImageSizes(type='profile',
                                         full_width=request.form['profile-large_width'],
                                         full_height=request.form['profile-large_width'],
                                         full_aspect=request.form.get('profile-large_aspect', 'off'),
                                         full_quality=request.form['profile-large_quality'],
                                         icon_width=request.form['profile-icon_width'],
                                         icon_height=request.form['profile-icon_width'],
                                         icon_aspect=request.form.get('profile-icon_aspect', 'off'),
                                         icon_quality=request.form['profile-icon_quality'],
                                         thumbnail_width=request.form['profile-thumbnail_width'],
                                         thumbnail_height=request.form['profile-thumbnail_width'],
                                         thumbnail_aspect=request.form.get('profile-thumbnail_aspect', 'off'),
                                         thumbnail_quality=request.form['profile-thumbnail_quality'],
                                         logo_width=None,
                                         logo_height=None)
                    save_to_db(im_size, "Image Sizes saved")
                    im_size = ImageSizes(type='event',
                                         full_width=request.form['event-large_width'],
                                         full_height=request.form['event-large_height'],
                                         full_aspect=request.form.get('event-large_aspect', 'off'),
                                         full_quality=request.form['profile-large_quality'],
                                         icon_width=request.form['event-icon_width'],
                                         icon_height=request.form['event-icon_height'],
                                         icon_aspect=request.form.get('event-icon_aspect', 'off'),
                                         icon_quality=request.form['profile-icon_quality'],
                                         thumbnail_width=request.form['event-thumbnail_width'],
                                         thumbnail_height=request.form['event-thumbnail_height'],
                                         thumbnail_aspect=request.form.get('event-thumbnail_aspect', 'off'),
                                         thumbnail_quality=request.form['profile-thumbnail_quality'],
                                         logo_width=request.form['logo_width'],
                                         logo_height=request.form['logo_height'])
                    save_to_db(im_size, "Image Sizes saved")

            if 'service_fee' in request.form:
                dic = ImmutableMultiDict(request.form)
            else:
                dic = dict(request.form.copy())
                for i in dic:
                    v = dic[i][0]
                    if not v:
                        dic[i] = None
                    else:
                        dic[i] = v
            set_settings(**dic)

        settings = get_settings()
        fees = DataGetter.get_fee_settings()
        event_view = EventsView()
        image_config = DataGetter.get_image_configs()
        event_image_sizes = DataGetter.get_image_sizes_by_type(type='event')
        profile_image_sizes = DataGetter.get_image_sizes_by_type(type='profile')

        return self.render(
            '/gentelella/admin/super_admin/settings/settings.html',
            settings=settings,
            fees=fees,
            payment_currencies=DataGetter.get_payment_currencies(),
            included_settings=event_view.get_module_settings(),
            image_config=image_config,
            super_admin_email=DataGetter.get_super_admin_user().email,
            event_image_sizes=event_image_sizes,
            profile_image_sizes=profile_image_sizes
        )
Ejemplo n.º 34
0
def save_event_from_json(json, event_id=None):
    """
    Save an event from a wizard json
    :param event_id:
    :param json:
    :return:
    """
    cache.delete('event_locations')
    event_data = json['event']
    state = json['state']

    if event_id and represents_int(event_id):
        event = DataGetter.get_event(event_id)
        is_edit = True
    else:
        event = Event()
        is_edit = False

    start_time = get_event_time_field_format(event_data, 'start_time')
    end_time = get_event_time_field_format(event_data, 'end_time')

    if event_data['name'].strip() == '' or not start_time or not end_time:
        abort(400)

    if start_time > end_time:
        abort(400)

    event.name = event_data['name']
    if event_data['event_url'].strip() != "":
        if not event_data['event_url'].startswith("http"):
            event.event_url = "https://" + event_data['event_url']
        else:
            event.event_url = event_data['event_url']
    else:
        event.event_url = ""
    event.location_name = event_data['location_name']
    event.show_map = 1 if event_data['show_map'] else 0
    event.start_time = start_time
    event.end_time = end_time
    event.timezone = event_data['timezone']
    event.description = event_data['description']
    event.privacy = event_data['privacy']
    event.type = event_data['type']
    event.topic = event_data['topic']
    event.sub_topic = event_data['sub_topic']
    event.latitude = event_data['latitude']
    event.longitude = event_data['longitude']
    event.searchable_location_name = get_searchable_location_name(event)
    event.state = state if event_data['location_name'].strip(
    ) != '' else 'Draft'

    event.organizer_description = event_data[
        'organizer_description'] if event_data['has_organizer_info'] else ''
    event.organizer_name = event_data['organizer_name'] if event_data[
        'has_organizer_info'] else ''
    event.code_of_conduct = event_data['code_of_conduct'] if event_data[
        'has_code_of_conduct'] else ''

    save_to_db(event, "Event Saved")
    record_activity('create_event', event_id=event.id)
    db.session.add(event)
    db.session.flush()
    db.session.refresh(event)

    copyright = event.copyright
    if not event.copyright:
        copyright = EventCopyright(event=event)

    year = datetime.now().year
    copyright.licence = event_data['copyright']['licence']
    _, _, licence_url, logo, _ = EVENT_LICENCES.get(copyright.licence,
                                                    ('', ) * 5)
    copyright.holder = event.organizer_name
    copyright.year = year
    copyright.logo = logo
    copyright.licence_url = licence_url

    save_social_links(event_data['social_links'], event)

    event.ticket_include = event_data['ticket_include']

    if event.ticket_include:
        event.ticket_url = url_for('event_detail.display_event_detail_home',
                                   identifier=event.identifier,
                                   _external=True)
        save_tickets(event_data['tickets'], event)
    else:
        event.ticket_url = event_data['ticket_url']

    event.discount_code_id = event_data['discount_code_id']
    event.payment_country = event_data['payment_country']
    event.payment_currency = event_data['payment_currency']
    event.pay_by_paypal = event_data['pay_by_paypal']
    event.pay_by_cheque = event_data['pay_by_cheque']
    event.pay_by_bank = event_data['pay_by_bank']
    event.pay_onsite = event_data['pay_onsite']
    event.pay_by_stripe = event_data['pay_by_stripe']

    event.cheque_details = event_data[
        'cheque_details'] if event.pay_by_cheque else ''
    event.bank_details = event_data['bank_details'] if event.pay_by_bank else ''
    event.onsite_details = event_data[
        'onsite_details'] if event.pay_onsite else ''

    if event.pay_by_paypal:
        event.paypal_email = event_data['paypal_email']
    else:
        event.paypal_email = None

    if event.pay_by_stripe and event_data['stripe']['linked']:
        stripe_data = event_data['stripe']
        stripe = event.stripe
        if not stripe:
            stripe = StripeAuthorization(event_id=event.id)

        stripe.stripe_secret_key = stripe_data['stripe_secret_key']
        stripe.stripe_refresh_token = stripe_data['stripe_refresh_token']
        stripe.stripe_publishable_key = stripe_data['stripe_publishable_key']
        stripe.stripe_user_id = stripe_data['stripe_user_id']
        stripe.stripe_email = stripe_data['stripe_email']

        db.session.add(stripe)
    else:
        if event.stripe:
            db.session.delete(event.stripe)

    event.tax_allow = bool(event_data['tax_allow'] == 1)

    if event.tax_allow:
        tax_data = event_data['tax']
        tax = event.tax
        if not tax:
            tax = Tax(event_id=event.id)

        tax.country = tax_data['country']
        tax.tax_name = tax_data['tax_name']
        tax.send_invoice = tax_data['send_invoice']
        tax.tax_id = tax_data['tax_id']
        tax.registered_company = tax_data['registered_company']
        tax.address = tax_data['address']
        tax.state = tax_data['state']
        tax.zip = tax_data['zip']
        tax.tax_include_in_price = tax_data['tax_include_in_price']
        tax.invoice_footer = tax_data['invoice_footer']
        db.session.add(tax)
    else:
        if event.tax:
            db.session.delete(event.tax)

    if event.logo != event_data['logo']:
        if event_data['logo'] and event_data['logo'].strip() != '':
            event.logo = save_logo(event_data['logo'], event.id)
        elif event.logo != '':
            event.logo = ''

    save_to_db(event)

    image_sizes = DataGetter.get_image_sizes_by_type(type='event')
    if not image_sizes:
        image_sizes = ImageSizes(full_width=1300,
                                 full_height=500,
                                 full_aspect='on',
                                 icon_width=75,
                                 icon_height=30,
                                 icon_aspect='on',
                                 thumbnail_width=500,
                                 thumbnail_height=200,
                                 thumbnail_aspect='on',
                                 type='event')
        save_to_db(image_sizes, "Image Sizes Saved")

    if event.background_url != event_data['background_url']:
        if event_data['background_url'] and event_data['background_url'].strip(
        ) != '':
            background_url = event_data['background_url']
            jpg_image = convert_background_to_jpg(background_url)
            event.background_url = save_untouched_background(
                background_url, event.id)
            event.large = save_resized_background(jpg_image, event.id, 'large',
                                                  image_sizes)
            event.thumbnail = save_resized_background(jpg_image, event.id,
                                                      'thumbnail', image_sizes)
            event.icon = save_resized_background(jpg_image, event.id, 'icon',
                                                 image_sizes)
            os.remove(jpg_image)
            save_to_db(event)
        elif event.background_url != '':
            event.background_url = ''
            event.large = ''
            event.thumbnail = ''
            event.icon = ''
            save_to_db(event)

    if not is_edit:
        role = Role.query.filter_by(name=ORGANIZER).first()
        uer = UsersEventsRoles(login.current_user, event, role)
        if save_to_db(uer, "Event saved"):
            new_email_notification_setting = EmailNotification(
                next_event=1,
                new_paper=1,
                session_schedule=1,
                session_accept_reject=1,
                after_ticket_purchase=1,
                user_id=login.current_user.id,
                event_id=event.id)
            save_to_db(new_email_notification_setting, "EmailSetting Saved")
    event_json_modified.send(current_app._get_current_object(),
                             event_id=event.id)
    return {'event_id': event.id}
Ejemplo n.º 35
0
 def test_admin_messages_edit(self):
     with app.test_request_context():
         setting = ObjectMother.get_message_settings()
         save_to_db(setting, "Message Settings Updated")
         data = DataGetter.get_message_setting_by_action("Next Event")
         self.assertEqual(1, data.mail_status, msg=data.mail_status)
 def test_add_event_to_db(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event saved")
         self.assertEqual(event.id, event.id)
Ejemplo n.º 37
0
def create_services(event_id, serial_no=''):
    """Creates services and associates them with `event_id`. Service names
    have an optional `serial_no` that can be used to make them unique.
    """
    test_micro = 'TestMicrolocation{}_{}'.format(serial_no, event_id)
    test_track = 'TestTrack{}_{}'.format(serial_no, event_id)
    test_session = 'TestSession{}_{}'.format(serial_no, event_id)
    test_speaker = 'TestSpeaker{}_{}'.format(serial_no, event_id)
    test_sponsor = 'TestSponsor{}_{}'.format(serial_no, event_id)
    test_sponsor_type = 'TestSponsorType{}_{}'.format(serial_no, event_id)
    test_session_type = 'TestSessionType{}_{}'.format(serial_no, event_id)
    test_social_link = 'TestSocialLink{}_{}'.format(serial_no, event_id)

    microlocation = Microlocation(name=test_micro, event_id=event_id)
    track = Track(
        name=test_track,
        description='descp',
        event_id=event_id,
        color='#caf034'
    )
    session_type = SessionType(
        name=test_session_type,
        length=30,
        event_id=event_id
    )
    session = Session(title=test_session,
                      long_abstract='descp',
                      start_time=datetime(2014, 8, 4, 12, 30, 45),
                      end_time=datetime(2014, 8, 4, 13, 00, 00),
                      event_id=event_id,
                      session_type=session_type)
    speaker = Speaker(name=test_speaker,
                      email='*****@*****.**',
                      organisation='org',
                      country='japan',
                      event_id=event_id)
    sponsor = Sponsor(name=test_sponsor, sponsor_type=test_sponsor_type,
                      event_id=event_id, level='level')
    social_link = SocialLink(
        name=test_social_link,
        link='http://fb.com',
        event_id=event_id
    )

    save_to_db(social_link, 'SocialLink saved')
    save_to_db(session_type, 'SessionType saved')
    save_to_db(microlocation, 'Microlocation saved')
    save_to_db(track, 'Track saved')
    save_to_db(session, 'Session saved')
    save_to_db(speaker, 'Speaker saved')
    save_to_db(sponsor, 'Sponsor saved')
Ejemplo n.º 38
0
    def import_data(file_path, creator_id, task_handle):

        with open(file_path, 'r') as xml_file:
            string = xml_file.read().replace('\n', '')

        update_status(task_handle, 'Parsing XML file')
        conference_object = PentabarfParser.parse(string)
        update_status(task_handle, 'Processing event')
        event = Event()
        event.start_time = conference_object.start
        event.end_time = conference_object.end
        event.has_session_speakers = True
        event.name = conference_object.title
        event.location_name = conference_object.venue + ', ' + conference_object.city
        event.searchable_location_name = conference_object.city
        event.state = 'Published'
        event.privacy = 'public'
        db.session.add(event)
        event_time_updated = False
        update_status(task_handle, 'Adding sessions')
        for day_object in conference_object.day_objects:
            for room_object in day_object.room_objects:
                microlocation, _ = get_or_create(Microlocation,
                                                 event_id=event.id,
                                                 name=room_object.name)
                for event_object in room_object.event_objects:
                    session_type_id = None
                    if event_object.type:
                        session_type, _ = get_or_create(SessionType,
                                                        event_id=event.id,
                                                        name=event_object.type,
                                                        length=30)
                        session_type_id = session_type.id
                    track_id = None
                    if event_object.track:
                        string_to_hash = event_object.track
                        seed = int('100'.join(
                            list(
                                str(ord(character))
                                for character in string_to_hash)))
                        random.seed(seed)
                        color = "#%06x" % random.randint(0, 0xFFFFFF)
                        track, _ = get_or_create(Track,
                                                 event_id=event.id,
                                                 name=event_object.track,
                                                 color=color)
                        track_id = track.id

                    session = Session()
                    session.track_id = track_id
                    session.microlocation_id = microlocation.id
                    session.session_type_id = session_type_id
                    session.title = event_object.title
                    session.short_abstract = event_object.abstract
                    session.long_abstract = event_object.description
                    session.level = event_object.level
                    session.start_time = event_object.date + string_to_timedelta(
                        event_object.start)
                    session.end_time = session.start_time + string_to_timedelta(
                        event_object.duration)
                    session.slides = event_object.slides_url
                    session.video = event_object.video_url
                    session.audio = event_object.audio_url
                    session.signup_url = event_object.conf_url
                    session.event_id = event.id
                    session.state = 'accepted'
                    session.speakers = []
                    save_to_db(session, 'Session Updated')

                    if not event_time_updated:
                        event.start_time = None
                        event.end_time = None
                        event_time_updated = True

                    if not event.start_time or session.start_time < event.start_time:
                        event.start_time = session.start_time
                    if not event.end_time or session.end_time > event.end_time:
                        event.end_time = session.end_time

                    for person_object in event_object.person_objects:
                        name_mix = person_object.name + ' ' + conference_object.title
                        email = ''.join(x for x in name_mix.title()
                                        if not x.isspace()) + '@example.com'
                        speaker = Speaker(name=person_object.name,
                                          event_id=event.id,
                                          email=email,
                                          country='Earth',
                                          organisation='')
                        db.session.add(speaker)
                        session.speakers.append(speaker)
                        db.session.commit()

                    update_status(task_handle,
                                  'Added session "' + session.title + '"')

        update_status(task_handle, 'Saving data')
        save_to_db(event)
        update_status(task_handle, 'Finalizing')
        own_event(event=event, user_id=creator_id)
        return event
Ejemplo n.º 39
0
    def initiate_order_payment(form, paid_via=None):
        identifier = form['identifier']
        email = form['email']

        order = TicketingManager.get_and_set_expiry(identifier)

        if order:
            user = DataGetter.get_or_create_user_by_email(email, form)
            order.user_id = user.id
            if not order.user.user_detail.firstname and not order.user.user_detail.lastname:
                order.user.user_detail.firstname = form['firstname']
                order.user.user_detail.lastname = form['lastname']

            if order.amount > 0 \
                and (not order.paid_via
                     or (order.paid_via
                         and (order.paid_via == 'stripe'
                              or order.paid_via == 'paypal'))):

                if paid_via:
                    order.paid_via = paid_via

                country = form['country']
                address = form['address']
                city = form['city']
                state = form['state']
                zipcode = form['zipcode']
                order.address = address
                order.city = city
                order.state = state
                order.country = country
                order.zipcode = zipcode

                if paid_via == 'transfer' or paid_via == 'onsite' or paid_via == 'cheque':
                    order.status = 'placed'
                else:
                    order.status = 'initialized'

            else:
                order.status = 'completed'
                order.completed_at = datetime.utcnow()
                if not order.paid_via:
                    order.paid_via = 'free'

            invoice_id = order.get_invoice_number()
            order_url = url_for('ticketing.view_order_after_payment',
                                order_identifier=order.identifier,
                                _external=True)

            # add holders to user
            holders_firstnames = form.getlist('holders[firstname]')
            holders_lastnames = form.getlist('holders[lastname]')
            holders_ticket_ids = form.getlist('holders[ticket_id]')
            holders_emails = form.getlist('holders[email]')

            for i, firstname in enumerate(holders_firstnames):
                data = {
                    'firstname': firstname,
                    'lastname': holders_lastnames[i]
                }
                holder_user = DataGetter.get_or_create_user_by_email(
                    holders_emails[i], data)
                ticket_holder = TicketHolder(firstname=data['firstname'],
                                             lastname=data['lastname'],
                                             ticket_id=int(
                                                 holders_ticket_ids[i]),
                                             email=holder_user.email,
                                             order_id=order.id)
                if data['firstname'] == '' or data[
                        'lastname'] == '' or holder_user.email == '':
                    return abort(400)
                if order.status == "completed":
                    send_email_for_after_purchase(holder_user.email,
                                                  invoice_id, order_url,
                                                  order.event.name,
                                                  order.event.organizer_name)
                DataManager.add_attendee_role_to_event(holder_user,
                                                       order.event_id)
                db.session.add(ticket_holder)

            # add attendee role to user
            if order.status == "completed":
                trigger_after_purchase_notifications(email, order.event_id,
                                                     order.event, invoice_id,
                                                     order_url)
                send_email_for_after_purchase(email, invoice_id, order_url,
                                              order.event.name,
                                              order.event.organizer_name)
            DataManager.add_attendee_role_to_event(user, order.event_id)
            # save items
            save_to_db(order)
            return order
        else:
            return False
Ejemplo n.º 40
0
    def get_checkout_url(order_invoice, currency=None, credentials=None):
        if not credentials:
            credentials = PayPalPaymentsManager.get_credentials(
                order_invoice.event)

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

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

        if not currency:
            currency = order_invoice.event.payment_currency

        if not currency or currency == "":
            currency = "USD"

        data = {
            'USER':
            credentials['USER'],
            'PWD':
            credentials['PWD'],
            'SIGNATURE':
            credentials['SIGNATURE'],
            'METHOD':
            'SetExpressCheckout',
            'VERSION':
            PayPalPaymentsManager.api_version,
            'PAYMENTREQUEST_0_PAYMENTACTION':
            'SALE',
            'PAYMENTREQUEST_0_AMT':
            order_invoice.amount,
            'PAYMENTREQUEST_0_CURRENCYCODE':
            currency,
            'RETURNURL':
            url_for('ticketing.paypal_callback',
                    order_identifier=order_invoice.identifier,
                    function='success',
                    _external=True),
            'CANCELURL':
            url_for('ticketing.paypal_callback',
                    order_identifier=order_invoice.identifier,
                    function='cancel',
                    _external=True)
        }

        if type(order_invoice) is Order:
            data['SUBJECT'] = credentials['EMAIL']
            data['RETURNURL'] = url_for(
                'ticketing.paypal_callback',
                order_identifier=order_invoice.identifier,
                function='success',
                _external=True),
            data['CANCELURL'] = url_for(
                'ticketing.paypal_callback',
                order_identifier=order_invoice.identifier,
                function='cancel',
                _external=True)

        else:
            data['RETURNURL'] = url_for(
                'event_invoicing.paypal_callback',
                invoice_identifier=order_invoice.identifier,
                function='success',
                _external=True),
            data['CANCELURL'] = url_for(
                'event_invoicing.paypal_callback',
                invoice_identifier=order_invoice.identifier,
                function='cancel',
                _external=True)

        count = 1

        if type(order_invoice) is Order:
            for ticket_order in order_invoice.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)
        token = dict(urlparse.parse_qsl(response.text))['TOKEN']
        order_invoice.paypal_token = token
        save_to_db(order_invoice)
        return credentials['CHECKOUT_URL'] + "?" + urlencode({
            'cmd': '_express-checkout',
            'token': token
        })
Ejemplo n.º 41
0
def save_speaker(request, event_id=None, speaker=None, user=None, no_name=False):
    if not speaker and not event_id:
        raise Exception('event_id or speaker is required')

    from app.helpers.data import save_to_db, record_activity

    if not speaker:
        if no_name:
            speaker = Speaker(
                event_id=event_id,
                user=user,
                name='',
                email=trim_get_form(request.form, 'email', None)
            )
        else:
            speaker = Speaker(
                event_id=event_id,
                user=user,
                name=trim_get_form(request.form, 'name', None),
                email=trim_get_form(request.form, 'email', None)
            )
        save_to_db(speaker)

    speaker.email = trim_get_form(request.form, 'email', None)
    if trim_get_form(request.form, 'name', None):
        speaker.name = trim_get_form(request.form, 'name', None)

    if not speaker.user:
        if user:
            speaker.user = user
        else:
            speaker.user = DataGetter.get_or_create_user_by_email(speaker.email, {
                'firstname': speaker.name,
                'lastname': ''
            })

    if not event_id:
        event_id = speaker.event_id

    image_sizes = speaker_image_sizes()

    photo = trim_get_form(request.form, 'photo', None)
    if photo and photo.strip() != '':
        if speaker.photo != photo:
            file_path = get_path_of_temp_url(photo)
            speaker.photo = save_untouched_photo(photo, event_id, speaker.id)
            speaker.small = save_resized_photo(file_path, event_id, speaker.id, 'small', image_sizes)
            speaker.thumbnail = save_resized_photo(file_path, event_id, speaker.id, 'thumbnail', image_sizes)
            speaker.icon = save_resized_photo(file_path, event_id, speaker.id, 'icon', image_sizes)
    else:
        speaker.photo = ''
        speaker.small = ''
        speaker.thumbnail = ''
        speaker.icon = ''

    speaker.short_biography = trim_get_form(request.form, 'short_biography', None)
    speaker.long_biography = trim_get_form(request.form, 'long_biography', None)
    speaker.mobile = trim_get_form(request.form, 'mobile', None)
    speaker.website = trim_get_form(request.form, 'website', None)
    speaker.twitter = trim_get_form(request.form, 'twitter', None)
    speaker.facebook = trim_get_form(request.form, 'facebook', None)
    speaker.github = trim_get_form(request.form, 'github', None)
    speaker.linkedin = trim_get_form(request.form, 'linkedin', None)
    speaker.organisation = trim_get_form(request.form, 'organisation', None)
    speaker.featured = True if trim_get_form(request.form, 'featured', 'false') == 'true' else False
    speaker.position = trim_get_form(request.form, 'position', None)
    speaker.country = trim_get_form(request.form, 'country', None)
    speaker.city = trim_get_form(request.form, 'city', None)
    speaker.gender = trim_get_form(request.form, 'gender', None)
    if trim_get_form(request.form, 'heard_from', None) == "Other":
        speaker.heard_from = trim_get_form(request.form, 'other_text', None)
    else:
        speaker.heard_from = trim_get_form(request.form, 'heard_from', None)
    speaker.sponsorship_required = trim_get_form(request.form, 'sponsorship_required', None)
    speaker.speaking_experience = trim_get_form(request.form, 'speaking_experience', None)
    speakers_modified.send(app._get_current_object(), event_id=event_id)
    save_to_db(speaker, "Speaker has been updated")
    record_activity('update_speaker', speaker=speaker, event_id=event_id)
    return speaker
 def test_get_session_by_id(self):
     session = ObjectMother.get_session()
     with app.test_request_context():
         save_to_db(session, "Session saved")
         response = self.app.get('/api/v1/event/sessions/1')
         self.assertEqual(response.status_code, 200)
Ejemplo n.º 43
0
 def test_add_session_to_db(self):
     session = ObjectMother.get_session()
     with app.test_request_context():
         save_to_db(session, "Session saved")
         self.assertEqual(session.id, 1)
         self.assertEqual(session.event_id, 1)
def create_import_job(task):
    """create import record in db"""
    ij = ImportJob(task=task, user=g.user)
    save_to_db(ij, 'Import job saved')
Ejemplo n.º 45
0
 def publish(self, event_id):
     event = DataGetter.get_event(event_id)
     event.schedule_published_on = datetime.now()
     save_to_db(event, "Event schedule published")
     flash('The schedule has been published for this event', 'success')
     return redirect(url_for('.display_view', event_id=event_id))
Ejemplo n.º 46
0
def edit_view(event_id, speaker_id):
    speaker = get_speaker_or_throw(speaker_id)
    event = DataGetter.get_event(event_id)
    form_elems = DataGetter.get_custom_form_elements(event_id)
    if not form_elems:
        flash(
            "Speaker form has been incorrectly configured for this event. Editing has been disabled",
            "danger")
        return redirect(url_for('.index_view', event_id=event_id))
    speaker_form = json.loads(form_elems.speaker_form)
    if request.method == 'GET':
        return render_template('gentelella/admin/event/speakers/edit.html',
                               speaker=speaker,
                               event_id=event_id,
                               event=event,
                               speaker_form=speaker_form)
    if request.method == 'POST':
        # set photo
        if 'photo' in request.files and request.files['photo'].filename != '':
            speaker_img_file = request.files['photo']
            speaker_img = upload(
                speaker_img_file, UPLOAD_PATHS['speakers']['photo'].format(
                    event_id=int(event_id), id=int(speaker.id)))
            speaker.photo = speaker_img
        logo = request.form.get('photo', None)
        print logo
        if logo != '' and logo:
            filename = '{}.png'.format(time.time())
            filepath = '{}/static/{}'.format(path.realpath('.'),
                                             logo[len('/serve_static/'):])
            logo_file = UploadedFile(filepath, filename)
            print logo_file
            logo = upload(
                logo_file, 'events/%d/speakers/%d/photo' %
                (int(event_id), int(speaker.id)))
            speaker.photo = logo
            image_sizes = DataGetter.get_image_sizes_by_type(type='profile')
            if not image_sizes:
                image_sizes = ImageSizes(full_width=150,
                                         full_height=150,
                                         icon_width=35,
                                         icon_height=35,
                                         thumbnail_width=50,
                                         thumbnail_height=50,
                                         type='profile')
            save_to_db(image_sizes, "Image Sizes Saved")
            filename = '{}.jpg'.format(time.time())
            filepath = '{}/static/{}'.format(path.realpath('.'),
                                             logo[len('/serve_static/'):])
            logo_file = UploadedFile(filepath, filename)

            temp_img_file = upload_local(
                logo_file, 'events/{event_id}/speakers/{id}/temp'.format(
                    event_id=int(event_id), id=int(speaker.id)))
            temp_img_file = temp_img_file.replace('/serve_', '')

            basewidth = image_sizes.full_width
            img = Image.open(temp_img_file)
            hsize = image_sizes.full_height
            img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
            img.save(temp_img_file)
            file_name = temp_img_file.rsplit('/', 1)[1]
            large_file = UploadedFile(file_path=temp_img_file,
                                      filename=file_name)
            profile_thumbnail_url = upload(
                large_file, UPLOAD_PATHS['speakers']['thumbnail'].format(
                    event_id=int(event_id), id=int(speaker.id)))

            basewidth = image_sizes.thumbnail_width
            img = Image.open(temp_img_file)
            hsize = image_sizes.thumbnail_height
            img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
            img.save(temp_img_file)
            file_name = temp_img_file.rsplit('/', 1)[1]
            thumbnail_file = UploadedFile(file_path=temp_img_file,
                                          filename=file_name)
            profile_small_url = upload(
                thumbnail_file, UPLOAD_PATHS['speakers']['small'].format(
                    event_id=int(event_id), id=int(speaker.id)))

            basewidth = image_sizes.icon_width
            img = Image.open(temp_img_file)
            hsize = image_sizes.icon_height
            img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
            img.save(temp_img_file)
            file_name = temp_img_file.rsplit('/', 1)[1]
            icon_file = UploadedFile(file_path=temp_img_file,
                                     filename=file_name)
            profile_icon_url = upload(
                icon_file,
                UPLOAD_PATHS['speakers']['icon'].format(event_id=int(event_id),
                                                        id=int(speaker.id)))
            shutil.rmtree(path='static/media/' +
                          'events/{event_id}/speakers/{id}/temp'.format(
                              event_id=int(event_id), id=int(speaker.id)))
            speaker.thumbnail = profile_thumbnail_url
            speaker.small = profile_small_url
            speaker.icon = profile_icon_url
            save_to_db(speaker, "Speaker photo saved")
        # set other fields
        speaker.name = request.form.get('name', None)
        speaker.short_biography = request.form.get('short_biography', None)
        speaker.long_biography = request.form.get('long_biography', None)
        speaker.email = request.form.get('email', None)
        speaker.mobile = request.form.get('mobile', None)
        speaker.website = request.form.get('website', None)
        speaker.twitter = request.form.get('twitter', None)
        speaker.facebook = request.form.get('facebook', None)
        speaker.github = request.form.get('github', None)
        speaker.linkedin = request.form.get('linkedin', None)
        speaker.organisation = request.form.get('organisation', None)
        speaker.featured = True if request.form.get(
            'featured', 'false') == 'true' else False
        speaker.position = request.form.get('position', None)
        speaker.country = request.form.get('country', None)
        save_to_db(speaker, "Speaker has been updated")
        flash("Speaker has been saved", "success")

    return redirect(url_for('.index_view', event_id=event_id))
    def create_order(form, from_organizer=False):
        order = Order()
        order.status = 'pending'
        order.identifier = TicketingManager.get_new_order_identifier()
        order.event_id = form.get('event_id')

        if from_organizer:
            order.paid_via = form.get('payment_via')

        ticket_ids = form.getlist('ticket_ids[]')
        ticket_quantity = form.getlist('ticket_quantities[]')
        ticket_discount = form.get('promo_code', '')
        discount = None
        if ticket_discount:
            discount = TicketingManager.get_discount_code(
                form.get('event_id'), form.get('promo_code', ''))
            access_code = TicketingManager.get_access_code(
                form.get('event_id'), form.get('promo_code', ''))
            if access_code and discount:
                order.discount_code = discount
                flash(
                    'Both access code and discount code have been applied. You can make this order now.',
                    'success')
            elif discount:
                order.discount_code = discount
                flash(
                    'The promotional code entered is valid. Offer has been applied to this order.',
                    'success')
            elif access_code:
                flash(
                    'Your access code is applied and you can make this order now.',
                    'success')
            else:
                flash(
                    'The promotional code entered is not valid. No offer has been applied to this order.',
                    'danger')

        ticket_subtotals = []
        if from_organizer:
            ticket_subtotals = form.getlist('ticket_subtotals[]')

        amount = 0
        total_discount = 0
        fees = DataGetter.get_fee_settings_by_currency(
            DataGetter.get_event(order.event_id).payment_currency)
        for index, id in enumerate(ticket_ids):
            if not string_empty(id) and int(ticket_quantity[index]) > 0:
                with db.session.no_autoflush:
                    order_ticket = OrderTicket()
                    order_ticket.ticket = TicketingManager.get_ticket(id)
                    order_ticket.quantity = int(ticket_quantity[index])
                    order.tickets.append(order_ticket)

                    if order_ticket.ticket.absorb_fees or not fees:
                        ticket_amount = (order_ticket.ticket.price *
                                         order_ticket.quantity)
                        amount += (order_ticket.ticket.price *
                                   order_ticket.quantity)
                    else:
                        order_fee = fees.service_fee * (
                            order_ticket.ticket.price *
                            order_ticket.quantity) / 100
                        if order_fee > fees.maximum_fee:
                            ticket_amount = (
                                order_ticket.ticket.price *
                                order_ticket.quantity) + fees.maximum_fee
                            amount += (
                                order_ticket.ticket.price *
                                order_ticket.quantity) + fees.maximum_fee
                        else:
                            ticket_amount = (order_ticket.ticket.price *
                                             order_ticket.quantity) + order_fee
                            amount += (order_ticket.ticket.price *
                                       order_ticket.quantity) + order_fee

                    if from_organizer:
                        amount += float(ticket_subtotals[index])
                    else:
                        if discount and str(order_ticket.ticket.id
                                            ) in discount.tickets.split(","):
                            if discount.type == "amount":
                                total_discount += discount.value * order_ticket.quantity
                            else:
                                total_discount += discount.value * ticket_amount / 100

        if discount:
            order.amount = max(amount - total_discount, 0)
        elif discount:
            order.amount = amount - (discount.value * amount / 100.0)
        else:
            order.amount = amount

        if login.current_user.is_authenticated:
            order.user_id = login.current_user.id

        save_to_db(order)
        return order
 def test_event_page(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event)
         resp = self.app.get('/sitemaps/events/1.xml.gz')
         self.assertIn('/' + str(event.identifier) + '/', resp.data)
Ejemplo n.º 49
0
 def test_scheduler_view(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event, "Event saved")
         rv = self.app.get(url_for('event_scheduler.display_view', event_id=event.id), follow_redirects=True)
         self.assertTrue("Scheduler" in rv.data, msg=rv.data)
Ejemplo n.º 50
0
def unpublish(event_id):
    event = DataGetter.get_event(event_id)
    event.schedule_published_on = None
    save_to_db(event, "Event schedule unpublished")
    flash('The schedule has been unpublished for this event', 'success')
    return redirect(url_for('.display_view', event_id=event_id))
def _upload_media(task_handle, event_id, base_path):
    """
    Actually uploads the resources
    """
    global UPLOAD_QUEUE
    total = len(UPLOAD_QUEUE)
    ct = 0

    for i in UPLOAD_QUEUE:
        # update progress
        ct += 1
        update_state(task_handle, 'Uploading media (%d/%d)' % (ct, total))
        # get upload infos
        name, dao = i['srv']
        id_ = i['id']
        if name == 'event':
            item = dao.get(event_id)
        else:
            item = dao.get(event_id, id_)
        # get cur file
        field = i['field']
        path = getattr(item, field)
        if path.startswith('/'):
            # relative files
            path = base_path + path
            if os.path.isfile(path):
                filename = path.rsplit('/', 1)[1]
                file = UploadedFile(path, filename)
            else:
                file = ''  # remove current file setting
        else:
            # absolute links
            try:
                filename = UPLOAD_PATHS[name][field].rsplit('/', 1)[1]
                if is_downloadable(path):
                    r = requests.get(path, allow_redirects=True)
                    file = UploadedMemory(r.content, filename)
                else:
                    file = None
            except:
                file = None
        # don't update current file setting
        if file is None:
            continue
        # upload
        try:
            if file == '':
                raise Exception()
            key = UPLOAD_PATHS[name][field]
            if name == 'event':
                key = key.format(event_id=event_id)
            else:
                key = key.format(event_id=event_id, id=id_)
            print key
            new_url = upload(file, key)
        except Exception:
            print traceback.format_exc()
            new_url = None
        setattr(item, field, new_url)
        save_to_db(item, msg='Url updated')
    # clear queue
    UPLOAD_QUEUE = []
    return
def index_view():
    if request.method == 'POST':
        if 'super_admin_email' in request.form:
            super_admin = DataGetter.get_super_admin_user()
            super_admin.email = request.form['super_admin_email']
            save_to_db(super_admin)
        if 'event-thumbnail_width' in request.form:
            im_size_profile = DataGetter.get_image_sizes_by_type(
                type='profile')
            im_size_event = DataGetter.get_image_sizes_by_type(type='event')
            if im_size_profile and im_size_event:
                im_size_profile.full_width = request.form[
                    'profile-large_width']
                im_size_profile.full_height = request.form[
                    'profile-large_width']
                im_size_profile.full_aspect = request.form.get(
                    'profile-large_aspect', 'off')
                im_size_profile.full_quality = request.form[
                    'profile-large_quality']
                im_size_profile.icon_width = request.form['profile-icon_width']
                im_size_profile.icon_height = request.form[
                    'profile-icon_width']
                im_size_profile.icon_aspect = request.form.get(
                    'profile-icon_aspect', 'off')
                im_size_profile.icon_quality = request.form[
                    'profile-icon_quality']
                im_size_profile.thumbnail_width = request.form[
                    'profile-thumbnail_width']
                im_size_profile.thumbnail_height = request.form[
                    'profile-thumbnail_width']
                im_size_profile.thumbnail_aspect = request.form.get(
                    'profile-thumbnail_aspect', 'off')
                im_size_profile.thumbnail_quality = request.form[
                    'profile-thumbnail_quality']
                im_size_profile.logo_width = None
                im_size_profile.logo_height = None
                save_to_db(im_size_profile, "Image Sizes saved")
                im_size_event.full_width = request.form['event-large_width']
                im_size_event.full_height = request.form['event-large_height']
                im_size_event.full_aspect = request.form.get(
                    'event-large_aspect', 'off')
                im_size_event.full_quality = request.form[
                    'event-large_quality']
                im_size_event.icon_width = request.form['event-icon_width']
                im_size_event.icon_height = request.form['event-icon_height']
                im_size_event.icon_aspect = request.form.get(
                    'event-icon_aspect', 'off')
                im_size_event.icon_quality = request.form['event-icon_quality']
                im_size_event.thumbnail_width = request.form[
                    'event-thumbnail_width']
                im_size_event.thumbnail_height = request.form[
                    'event-thumbnail_height']
                im_size_event.thumbnail_aspect = request.form.get(
                    'event-thumbnail_aspect', 'off')
                im_size_event.thumbnail_quality = request.form[
                    'event-thumbnail_quality']
                im_size_event.logo_width = request.form['logo_width']
                im_size_event.logo_height = request.form['logo_height']
                save_to_db(im_size_event, "Image Sizes saved")
            else:
                all_im_sizes = DataGetter.get_image_sizes()
                for sizes in all_im_sizes:
                    delete_from_db(sizes, 'Delete Image Sizes')

                im_size = ImageSizes(
                    type='profile',
                    full_width=request.form['profile-large_width'],
                    full_height=request.form['profile-large_width'],
                    full_aspect=request.form.get('profile-large_aspect',
                                                 'off'),
                    full_quality=request.form['profile-large_quality'],
                    icon_width=request.form['profile-icon_width'],
                    icon_height=request.form['profile-icon_width'],
                    icon_aspect=request.form.get('profile-icon_aspect', 'off'),
                    icon_quality=request.form['profile-icon_quality'],
                    thumbnail_width=request.form['profile-thumbnail_width'],
                    thumbnail_height=request.form['profile-thumbnail_width'],
                    thumbnail_aspect=request.form.get(
                        'profile-thumbnail_aspect', 'off'),
                    thumbnail_quality=request.
                    form['profile-thumbnail_quality'],
                    logo_width=None,
                    logo_height=None)
                save_to_db(im_size, "Image Sizes saved")
                im_size = ImageSizes(
                    type='event',
                    full_width=request.form['event-large_width'],
                    full_height=request.form['event-large_height'],
                    full_aspect=request.form.get('event-large_aspect', 'off'),
                    full_quality=request.form['profile-large_quality'],
                    icon_width=request.form['event-icon_width'],
                    icon_height=request.form['event-icon_height'],
                    icon_aspect=request.form.get('event-icon_aspect', 'off'),
                    icon_quality=request.form['profile-icon_quality'],
                    thumbnail_width=request.form['event-thumbnail_width'],
                    thumbnail_height=request.form['event-thumbnail_height'],
                    thumbnail_aspect=request.form.get('event-thumbnail_aspect',
                                                      'off'),
                    thumbnail_quality=request.
                    form['profile-thumbnail_quality'],
                    logo_width=request.form['logo_width'],
                    logo_height=request.form['logo_height'])
                save_to_db(im_size, "Image Sizes saved")

        if 'service_fee' in request.form:
            dic = ImmutableMultiDict(request.form)
        else:
            dic = dict(request.form.copy())
            for i in dic:
                v = dic[i][0]
                if not v:
                    dic[i] = None
                else:
                    dic[i] = v
        set_settings(**dic)

    settings = get_settings()
    fees = DataGetter.get_fee_settings()
    image_config = DataGetter.get_image_configs()
    event_image_sizes = DataGetter.get_image_sizes_by_type(type='event')
    profile_image_sizes = DataGetter.get_image_sizes_by_type(type='profile')

    if current_app.config['PRODUCTION']:
        settings['app_environment'] = Environment.PRODUCTION
    elif current_app.config['STAGING']:
        settings['app_environment'] = Environment.STAGING
    elif current_app.config['DEVELOPMENT']:
        settings['app_environment'] = Environment.DEVELOPMENT

    return render_template(
        'gentelella/super_admin/settings/settings.html',
        settings=settings,
        fees=fees,
        s3_regions=boto.s3.regions(),
        payment_currencies=DataGetter.get_payment_currencies(),
        included_settings=get_module_settings(),
        image_config=image_config,
        super_admin_email=DataGetter.get_super_admin_user().email,
        event_image_sizes=event_image_sizes,
        profile_image_sizes=profile_image_sizes,
        navigation_bar=list_navbar())
    def initiate_order_payment(form, paid_via=None):
        identifier = form['identifier']
        email = form['email']

        order = TicketingManager.get_and_set_expiry(identifier)

        if order:

            user = TicketingManager.get_or_create_user_by_email(email, form)
            order.user_id = user.id

            if order.amount > 0 \
                and (not order.paid_via
                     or (order.paid_via
                         and (order.paid_via == 'stripe'
                              or order.paid_via == 'paypal'))):

                if paid_via:
                    order.paid_via = paid_via

                country = form['country']
                address = form['address']
                city = form['city']
                state = form['state']
                zipcode = form['zipcode']
                order.address = address
                order.city = city
                order.state = state
                order.country = country
                order.zipcode = zipcode

                if paid_via == 'transfer' or paid_via == 'onsite' or paid_via == 'cheque':
                    order.status = 'placed'
                else:
                    order.status = 'initialized'

            else:
                order.status = 'completed'
                order.completed_at = datetime.utcnow()
                if not order.paid_via:
                    order.paid_via = 'free'

            holders_firstnames = form.getlist('holders[firstname]')
            holders_lastnames = form.getlist('holders[lastname]')
            holders_ticket_ids = form.getlist('holders[ticket_id]')
            holders_emails = form.getlist('holders[email]')

            for i, firstname in enumerate(holders_firstnames):
                data = {
                    'firstname': firstname,
                    'lastname': holders_lastnames[i]
                }
                holder_user = TicketingManager.get_or_create_user_by_email(
                    holders_emails[i], data)
                ticket_holder = TicketHolder(firstname=data['firstname'],
                                             lastname=data['lastname'],
                                             ticket_id=int(
                                                 holders_ticket_ids[i]),
                                             email=holder_user.email,
                                             order_id=order.id)
                DataManager.add_attendee_role_to_event(holder_user,
                                                       order.event_id)
                db.session.add(ticket_holder)

            # add attendee role to user
            DataManager.add_attendee_role_to_event(user, order.event_id)
            # save items
            save_to_db(order)
            return order
        else:
            return False
Ejemplo n.º 54
0
def save_db_model(new_model, model_name, event_id=None):
    """
    Save a new/modified model to database
    """
    save_to_db(new_model, "Model %s saved" % model_name)
    return new_model
 def test_index_with_event(self):
     with app.test_request_context():
         event = ObjectMother.get_event()
         save_to_db(event)
     resp = self.app.get('/sitemap.xml')
     self.assertIn('1.xml.gz', resp.data)
Ejemplo n.º 56
0
    def import_data(file_path, creator_id, task_handle):
        update_status(task_handle, 'Parsing iCal file')
        file = open(file_path, 'rb')
        calendar = Calendar.from_ical(file.read())
        update_status(task_handle, 'Processing event')
        event = Event()

        if 'X-WR-CALNAME' in calendar:
            event.name = get_valid_event_name(calendar.decoded('X-WR-CALNAME'))
        if not event.name and 'X-WR-CALDESC' in calendar:
            event.name = get_valid_event_name(calendar.decoded('X-WR-CALDESC'))
        for session in calendar.walk('vevent'):
            if not event.name:
                event.name = get_valid_event_name(session.decoded('UID'))

            start_time = session.decoded('dtstart')
            end_time = session.decoded('dtend')

            if not event.start_time or start_time < event.start_time:
                event.start_time = start_time
            if not event.end_time or end_time > event.end_time:
                event.end_time = end_time

        if not event.name:
            event.name = 'Un-named Event'
        # Event name set

        if 'X-WR-TIMEZONE' in calendar:
            event.timezone = calendar.decoded('X-WR-TIMEZONE')

        event.has_session_speakers = True
        event.state = 'Published'
        event.privacy = 'public'
        db.session.add(event)

        update_status(task_handle, 'Adding sessions')

        for session_block in calendar.walk('vevent'):
            track_id = None
            if 'CATEGORIES' in session_block:
                categories = session_block['CATEGORIES']
                string_to_hash = categories if not hasattr(
                    categories, '__iter__') else categories[0]
                seed = int('100'.join(
                    list(str(ord(character)) for character in string_to_hash)))
                random.seed(seed)
                color = "#%06x" % random.randint(0, 0xFFFFFF)
                track, _ = get_or_create(Track,
                                         event_id=event.id,
                                         name=string_to_hash,
                                         color=color)
                track_id = track.id

            microlocation, _ = get_or_create(
                Microlocation,
                event_id=event.id,
                name=session_block.decoded('location'))

            session = Session()
            session.track_id = track_id
            session.microlocation_id = microlocation.id
            session.title = session_block.decoded('summary')
            session.short_abstract = session_block.decoded('description')
            session.start_time = session_block.decoded('dtstart')
            session.end_time = session_block.decoded('dtend')
            session.signup_url = session_block.decoded('url')
            session.event_id = event.id
            session.state = 'accepted'
            session.speakers = []
            save_to_db(session, 'Session Updated')

            attendees = []
            if 'attendee' in session_block:
                attendees_dirty = session_block['attendee']
                if hasattr(attendees_dirty, '__iter__'):
                    for attendee in attendees_dirty:
                        attendees.append(attendee.params['CN'])
                else:
                    attendees.append(attendees_dirty.params['CN'])

            for attendee in attendees:
                name_mix = attendee + ' ' + event.name
                email = ''.join(x for x in name_mix.title()
                                if not x.isspace()) + '@example.com'
                speaker = Speaker(name=attendee,
                                  event_id=event.id,
                                  email=email,
                                  country='Earth',
                                  organisation='')
                db.session.add(speaker)
                session.speakers.append(speaker)
                db.session.commit()

            update_status(task_handle, 'Added session "' + session.title + '"')

        update_status(task_handle, 'Saving data')
        save_to_db(event)
        update_status(task_handle, 'Finalizing')

        own_event(event=event, user_id=creator_id)
        return event