예제 #1
0
    def it_sends_the_event_email_reminder(self, mocker, db_session,
                                          sample_event_with_dates,
                                          sample_admin_user):
        dao_update_event(sample_event_with_dates.id, event_state=APPROVED)
        mock_send_email = mocker.patch(
            'app.na_celery.event_tasks.send_smtp_email', return_value=200)

        send_event_email_reminder()

        assert mock_send_email.call_args[0][0] == sample_admin_user.email
        assert mock_send_email.call_args[0][
            1] == f"Event: {sample_event_with_dates.title} email reminder"
예제 #2
0
    def it_reports_an_error_if_sending_reminder_fails(self, mocker, db_session,
                                                      sample_event_with_dates,
                                                      sample_admin_user):
        dao_update_event(sample_event_with_dates.id, event_state=APPROVED)
        mock_send_email = mocker.patch(
            'app.na_celery.event_tasks.send_smtp_email', return_value=503)
        mock_logger = mocker.patch(
            'app.na_celery.event_tasks.current_app.logger.error')

        send_event_email_reminder()

        assert mock_send_email.call_args[0][0] == sample_admin_user.email
        assert mock_send_email.call_args[0][
            1] == f"Event: {sample_event_with_dates.title} email reminder"
        assert mock_logger.called
        assert mock_logger.call_args[0][0] == f"Problem sending reminder email Event"\
            f": {sample_event_with_dates.title} email reminder for {sample_admin_user.id}, status code: 503"
    def it_updates_an_event_dao_with_new_event_date(self, db, db_session,
                                                    sample_event):
        speaker = create_speaker(name='John Brown')
        event_date = create_event_date(event_datetime='2018-01-20T19:00:00',
                                       speakers=[speaker])

        dao_update_event(sample_event.id, event_dates=[event_date])

        event_from_db = Event.query.filter(Event.id == sample_event.id).first()

        assert sample_event.event_dates[0] == event_from_db.event_dates[0]

        event_date2 = create_event_date(event_datetime='2018-02-20T19:00:00',
                                        speakers=[speaker])

        dao_update_event(sample_event.id, event_dates=[event_date2])

        event_dates = EventDate.query.all()

        assert len(event_dates) == 1
    def it_updates_an_event_dao_with_new_speaker(self, db, db_session):
        speaker = create_speaker(name='John Brown')
        event_date = create_event_date(event_datetime='2018-01-20T19:00:00',
                                       speakers=[speaker])
        event = create_event(event_dates=[event_date])

        speaker2 = create_speaker(name='Jim Blue')

        db_event_date = dao_get_event_date_by_id(event_date.id)

        db_event_date.speakers = [speaker, speaker2]

        dao_update_event(event.id, event_dates=[db_event_date])

        event_from_db = Event.query.filter(Event.id == event.id).first()

        assert event.event_dates[0] == event_from_db.event_dates[0]

        event_dates = EventDate.query.all()

        assert len(event_dates) == 1
예제 #5
0
def create_update_paypal_button_task(self, event_id):
    current_app.logger.info('Task create_paypal_button received for event %s',
                            str(event_id))

    try:
        event = dao_get_event_by_id(event_id)
        if not event.booking_code:
            dao_update_event(event_id,
                             booking_code=f'pending: {self.request.id}')

        booking_code = event.booking_code
        if event.booking_code.startswith(
                'pending:') or event.booking_code.startswith('error:'):
            booking_code = None

        p = PayPal()
        booking_code = p.create_update_paypal_button(
            event_id,
            event.title,
            event.fee,
            event.conc_fee,
            event.multi_day_fee,
            event.multi_day_conc_fee,
            True if event.event_type == 'Talk' else False,
            booking_code=booking_code)

        dao_update_event(event_id, booking_code=booking_code)
    except NoResultFound as e:
        current_app.logger.error(
            f'No result error trying to create_update_paypal_button {e} {event_id}'
        )
    except PaypalException as e:
        dao_update_event(event_id, booking_code=f'error: {str(e)[:40]}')
        current_app.logger.error(
            f'Paypal error trying to create_update_paypal_button {e} {event_id}'
        )
예제 #6
0
def create_event():
    data = request.get_json(force=True)
    event_year = None

    validate(data, post_create_event_schema)

    try:
        dao_get_event_type_by_id(data['event_type_id'])
    except NoResultFound:
        raise InvalidRequest(
            'event type not found: {}'.format(data['event_type_id']), 400)

    try:
        dao_get_venue_by_id(data['venue_id'])
    except NoResultFound:
        raise InvalidRequest('venue not found: {}'.format(data['venue_id']),
                             400)

    event = Event(
        event_type_id=data['event_type_id'],
        title=data['title'],
        sub_title=data.get('sub_title'),
        description=data['description'],
        booking_code='',
        fee=data.get('fee'),
        conc_fee=data.get('conc_fee'),
        multi_day_fee=data.get('multi_day_fee'),
        multi_day_conc_fee=data.get('multi_day_conc_fee'),
        venue_id=data.get('venue_id'),
        event_state=data.get('event_state', DRAFT),
        remote_access=data.get('remote_access'),
        remote_pw=data.get('remote_pw'),
    )

    for event_date in data.get('event_dates'):
        if not event_year:
            event_year = event_date['event_date'].split('-')[0]
        speakers = []
        for s in event_date.get('speakers', []):
            speaker = dao_get_speaker_by_id(s['speaker_id'])
            speakers.append(speaker)

        e = EventDate(event_datetime=event_date['event_date'],
                      end_time=None if event_date.get('end_time') == '' else
                      event_date.get('end_time'),
                      speakers=speakers)

        dao_create_event_date(e)
        event.event_dates.append(e)

    dao_create_event(event)

    image_filename = data.get('image_filename')

    image_data = data.get('image_data')

    storage = Storage(current_app.config['STORAGE'])

    if image_data:
        target_image_filename = '{}/{}'.format(event_year, str(event.id))

        storage.upload_blob_from_base64string(image_filename,
                                              target_image_filename,
                                              base64.b64decode(image_data))

        image_filename = target_image_filename
    elif image_filename:
        if not storage.blob_exists(image_filename):
            raise InvalidRequest('{} does not exist'.format(image_filename),
                                 400)

    event.image_filename = image_filename
    dao_update_event(event.id, image_filename=image_filename)

    if event.fee and event.fee > 0 and event.event_state in [READY, APPROVED]:
        paypal_tasks.create_update_paypal_button_task.apply_async(
            (str(event.id), ))

    return jsonify(event.serialize()), 201
예제 #7
0
def update_event(event_id):
    data = request.get_json(force=True)

    current_app.logger.info('Update event: {}'.format(data))

    validate(data, post_update_event_schema)

    try:
        event = dao_get_event_by_id(event_id)
    except NoResultFound:
        raise InvalidRequest('event not found: {}'.format(event_id), 400)

    errs = []
    event_dates = []
    event_data = {}

    if data.get('event_state') == REJECTED:
        new_rejects = [
            r for r in data.get('reject_reasons') if not r.get('id')
        ]
        if not new_rejects:
            raise InvalidRequest('rejected event requires new reject reason',
                                 400)
    elif data.get('event_state') == APPROVED:
        if data.get('reject_reasons'):
            rejects = [
                r for r in data.get('reject_reasons') if not r.get('resolved')
            ]
            if rejects:
                raise InvalidRequest(
                    'approved event should not have any reject reasons', 400)

    data_event_dates = data.get('event_dates')

    if data_event_dates:
        serialized_event_dates = event.serialize_event_dates()

        data_event_dates__dates = [e['event_date'] for e in data_event_dates]
        serialized_event_dates__dates = [
            e['event_datetime'] for e in serialized_event_dates
        ]

        diff_add = set(data_event_dates__dates).difference(
            serialized_event_dates__dates)
        intersect = set(data_event_dates__dates).intersection(
            serialized_event_dates__dates)

        dates_to_add = [
            e for e in data_event_dates if e['event_date'] in diff_add
        ]
        dates_to_update = [
            e for e in data_event_dates if e['event_date'] in intersect
        ]

        for _date in dates_to_add:
            speakers = []
            for s in _date.get('speakers', []):
                speaker = dao_get_speaker_by_id(s['speaker_id'])
                speakers.append(speaker)

            e = EventDate(event_id=event_id,
                          event_datetime=_date['event_date'],
                          end_time=_date.get('end_time'),
                          speakers=speakers)

            current_app.logger.info('Adding event date: {}'.format(
                _date['event_date']))

            dao_create_event_date(e)

            if _date['event_date'] not in [
                    _e.event_datetime for _e in event_dates
            ]:
                event_dates.append(e)

        for _date in sorted(dates_to_update, key=lambda k: k['event_date']):
            speakers = []
            for s in _date['speakers']:
                speaker = dao_get_speaker_by_id(s['speaker_id'])
                speakers.append(speaker)
            db_event_date = [
                e for e in event.event_dates if e.event_datetime.strftime(
                    '%Y-%m-%d %H:%M') == _date['event_date']
            ][0]
            db_event_date.speakers = speakers

            if _date['event_date'] not in [
                    _e.event_datetime for _e in event_dates
            ]:
                event_dates.append(db_event_date)

    if data.get('reject_reasons'):
        for reject_reason in data.get('reject_reasons'):
            if reject_reason.get('id'):
                reject_data = {
                    'reason': reject_reason['reason'],
                    'resolved': reject_reason.get('resolved') or False
                }

                dao_update_reject_reason(reject_reason.get('id'),
                                         **reject_data)
            else:
                rr = RejectReason(event_id=event_id,
                                  reason=reject_reason['reason'],
                                  resolved=reject_reason.get('resolved')
                                  or False,
                                  created_by=reject_reason.get('created_by'))
                dao_create_reject_reason(rr)

    event_data = {}
    for k in data.keys():
        if hasattr(Event, k) and k not in ['reject_reasons']:
            event_data[k] = data[k]

    if event_dates:
        event_data['event_dates'] = event_dates
    elif data_event_dates == []:
        raise InvalidRequest('{} needs an event date'.format(event_id), 400)

    if event_data.get('fee') and event_data.get('fee') > 0:
        update_data = {
            'fee': event_data.get('fee'),
            'conc_fee': event_data.get('conc_fee'),
            'multi_day_fee': event_data.get('multi_day_fee') or 0,
            'multi_day_conc_fee': event_data.get('multi_day_conc_fee') or 0,
            'event_type_id': event_data.get('event_type_id'),
        }
        db_data = {
            'fee': event.fee,
            'conc_fee': event.conc_fee,
            'multi_day_fee': event.multi_day_fee,
            'multi_day_conc_fee': event.multi_day_conc_fee,
            'event_type_id': str(event.event_type.id),
        }

        if update_data != db_data:
            if data.get('event_state') in [READY, APPROVED]:
                paypal_tasks.create_update_paypal_button_task.apply_async(
                    (str(event_id), ))

    res = dao_update_event(event_id, **event_data)

    if res:
        image_data = data.get('image_data')

        image_filename = data.get('image_filename')

        if current_app.config['STORAGE'].startswith('None'):
            current_app.logger.warn('Storage not setup')
        else:
            storage = Storage(current_app.config['STORAGE'])
            if image_data:
                event_year = str(
                    event.event_dates[0].event_datetime).split('-')[0]
                target_image_filename = '{}/{}'.format(event_year,
                                                       str(event_id))

                if data.get('event_state') != APPROVED:
                    target_image_filename += '-temp'

                storage.upload_blob_from_base64string(
                    image_filename, target_image_filename,
                    base64.b64decode(image_data))

                unix_time = time.time()
                image_filename = '{}?{}'.format(target_image_filename,
                                                unix_time)
            elif image_filename:
                image_filename_without_cache_buster = image_filename.split(
                    '?')[0]
                if not storage.blob_exists(
                        image_filename_without_cache_buster):
                    raise InvalidRequest(
                        '{} does not exist'.format(
                            image_filename_without_cache_buster), 400)

        if image_filename:
            if data.get('event_state') == APPROVED:
                if '-temp' in image_filename:
                    q_pos = image_filename.index('-temp?')
                    image_filename = image_filename[0:q_pos]
                    storage.rename_image(image_filename + '-temp',
                                         image_filename)
                else:
                    current_app.logger.warn(
                        f"No temp file to rename: {image_filename}")

            event.image_filename = image_filename
            dao_update_event(event.id, image_filename=image_filename)

        json_event = event.serialize()

        if data.get('event_state') == READY:
            emails_to = [admin.email for admin in dao_get_admin_users()]

            message = 'Please review this event for publishing <a href="{}">{}</a>'.format(
                '{}/events/{}'.format(current_app.config['FRONTEND_ADMIN_URL'],
                                      event_id), event.title)

            status_code = send_smtp_email(
                emails_to, '{} is ready for review'.format(event.title),
                message)
            if status_code != 200:
                errs.append(f"Problem sending admin email {status_code}")
        elif data.get('event_state') == REJECTED:
            emails_to = [user.email for user in dao_get_users()]

            message = '<div>Please correct this event <a href="{}">{}</a></div>'.format(
                '{}/events/{}'.format(current_app.config['FRONTEND_ADMIN_URL'],
                                      event_id), event.title)

            message += '<ol>'
            for reject_reason in [
                    rr for rr in json_event.get('reject_reasons')
                    if not rr.get('resolved')
            ]:
                message += '<li>{}</li>'.format(reject_reason['reason'])
            message += '</ol>'

            status_code = send_smtp_email(
                emails_to,
                '{} event needs to be corrected'.format(event.title), message)
            if status_code != 200:
                errs.append(f"Problem sending smtp emails: {status_code}")

        json_event['errors'] = errs
        return jsonify(json_event), 200

    raise InvalidRequest('{} did not update event'.format(event_id), 400)
    def it_updates_an_event_dao(self, db, db_session, sample_event):
        dao_update_event(sample_event.id, title='new title')

        event_from_db = Event.query.filter(Event.id == sample_event.id).first()

        assert sample_event.title == event_from_db.title