Beispiel #1
0
def insert_admin():
    Session.initialize_db(initialize=True)
    with Session() as session:
        if session.insert_test_admin_account():
            print("Test admin account created successfully")
        else:
            print("Not allowed to create admin account at this time")
Beispiel #2
0
def send_automated_emails():
    from uber.tasks.email import send_automated_emails as send_emails
    Session.initialize_db(initialize=True)
    timed(AutomatedEmail.reconcile_fixtures)()
    results = timed(send_emails)()
    if results:
        print('Unapproved email counts:\n{}'.format(dumps(results, indent=2, sort_keys=True)))
Beispiel #3
0
def has_admin():
    Session.initialize_db(initialize=True)
    with Session() as session:
        if session.query(AdminAccount).first() is None:
            print('Could not find any admin accounts', file=sys.stderr)
            sys.exit(1)
        else:
            print('At least one admin account exists', file=sys.stderr)
            sys.exit(0)
Beispiel #4
0
def session(request):
    session = Session().session
    for num in ['One', 'Two', 'Three', 'Four', 'Five', 'Six']:
        setattr(session, 'job_' + num.lower(), session.job(name='Job ' + num))
    for num in ['One', 'Two', 'Three', 'Four', 'Five']:
        setattr(session, 'staff_{}'.format(num).lower(), session.attendee(badge_type=c.STAFF_BADGE, first_name=num))
    for name in ['Arcade', 'Console']:
        setattr(session, 'dept_' + name.lower(), session.department(name=name))
    request.addfinalizer(session.close)
    return session
Beispiel #5
0
def import_uber_test_data(test_data_file):
    with open(test_data_file) as f:
        global dump
        dump = json.load(f)

    Session.initialize_db(initialize=True)
    with Session() as session:
        import_groups(session)
        import_attendees(session)
        import_events(session)
        import_jobs(session)
Beispiel #6
0
def decline_and_convert_dealer_groups():
    from uber.site_sections.groups import _decline_and_convert_dealer_group
    Session.initialize_db(initialize=True)
    with Session() as session:
        groups = session.query(Group) \
            .filter(Group.tables > 0, Group.status == c.WAITLISTED) \
            .options(
                subqueryload(Group.attendees).subqueryload(Attendee.admin_account),
                subqueryload(Group.attendees).subqueryload(Attendee.shifts)) \
            .order_by(Group.name, Group.id).all()

        for group in groups:
            print('{}: {}'.format(
                group.name,
                _decline_and_convert_dealer_group(session, group)))
Beispiel #7
0
def out_of_badge_type(attendee):
    if attendee.badge_type != attendee.orig_value_of('badge_type'):
        with Session() as session:
            try:
                session.get_next_badge_num(attendee.badge_type_real)
            except AssertionError:
                return 'There are no more badges available for that type'
Beispiel #8
0
def no_dupe_code(promo_code):
    if promo_code.code and (promo_code.is_new or promo_code.code !=
                            promo_code.orig_value_of('code')):
        with Session() as session:
            if session.lookup_promo_code(promo_code.code):
                return 'The code you entered already belongs to another ' \
                    'promo code. Note that promo codes are not case sensitive.'
Beispiel #9
0
 def reconcile_fixtures():
     from uber.models import Session
     with Session() as session:
         for ident, fixture in AutomatedEmail._fixtures.items():
             automated_email = session.query(AutomatedEmail).filter_by(
                 ident=ident).first() or AutomatedEmail()
             session.add(automated_email.reconcile(fixture))
         session.flush()
         for automated_email in session.query(AutomatedEmail).all():
             if automated_email.ident in AutomatedEmail._fixtures:
                 # This automated email exists in our email fixtures.
                 session.execute(
                     update(Email).where(
                         Email.ident == automated_email.ident).values(
                             automated_email_id=automated_email.id))
             else:
                 # This automated email no longer exists in our email
                 # fixtures. It was probably deleted because it was no
                 # longer relevant, or perhaps it was removed by disabling
                 # a feature flag. Either way, we want to clean up and
                 # delete it from the database.
                 session.execute(
                     update(Email).where(
                         Email.ident == automated_email.ident).values(
                             automated_email_id=None))
                 session.delete(automated_email)
Beispiel #10
0
 def PUBLIC_DEPARTMENT_OPTS_WITH_DESC(self):
     from uber.models import Session, Department
     with Session() as session:
         query = session.query(Department).filter_by(
             solicits_volunteers=True).order_by(Department.name)
         return [('All', 'Anywhere', 'I want to help anywhere I can!')] \
             + [(d.id, d.name, d.description) for d in query]
Beispiel #11
0
 def admin_name():
     try:
         from uber.models import Session
         with Session() as session:
             return session.admin_attendee().full_name
     except Exception as ex:
         return None
Beispiel #12
0
def check_duplicate_registrations():
    """
    This function looks through registered attendees for attendees with the
    same names and email addresses. It first deletes any unpaid duplicates,
    then sets paid duplicates from "Completed" to "New" and sends an email to
    the registration email address. This allows us to see new duplicate
    attendees without repetitive emails.
    """
    if c.PRE_CON and (c.DEV_BOX or c.SEND_EMAILS):
        subject = c.EVENT_NAME + ' Duplicates Report for ' + localized_now().strftime('%Y-%m-%d')
        with Session() as session:
            if session.no_email(subject):
                grouped = defaultdict(list)
                for a in session.query(Attendee).filter(Attendee.first_name != '') \
                        .filter(Attendee.badge_status == c.COMPLETED_STATUS).options(joinedload(Attendee.group)) \
                        .order_by(Attendee.registered):
                    if not a.group or a.group.status not in [c.WAITLISTED, c.UNAPPROVED]:
                        grouped[a.full_name, a.email.lower()].append(a)

                dupes = {k: v for k, v in grouped.items() if len(v) > 1}

                for who, attendees in dupes.items():
                    paid = [a for a in attendees if a.paid == c.HAS_PAID]
                    unpaid = [a for a in attendees if a.paid == c.NOT_PAID]
                    if len(paid) == 1 and len(attendees) == 1 + len(unpaid):
                        for a in unpaid:
                            session.delete(a)
                        del dupes[who]
                    for a in paid:
                        a.badge_status = c.NEW_STATUS

                if dupes:
                    body = render('emails/daily_checks/duplicates.html', {'dupes': sorted(dupes.items())})
                    send_email(c.ADMIN_EMAIL, c.REGDESK_EMAIL, subject, body, format='html', model='n/a')
Beispiel #13
0
    def export_model(self, out, session, selected_model=''):
        model = Session.resolve_model(selected_model)

        cols = [getattr(model, col.name) for col in model.__table__.columns]
        out.writerow([col.name for col in cols])

        for attendee in session.query(model).all():
            row = []
            for col in cols:
                if isinstance(col.type, Choice):
                    # Choice columns are integers with a single value with an automatic
                    # _label property, e.g. the "shirt" column has a "shirt_label"
                    # property, so we'll use that.
                    row.append(getattr(attendee, col.name + '_label'))
                elif isinstance(col.type, MultiChoice):
                    # MultiChoice columns are comma-separated integer lists with an
                    # automatic _labels property which is a list of string labels.
                    # So we'll get that and then separate the labels with slashes.
                    row.append(' / '.join(getattr(attendee, col.name + '_labels')))
                elif isinstance(col.type, UTCDateTime):
                    # Use the empty string if this is null, otherwise use strftime.
                    # Also you should fill in whatever actual format you want.
                    val = getattr(attendee, col.name)
                    row.append(val.strftime('%Y-%m-%d %H:%M:%S') if val else '')
                else:
                    # For everything else we'll just dump the value, although we might
                    # consider adding more special cases for things like foreign keys.
                    row.append(getattr(attendee, col.name))
            out.writerow(row)
Beispiel #14
0
    def update_request(self, id=None, **kwargs):
        """
        Create or update a hotel request. If the id is supplied then it will
        attempt to update the given request.
        Possible attributes are attendee_id, nights, wanted_roommates, unwanted_roommates, special_needs, and approved.

        Returns the created or updated request.
        """
        with Session() as session:
            if id:
                hotel_request = session.query(HotelRequests).filter(
                    HotelRequests.id == id).one_or_none()
                if not hotel_request:
                    return HTTPError(404,
                                     "Could not locate request {}".format(id))
            else:
                hotel_request = HotelRequests()
            for attr in [
                    'attendee_id', 'nights', 'wanted_roommates',
                    'unwanted_roommates', 'special_needs', 'approved'
            ]:
                if attr in kwargs:
                    setattr(hotel_request, attr, kwargs[attr])
            session.add(hotel_request)
            session.commit()
            return hotel_request.to_dict()
Beispiel #15
0
 def test_staff_badge(self, monkeypatch):
     with Session() as session:
         assert session
         monkeypatch.setattr(Attendee, 'session', Mock())
         a = Attendee(badge_type=c.STAFF_BADGE, badge_num=123)
         a.unset_volunteering()
         assert a.badge_type == c.ATTENDEE_BADGE and a.badge_num is None
Beispiel #16
0
 def test_no_to_yes_volunteering(self, unset_volunteering, prevent_presave_adjustments):
     with Session() as session:
         a = session.attendee(first_name='Regular', last_name='Attendee')
         a.staffing = True
         a._staffing_adjustments()
         assert a.ribbon_ints == [c.VOLUNTEER_RIBBON]
         assert not unset_volunteering.called
Beispiel #17
0
def auth_by_token(required_access):
    token = cherrypy.request.headers.get('X-Auth-Token', None)
    if not token:
        return (401, 'Missing X-Auth-Token header')

    try:
        token = uuid.UUID(token)
    except ValueError as ex:
        return (403, 'Invalid auth token, {}: {}'.format(ex, token))

    with Session() as session:
        api_token = session.query(ApiToken).filter_by(token=token).first()
        if not api_token:
            return (403, 'Auth token not recognized: {}'.format(token))
        if api_token.revoked_time:
            return (403, 'Revoked auth token: {}'.format(token))
        if not required_access.issubset(set(api_token.access_ints)):
            # If the API call requires extra access, like c.ADMIN, check if the
            # associated admin account has the required access.
            extra_required_access = required_access.difference(
                set(c.API_ACCESS.keys()))
            if not extra_required_access or not extra_required_access.issubset(
                    api_token.admin_account.access_ints):
                return (403,
                        'Insufficient access for auth token: {}'.format(token))
        cherrypy.session['account_id'] = api_token.admin_account_id
    return None
Beispiel #18
0
    def undo_delete(self, session, id, message='', page='1', who='', what='', action=''):
        if cherrypy.request.method == "POST":
            model_class = None
            tracked_delete = session.query(Tracking).get(id)
            if tracked_delete.action != c.DELETED:
                message = 'Only a delete can be undone'
            else:
                model_class = Session.resolve_model(tracked_delete.model)

            if model_class:
                params = json.loads(tracked_delete.snapshot)
                model_id = params.get('id').strip()
                if model_id:
                    existing_model = session.query(model_class).filter(
                        model_class.id == model_id).first()
                    if existing_model:
                        message = '{} has already been undeleted'.format(tracked_delete.which)
                    else:
                        model = model_class(id=model_id).apply(params, restricted=False)
                else:
                    model = model_class().apply(params, restricted=False)

                if not message:
                    session.add(model)
                    message = 'Successfully undeleted {}'.format(tracked_delete.which)
            else:
                message = 'Could not resolve {}'.format(tracked_delete.model)

        raise HTTPRedirect('feed?page={}&who={}&what={}&action={}&message={}', page, who, what, action, message)
Beispiel #19
0
    def generate_word_code(cls, count=None):
        """
        Generates a promo code consisting of words from `PromoCodeWord`.

        Arguments:
            count (int): The number of codes to generate. If `count` is `None`,
                then a single code will be generated. Defaults to `None`.

        Returns:
            If an `int` value was passed for `count`, then a `list` of newly
            generated codes is returned. If `count` is `None`, then a single
            `str` is returned.
        """
        from uber.models import Session
        with Session() as session:
            words = PromoCodeWord.group_by_parts_of_speech(
                session.query(PromoCodeWord).order_by(
                    PromoCodeWord.normalized_word).all())

        # The actual generator function, called repeatedly by `_generate_code`
        def _generate_word_code():
            code_words = []
            for part_of_speech, _ in PromoCodeWord._PART_OF_SPEECH_OPTS:
                if words[part_of_speech]:
                    code_words.append(random.choice(words[part_of_speech]))
            return ' '.join(code_words)

        return cls._generate_code(_generate_word_code, count=count)
Beispiel #20
0
def mivs_unique_name(studio):
    with Session() as session:
        if session.query(IndieStudio).filter(
                IndieStudio.name == studio.name,
                IndieStudio.id != studio.id).count():
            return "That studio name is already taken; " \
                "are you sure you shouldn't be logged in with that studio's account?"
Beispiel #21
0
    def update(self, id, params):
        """
        Update an attendee using their unique ID, returned by our lookup functions.

        `params` should be a dictionary with column name: value to update values.
        Use labels for Choice and MultiChoice columns, and a string like "no" or "yes" for Boolean columns.
        Date and DateTime columns should be parsed correctly as long as they follow a standard format.

        Example:
        <pre>{"first_name": "First", "paid": "doesn't need to", "ribbons": "Staff, Panelist"}</pre>
        """
        with Session() as session:
            attendee = session.attendee(id, allow_invalid=True)

            if not attendee:
                raise HTTPError(404, 'No attendee found with this ID')

            for key, val in params.items():
                params[key] = _parse_if_datetime(key, val)
                params[key] = _parse_if_boolean(key, val)

            attendee.apply(params, restricted=False)
            message = check(attendee)
            if message:
                session.rollback()
                raise HTTPError(400, message)

            # Staff (not volunteers) also almost never need to pay by default
            if attendee.staffing and not attendee.orig_value_of('staffing') \
                    and c.VOLUNTEER_RIBBON not in attendee.ribbon_ints and 'paid' not in params:
                attendee.paid = c.NEED_NOT_PAY

            return attendee.id
    def export_model(self, out, session, selected_model=''):
        model = Session.resolve_model(selected_model)

        cols = [getattr(model, col.name) for col in model.__table__.columns]
        out.writerow([col.name for col in cols])

        for attendee in session.query(model).all():
            row = []
            for col in cols:
                if isinstance(col.type, Choice):
                    # Choice columns are integers with a single value with an automatic
                    # _label property, e.g. the "shirt" column has a "shirt_label"
                    # property, so we'll use that.
                    row.append(getattr(attendee, col.name + '_label'))
                elif isinstance(col.type, MultiChoice):
                    # MultiChoice columns are comma-separated integer lists with an
                    # automatic _labels property which is a list of string labels.
                    # So we'll get that and then separate the labels with slashes.
                    row.append(' / '.join(
                        getattr(attendee, col.name + '_labels')))
                elif isinstance(col.type, UTCDateTime):
                    # Use the empty string if this is null, otherwise use strftime.
                    # Also you should fill in whatever actual format you want.
                    val = getattr(attendee, col.name)
                    row.append(
                        val.strftime('%Y-%m-%d %H:%M:%S') if val else '')
                elif isinstance(col.type, JSONB):
                    row.append(json.dumps(getattr(attendee, col.name)))
                else:
                    # For everything else we'll just dump the value, although we might
                    # consider adding more special cases for things like foreign keys.
                    row.append(getattr(attendee, col.name))
            out.writerow(row)
Beispiel #23
0
    def test_POST_creates_group(self, POST, csrf_token, admin_attendee):
        with pytest.raises(HTTPRedirect, match='Group1 has been uploaded'):
            self._add_group_response(name='Group1',
                                     admin_notes='Stuff',
                                     first_name='Al',
                                     last_name='Bert',
                                     email='*****@*****.**',
                                     group_type=str(c.BAND),
                                     badges=4)

        with Session() as session:
            group = session.query(Group).filter(Group.name == 'Group1').first()
            assert group
            assert not group.auto_recalc
            assert group.admin_notes == 'Stuff'
            assert group.leader
            assert group.leader.first_name == 'Al'
            assert group.leader.last_name == 'Bert'
            assert group.leader.email == '*****@*****.**'
            assert group.leader.placeholder
            assert group.leader.paid == c.PAID_BY_GROUP
            assert group.guest
            assert group.badges == 4
            for attendee in group.attendees:
                assert attendee.paid == c.PAID_BY_GROUP
                assert attendee.badge_type == c.GUEST_BADGE
                assert c.BAND in attendee.ribbon_ints
Beispiel #24
0
    def test_model_id_invalid(self, ModelClass, params):
        @id_required(ModelClass)
        def _requires_model_id(**params):
            return True

        params['session'] = Session().session
        pytest.raises(HTTPRedirect, _requires_model_id, **params)
Beispiel #25
0
def test_dept_head_ribbon_label_from_dept_membership():
    with Session() as session:
        a = Attendee()
        session.add(a)

        a.presave_adjustments()
        assert a.ribbon_labels == []

        a.dept_memberships = [DeptMembership(is_dept_head=True)]
        a.presave_adjustments()
        assert a.ribbon_labels == ['Department Head']
        a.presave_adjustments()
        assert a.ribbon_labels == ['Department Head']

        a.badge_type = c.ATTENDEE_BADGE
        a.staffing = True
        a.ribbon = '{}'.format(c.DEALER_RIBBON)
        a.presave_adjustments()
        assert set(a.ribbon_labels) == set(['Department Head', 'Shopkeep'])
        a.presave_adjustments()
        assert set(a.ribbon_labels) == set(['Department Head', 'Shopkeep'])

        a.dept_memberships = [DeptMembership(is_dept_head=False)]
        a.presave_adjustments()
        assert set(a.ribbon_labels) == set(['Department Head', 'Shopkeep'])
        a.presave_adjustments()
        assert set(a.ribbon_labels) == set(['Department Head', 'Shopkeep'])

        session.expunge_all()
Beispiel #26
0
 def admin_email():
     try:
         from uber.models import Session
         with Session() as session:
             return session.admin_attendee().email
     except Exception as ex:
         return None
Beispiel #27
0
def check_pending_badges():
    if c.PRE_CON and (c.DEV_BOX or c.SEND_EMAILS):
        emails = [[
            'Staff', c.STAFF_EMAIL, Attendee.badge_type == c.STAFF_BADGE,
            'staffing_admin'
        ],
                  [
                      'Attendee', c.REGDESK_EMAIL,
                      Attendee.badge_type != c.STAFF_BADGE, 'registration'
                  ]]
        subject = c.EVENT_NAME + ' Pending {} Badge Report for ' + localized_now(
        ).strftime('%Y-%m-%d')
        with Session() as session:
            for badge_type, to, per_email_filter, site_section in emails:
                pending = session.query(Attendee).filter_by(
                    badge_status=c.PENDING_STATUS).filter(
                        per_email_filter).all()
                if pending and session.no_email(subject.format(badge_type)):
                    body = render('emails/daily_checks/pending.html', {
                        'pending': pending,
                        'site_section': site_section
                    })
                    send_email(c.ADMIN_EMAIL,
                               to,
                               subject.format(badge_type),
                               body,
                               format='html',
                               model='n/a')
Beispiel #28
0
    def lookup_attendee_from_barcode(self, barcode_value, full=False):
        """
        Returns a single attendee using the barcode value from their badge.

        Takes the (possibly encrypted) barcode value as the first parameter.

        Optionally, "full" may be passed as the second parameter to return the
        complete attendee record, including departments, shifts, and food
        restrictions.
        """
        badge_num = -1
        try:
            result = get_badge_num_from_barcode(barcode_value)
            badge_num = result['badge_num']
        except Exception as e:
            raise HTTPError(500, "Couldn't look up barcode value: " + str(e))

        # Note: A decrypted barcode can yield a valid badge num,
        # but that badge num may not be assigned to an attendee.
        with Session() as session:
            query = session.query(Attendee).filter_by(badge_num=badge_num)
            fields, query = _attendee_fields_and_query(full, query)
            attendee = query.first()
            if attendee:
                return attendee.to_dict(fields)
            else:
                raise HTTPError(404, 'Valid barcode, but no attendee found with Badge #{}'.format(badge_num))
 def test_ordinal(self, automated_email_fixtures):
     with Session() as session:
         for ordinal, (ident, fixture) in enumerate(
                 AutomatedEmail._fixtures.items()):
             automated_email = session.query(AutomatedEmail).filter_by(
                 ident=ident).one()
             assert automated_email.ordinal == ordinal
Beispiel #30
0
    def lookup(self, department_id, start_time=None, end_time=None):
        """
        Returns a list of all shifts for the given department.

        Takes the department id as the first parameter. For a list of all
        department ids call the "dept.list" method.

        Optionally, takes a "start_time" and "end_time" to constrain the
        results to a given date range. Dates may be given in any format
        supported by the
        <a href="http://dateutil.readthedocs.io/en/stable/parser.html">
        dateutil parser</a>, plus the string "now".

        Unless otherwise specified, "start_time" and "end_time" are assumed
        to be in the local timezone of the event.
        """
        with Session() as session:
            query = session.query(Job).filter_by(department_id=department_id)
            if start_time:
                start_time = _parse_datetime(start_time)
                query = query.filter(Job.start_time >= start_time)
            if end_time:
                end_time = _parse_datetime(end_time)
                query = query.filter(Job.start_time <= end_time)
            query = query.options(
                    subqueryload(Job.department),
                    subqueryload(Job.shifts).subqueryload(Shift.attendee))
            return [job.to_dict(self.fields) for job in query]
Beispiel #31
0
    def undo_delete(self, session, id, message='', page='1', who='', what='', action=''):
        if cherrypy.request.method == "POST":
            model_class = None
            tracked_delete = session.query(Tracking).get(id)
            if tracked_delete.action != c.DELETED:
                message = 'Only a delete can be undone'
            else:
                model_class = Session.resolve_model(tracked_delete.model)

            if model_class:
                params = json.loads(tracked_delete.snapshot)
                model_id = params.get('id').strip()
                if model_id:
                    existing_model = session.query(model_class).filter(
                        model_class.id == model_id).first()
                    if existing_model:
                        message = '{} has already been undeleted'.format(tracked_delete.which)
                    else:
                        model = model_class(id=model_id).apply(params, restricted=False)
                else:
                    model = model_class().apply(params, restricted=False)

                if not message:
                    session.add(model)
                    message = 'Successfully undeleted {}'.format(tracked_delete.which)
            else:
                message = 'Could not resolve {}'.format(tracked_delete.model)

        raise HTTPRedirect('feed?page={}&who={}&what={}&action={}&message={}', page, who, what, action, message)
Beispiel #32
0
 def DEALER_APPS(self):
     from uber.models import Session, Group
     with Session() as session:
         return session.query(Group).filter(
             Group.tables > 0,
             Group.cost > 0,
             Group.status == self.UNAPPROVED).count()
Beispiel #33
0
 def schedule(self):
     """
     Returns the entire schedule in machine parseable format.
     """
     with Session() as session:
         return [{
             'name':
             event.name,
             'location':
             event.location_label,
             'start':
             event.start_time_local.strftime('%I%p %a').lstrip('0'),
             'end':
             event.end_time_local.strftime('%I%p %a').lstrip('0'),
             'start_unix':
             int(mktime(event.start_time.utctimetuple())),
             'end_unix':
             int(mktime(event.end_time.utctimetuple())),
             'duration':
             event.minutes,
             'description':
             event.description,
             'panelists': [
                 panelist.attendee.full_name
                 for panelist in event.assigned_panelists
             ]
         } for event in sorted(
             session.query(Event).all(),
             key=lambda e: [e.start_time, e.location_label])]
Beispiel #34
0
def resave_all_attendees_and_groups():
    """
    Re-save all attendees and groups in the database. this is useful to re-run all validation code
    and allow re-calculation of automatically calculated values.  This is sometimes needed when
    doing database changes and we need to re-save everything.

    SAFETY: This -should- be safe to run at any time, but, for safety sake, recommend turning off
    any running sideboard servers before running this command.
    """
    Session.initialize_db(modify_tables=False, drop=False, initialize=True)
    with Session() as session:
        print("Re-saving all attendees....")
        [a.presave_adjustments() for a in session.query(Attendee).all()]
        print("Re-saving all groups....")
        [g.presave_adjustments() for g in session.query(Group).all()]
        print("Saving resulting changes to database (can take a few minutes)...")
    print("Done!")
Beispiel #35
0
    def index(self, message='', **params):
        if 'model' in params:
            self.export_model(selected_model=params['model'])

        return {
            'message': message,
            'tables': sorted(model.__name__ for model in Session.all_models())
        }
Beispiel #36
0
    def index(self, message='', **params):
        if 'model' in params:
            self.export_model(selected_model=params['model'])

        return {
            'message': message,
            'tables': sorted(model.__name__ for model in Session.all_models())
        }
Beispiel #37
0
def test_get_fk_from_id():
    with Session() as session:
        a = Attendee(first_name='Regular', last_name='Attendee')
        e = Email(fk_id=a.id, model='Attendee')
        session.add(a)
        session.add(e)
        session.commit()
        assert a == e.fk
Beispiel #38
0
 def access_set(id=None):
     try:
         from uber.models import Session
         with Session() as session:
             id = id or cherrypy.session['account_id']
             return set(session.admin_account(id).access_ints)
     except Exception:
         return set()
Beispiel #39
0
 def _run(self, raise_errors):
     with Session() as session:
         # performance: we use request_cached_context() to force cache invalidation
         # of variables like c.EMAIL_APPROVED_IDENTS
         with request_cached_context(clear_cache_on_start=True):
             self._init(session, raise_errors)
             self._send_all_emails()
             self._on_finished_run()
def no_more_custom_badges(attendee):
    if (attendee.badge_type != attendee.orig_value_of('badge_type') or attendee.is_new) \
            and attendee.has_personalized_badge and c.AFTER_PRINTED_BADGE_DEADLINE:
        with Session() as session:
            required_depts = [c.DEFAULT_REGDESK_INT, c.DEFAULT_STOPS_INT]
            if all(not session.admin_attendee().is_dept_head_of(d)
                   for d in required_depts):
                return 'Custom badges have already been ordered so you cannot use this badge type'
Beispiel #41
0
    def import_model(self, session, model_import, selected_model='', date_format="%Y-%m-%d"):
        model = Session.resolve_model(selected_model)
        message = ''

        cols = {col.name: getattr(model, col.name) for col in model.__table__.columns}
        result = csv.DictReader(model_import.file.read().decode('utf-8').split('\n'))
        id_list = []

        for row in result:
            if 'id' in row:
                id = row.pop('id')  # id needs special treatment

                try:
                    # get the instance if it already exists
                    model_instance = getattr(session, selected_model)(id, allow_invalid=True)
                except Exception:
                    session.rollback()
                    # otherwise, make a new one and add it to the session for when we commit
                    model_instance = model()
                    session.add(model_instance)

            for colname, val in row.items():
                col = cols[colname]
                if not val:
                    # in a lot of cases we'll just have the empty string, so we'll just
                    # do nothing for those cases
                    continue
                if isinstance(col.type, Boolean):
                    if isinstance(val, six.string_types):
                        val = val.strip().lower() not in ('f', 'false', 'n', 'no', '0')
                    else:
                        val = bool(val)
                elif isinstance(col.type, Choice):
                    # the export has labels, and we want to convert those back into their
                    # integer values, so let's look that up (note: we could theoretically
                    # modify the Choice class to do this automatically in the future)
                    label_lookup = {val: key for key, val in col.type.choices.items()}
                    val = label_lookup[val]
                elif isinstance(col.type, MultiChoice):
                    # the export has labels separated by ' / ' and we want to convert that
                    # back into a comma-separate list of integers
                    label_lookup = {val: key for key, val in col.type.choices}
                    vals = [label_lookup[label] for label in val.split(' / ')]
                    val = ','.join(map(str, vals))
                elif isinstance(col.type, UTCDateTime):
                    # we'll need to make sure we use whatever format string we used to
                    # export this date in the first place
                    try:
                        val = UTC.localize(datetime.strptime(val, date_format + ' %H:%M:%S'))
                    except Exception:
                        val = UTC.localize(datetime.strptime(val, date_format))
                elif isinstance(col.type, Date):
                    val = datetime.strptime(val, date_format).date()
                elif isinstance(col.type, Integer):
                    val = int(val)

                # now that we've converted val to whatever it actually needs to be, we
                # can just set it on the model
                setattr(model_instance, colname, val)

            try:
                session.commit()
            except Exception:
                log.error('ImportError', exc_info=True)
                session.rollback()
                message = 'Import unsuccessful'

            id_list.append(model_instance.id)

        all_instances = session.query(model).filter(model.id.in_(id_list)).all() if id_list else None

        return self.index(message, all_instances)
    readline.write_history_file(history_path)


if os.path.exists(history_path):
    readline.read_history_file(history_path)

try:
    import cherrypy
    import sideboard
    from uber.config import c
    from uber.models import AdminAccount, Attendee, initialize_db, Session

    initialize_db()

    # Make it easier to do session stuff at the command line
    session = Session().session

    admin = session.query(AdminAccount).filter(
        AdminAccount.attendee_id == Attendee.id,
        Attendee.email == '*****@*****.**'
    ).order_by(AdminAccount.id).first()

    if not admin:
        admin = session.query(AdminAccount).filter(
            AdminAccount.access.like('%{}%'.format(c.ADMIN))
        ).order_by(AdminAccount.id).first()

    if not admin:
        admin = session.query(AdminAccount).order_by(AdminAccount.id).first()

    if admin:
Beispiel #43
0
 def index(self, message='', all_instances=None):
     return {
         'message': message,
         'tables': sorted(model.__name__ for model in Session.all_models()),
         'attendees': all_instances
     }
Beispiel #44
0
def init_worker_process(*args, **kwargs):
    Session.initialize_db(initialize=True)
Beispiel #45
0
def drop_uber_db():
    assert c.DEV_BOX, 'drop_uber_db is only available on development boxes'
    Session.initialize_db(modify_tables=False, drop=True)
Beispiel #46
0
def notify_admins_of_pending_emails():
    from uber.tasks.email import notify_admins_of_pending_emails as notify_admins
    Session.initialize_db(initialize=True)
    results = timed(notify_admins)()
    if results:
        print('Notification emails sent to:\n{}'.format(dumps(results, indent=2, sort_keys=True)))
Beispiel #47
0
def reset_uber_db():
    assert c.DEV_BOX, 'reset_uber_db is only available on development boxes'
    Session.initialize_db(modify_tables=True, drop=True)
    insert_admin()