class UserSetting(JSONSettingsBase, db.Model): """User-specific settings""" __table_args__ = (db.Index(None, 'user_id', 'module', 'name'), db.Index(None, 'user_id', 'module'), db.UniqueConstraint('user_id', 'module', 'name'), db.CheckConstraint('module = lower(module)', 'lowercase_module'), db.CheckConstraint('name = lower(name)', 'lowercase_name'), { 'schema': 'users' }) user_id = db.Column(db.Integer, db.ForeignKey('users.users.id'), nullable=False, index=True) user = db.relationship('User', lazy=True, backref=db.backref('_all_settings', lazy='dynamic', cascade='all, delete-orphan')) @return_ascii def __repr__(self): return '<UserSetting({}, {}, {}, {!r})>'.format( self.user_id, self.module, self.name, self.value)
def __auto_table_args(): default_inheriting = 'not (is_default and protection_mode != {})'.format( ProtectionMode.inheriting.value) return (db.CheckConstraint(default_inheriting, 'default_inheriting'), db.CheckConstraint('is_default = (title IS NULL)', 'default_or_title'), db.CheckConstraint('not (is_default and is_deleted)', 'default_not_deleted'), { 'schema': 'attachments' })
def __auto_table_args(cls): checks = [ db.CheckConstraint("(text_color = '') = (background_color = '')", 'both_or_no_colors') ] if cls.colors_required: checks.append( db.CheckConstraint( "text_color != '' AND background_color != ''", 'colors_not_empty')) return tuple(checks)
def _make_check(type_, *cols): all_cols = {'session_block_id', 'contribution_id', 'break_id'} required_cols = all_cols & set(cols) forbidden_cols = all_cols - required_cols criteria = ['{} IS NULL'.format(col) for col in sorted(forbidden_cols)] criteria += ['{} IS NOT NULL'.format(col) for col in sorted(required_cols)] condition = 'type != {} OR ({})'.format(type_, ' AND '.join(criteria)) return db.CheckConstraint(condition, 'valid_{}'.format(type_.name.lower()))
def __auto_table_args(cls): args = [ db.Index('ix_{}_title_fts'.format(cls.__tablename__), db.func.to_tsvector('simple', cls.title), postgresql_using='gin') ] if cls.title_required: args.append(db.CheckConstraint("title != ''", 'valid_title')) return tuple(args)
def _make_checks(): available_columns = set(chain.from_iterable(cols for type_, cols in _columns_for_types.iteritems())) for link_type in VCRoomLinkType: required_cols = available_columns & _columns_for_types[link_type] forbidden_cols = available_columns - required_cols criteria = ['{} IS NULL'.format(col) for col in sorted(forbidden_cols)] criteria += ['{} IS NOT NULL'.format(col) for col in sorted(required_cols)] condition = 'link_type != {} OR ({})'.format(link_type, ' AND '.join(criteria)) yield db.CheckConstraint(condition, 'valid_{}_link'.format(link_type.name))
def _make_checks(allowed_link_types): available_columns = set( chain.from_iterable(cols for type_, cols in _columns_for_types.iteritems() if type_ in allowed_link_types)) yield db.CheckConstraint( '(event_id IS NULL) = (link_type = {})'.format(LinkType.category), 'valid_event_id') for link_type in allowed_link_types: required_cols = available_columns & _columns_for_types[link_type] forbidden_cols = available_columns - required_cols criteria = ['{} IS NULL'.format(col) for col in sorted(forbidden_cols)] criteria += [ '{} IS NOT NULL'.format(col) for col in sorted(required_cols) ] condition = 'link_type != {} OR ({})'.format(link_type, ' AND '.join(criteria)) yield db.CheckConstraint(condition, 'valid_{}_link'.format(link_type.name))
def __auto_table_args(cls): checks = [ db.CheckConstraint( "(room_id IS NULL) OR (venue_name = '' AND room_name = '')", 'no_custom_location_if_room'), db.CheckConstraint("(venue_id IS NULL) OR (venue_name = '')", 'no_venue_name_if_venue_id'), db.CheckConstraint("(room_id IS NULL) OR (venue_id IS NOT NULL)", 'venue_id_if_room_id') ] if cls.allow_location_inheritance: checks.append( db.CheckConstraint( "NOT inherit_location OR (venue_id IS NULL AND room_id IS NULL AND " "venue_name = '' AND room_name = '' AND address = '')", 'inherited_location')) fkeys = [ db.ForeignKeyConstraint( ['venue_id', 'room_id'], ['roombooking.rooms.location_id', 'roombooking.rooms.id']) ] return tuple(checks) + tuple(fkeys)
def __table_args__(cls): return (db.Index('ix_timetable_entries_start_dt_desc', cls.start_dt.desc()), _make_check(TimetableEntryType.SESSION_BLOCK, 'session_block_id'), _make_check(TimetableEntryType.CONTRIBUTION, 'contribution_id'), _make_check(TimetableEntryType.BREAK, 'break_id'), db.CheckConstraint( "type != {} OR parent_id IS NULL".format( TimetableEntryType.SESSION_BLOCK), 'valid_parent'), { 'schema': 'events' })
def __auto_table_args(cls): return (db.CheckConstraint( "(icon IS NULL) = (icon_metadata::text = 'null')", 'valid_icon'), db.CheckConstraint( "(logo IS NULL) = (logo_metadata::text = 'null')", 'valid_logo'), db.CheckConstraint("(parent_id IS NULL) = (id = 0)", 'valid_parent'), db.CheckConstraint("(id != 0) OR NOT is_deleted", 'root_not_deleted'), db.CheckConstraint( "(id != 0) OR (protection_mode != {})".format( ProtectionMode.inheriting), 'root_not_inheriting'), db.CheckConstraint('visibility IS NULL OR visibility > 0', 'valid_visibility'), { 'schema': 'categories' })
class UserEmail(db.Model): __tablename__ = 'emails' __table_args__ = ( db.CheckConstraint('email = lower(email)', 'lowercase_email'), db.Index(None, 'email', unique=True, postgresql_where=db.text('NOT is_user_deleted')), db.Index( None, 'user_id', unique=True, postgresql_where=db.text('is_primary AND NOT is_user_deleted')), { 'schema': 'users' }) #: the unique id of the email address id = db.Column(db.Integer, primary_key=True) #: the id of the associated user user_id = db.Column(db.Integer, db.ForeignKey('users.users.id'), nullable=False, index=True) #: the email address email = db.Column(db.String, nullable=False, index=True) #: if the email is the user's primary email is_primary = db.Column(db.Boolean, nullable=False, default=False) #: if the user is marked as deleted (e.g. due to a merge). DO NOT use this flag when actually deleting an email is_user_deleted = db.Column(db.Boolean, nullable=False, default=False) # relationship backrefs: # - user (User._all_emails) @return_ascii def __repr__(self): return '<UserEmail({}, {}, {})>'.format(self.id, self.email, self.is_primary, self.user)
class Contribution(DescriptionMixin, ProtectionManagersMixin, LocationMixin, AttachedItemsMixin, AttachedNotesMixin, PersonLinkDataMixin, AuthorsSpeakersMixin, CustomFieldsMixin, db.Model): __tablename__ = 'contributions' __auto_table_args = ( db.Index(None, 'friendly_id', 'event_id', unique=True, postgresql_where=db.text('NOT is_deleted')), db.Index(None, 'event_id', 'track_id'), db.Index(None, 'event_id', 'abstract_id'), db.Index(None, 'abstract_id', unique=True, postgresql_where=db.text('NOT is_deleted')), db.CheckConstraint( "session_block_id IS NULL OR session_id IS NOT NULL", 'session_block_if_session'), db.ForeignKeyConstraint( ['session_block_id', 'session_id'], ['events.session_blocks.id', 'events.session_blocks.session_id']), { 'schema': 'events' }) location_backref_name = 'contributions' disallowed_protection_modes = frozenset() inheriting_have_acl = True possible_render_modes = {RenderMode.html, RenderMode.markdown} default_render_mode = RenderMode.markdown allow_relationship_preloading = True PRELOAD_EVENT_ATTACHED_ITEMS = True PRELOAD_EVENT_NOTES = True ATTACHMENT_FOLDER_ID_COLUMN = 'contribution_id' @declared_attr def __table_args__(cls): return auto_table_args(cls) id = db.Column(db.Integer, primary_key=True) #: The human-friendly ID for the contribution friendly_id = db.Column(db.Integer, nullable=False, default=_get_next_friendly_id) event_id = db.Column(db.Integer, db.ForeignKey('events.events.id'), index=True, nullable=False) session_id = db.Column(db.Integer, db.ForeignKey('events.sessions.id'), index=True, nullable=True) session_block_id = db.Column(db.Integer, db.ForeignKey('events.session_blocks.id'), index=True, nullable=True) track_id = db.Column(db.Integer, db.ForeignKey('events.tracks.id', ondelete='SET NULL'), index=True, nullable=True) abstract_id = db.Column(db.Integer, db.ForeignKey('event_abstracts.abstracts.id'), index=True, nullable=True) type_id = db.Column(db.Integer, db.ForeignKey('events.contribution_types.id'), index=True, nullable=True) title = db.Column(db.String, nullable=False) duration = db.Column(db.Interval, nullable=False) board_number = db.Column(db.String, nullable=False, default='') keywords = db.Column(ARRAY(db.String), nullable=False, default=[]) is_deleted = db.Column(db.Boolean, nullable=False, default=False) #: The last user-friendly sub-contribution ID _last_friendly_subcontribution_id = db.deferred( db.Column('last_friendly_subcontribution_id', db.Integer, nullable=False, default=0)) event = db.relationship( 'Event', lazy=True, backref=db.backref( 'contributions', primaryjoin= '(Contribution.event_id == Event.id) & ~Contribution.is_deleted', cascade='all, delete-orphan', lazy=True)) session = db.relationship( 'Session', lazy=True, backref=db.backref( 'contributions', primaryjoin= '(Contribution.session_id == Session.id) & ~Contribution.is_deleted', lazy=True)) session_block = db.relationship( 'SessionBlock', lazy=True, foreign_keys=[session_block_id], backref=db.backref( 'contributions', primaryjoin= '(Contribution.session_block_id == SessionBlock.id) & ~Contribution.is_deleted', lazy=True)) type = db.relationship('ContributionType', lazy=True, backref=db.backref('contributions', lazy=True)) acl_entries = db.relationship('ContributionPrincipal', lazy=True, cascade='all, delete-orphan', collection_class=set, backref='contribution') subcontributions = db.relationship( 'SubContribution', lazy=True, primaryjoin= '(SubContribution.contribution_id == Contribution.id) & ~SubContribution.is_deleted', order_by='SubContribution.position', cascade='all, delete-orphan', backref=db.backref( 'contribution', primaryjoin='SubContribution.contribution_id == Contribution.id', lazy=True)) abstract = db.relationship( 'Abstract', lazy=True, backref=db.backref( 'contribution', primaryjoin= '(Contribution.abstract_id == Abstract.id) & ~Contribution.is_deleted', lazy=True, uselist=False)) track = db.relationship( 'Track', lazy=True, backref=db.backref( 'contributions', primaryjoin= '(Contribution.track_id == Track.id) & ~Contribution.is_deleted', lazy=True, passive_deletes=True)) #: External references associated with this contribution references = db.relationship('ContributionReference', lazy=True, cascade='all, delete-orphan', backref=db.backref('contribution', lazy=True)) #: Persons associated with this contribution person_links = db.relationship('ContributionPersonLink', lazy=True, cascade='all, delete-orphan', backref=db.backref('contribution', lazy=True)) #: Data stored in abstract/contribution fields field_values = db.relationship('ContributionFieldValue', lazy=True, cascade='all, delete-orphan', backref=db.backref('contribution', lazy=True)) #: The accepted paper revision _accepted_paper_revision = db.relationship( 'PaperRevision', lazy=True, viewonly=True, uselist=False, primaryjoin= ('(PaperRevision._contribution_id == Contribution.id) & (PaperRevision.state == {})' .format(PaperRevisionState.accepted)), ) #: Paper files not submitted for reviewing pending_paper_files = db.relationship( 'PaperFile', lazy=True, viewonly=True, primaryjoin= '(PaperFile._contribution_id == Contribution.id) & (PaperFile.revision_id.is_(None))', ) #: Paper reviewing judges paper_judges = db.relationship('User', secondary='event_paper_reviewing.judges', collection_class=set, lazy=True, backref=db.backref( 'judge_for_contributions', collection_class=set, lazy=True)) #: Paper content reviewers paper_content_reviewers = db.relationship( 'User', secondary='event_paper_reviewing.content_reviewers', collection_class=set, lazy=True, backref=db.backref('content_reviewer_for_contributions', collection_class=set, lazy=True)) #: Paper layout reviewers paper_layout_reviewers = db.relationship( 'User', secondary='event_paper_reviewing.layout_reviewers', collection_class=set, lazy=True, backref=db.backref('layout_reviewer_for_contributions', collection_class=set, lazy=True)) @declared_attr def _paper_last_revision(cls): # Incompatible with joinedload subquery = (db.select([ db.func.max(PaperRevision.submitted_dt) ]).where(PaperRevision._contribution_id == cls.id).correlate_except( PaperRevision).as_scalar()) return db.relationship('PaperRevision', uselist=False, lazy=True, viewonly=True, primaryjoin=db.and_( PaperRevision._contribution_id == cls.id, PaperRevision.submitted_dt == subquery)) # relationship backrefs: # - _paper_files (PaperFile._contribution) # - _paper_revisions (PaperRevision._contribution) # - attachment_folders (AttachmentFolder.contribution) # - legacy_mapping (LegacyContributionMapping.contribution) # - note (EventNote.contribution) # - timetable_entry (TimetableEntry.contribution) # - vc_room_associations (VCRoomEventAssociation.linked_contrib) @declared_attr def is_scheduled(cls): from fossir.modules.events.timetable.models.entries import TimetableEntry query = (db.exists([1]).where(TimetableEntry.contribution_id == cls.id).correlate_except(TimetableEntry)) return db.column_property(query, deferred=True) @declared_attr def subcontribution_count(cls): from fossir.modules.events.contributions.models.subcontributions import SubContribution query = (db.select([db.func.count(SubContribution.id)]).where( (SubContribution.contribution_id == cls.id) & ~SubContribution.is_deleted).correlate_except(SubContribution)) return db.column_property(query, deferred=True) @declared_attr def _paper_revision_count(cls): query = (db.select([db.func.count(PaperRevision.id) ]).where(PaperRevision._contribution_id == cls.id).correlate_except(PaperRevision)) return db.column_property(query, deferred=True) def __init__(self, **kwargs): # explicitly initialize those relationships with None to avoid # an extra query to check whether there is an object associated # when assigning a new one (e.g. during cloning) kwargs.setdefault('note', None) kwargs.setdefault('timetable_entry', None) super(Contribution, self).__init__(**kwargs) @classmethod def preload_acl_entries(cls, event): cls.preload_relationships(cls.query.with_parent(event), 'acl_entries') @property def location_parent(self): if self.session_block_id is not None: return self.session_block elif self.session_id is not None: return self.session else: return self.event @property def protection_parent(self): return self.session if self.session_id is not None else self.event @property def start_dt(self): return self.timetable_entry.start_dt if self.timetable_entry else None @property def end_dt(self): return self.timetable_entry.start_dt + self.duration if self.timetable_entry else None @property def start_dt_poster(self): if self.session and self.session.is_poster and self.timetable_entry and self.timetable_entry.parent: return self.timetable_entry.parent.start_dt @property def end_dt_poster(self): if self.session and self.session.is_poster and self.timetable_entry and self.timetable_entry.parent: return self.timetable_entry.parent.end_dt @property def duration_poster(self): if self.session and self.session.is_poster and self.timetable_entry and self.timetable_entry.parent: return self.timetable_entry.parent.duration @property def start_dt_display(self): """The displayed start time of the contribution. This is the start time of the poster session if applicable, otherwise the start time of the contribution itself. """ return self.start_dt_poster or self.start_dt @property def end_dt_display(self): """The displayed end time of the contribution. This is the end time of the poster session if applicable, otherwise the end time of the contribution itself. """ return self.end_dt_poster or self.end_dt @property def duration_display(self): """The displayed duration of the contribution. This is the duration of the poster session if applicable, otherwise the duration of the contribution itself. """ return self.duration_poster or self.duration @property def submitters(self): return { person_link for person_link in self.person_links if person_link.is_submitter } @locator_property def locator(self): return dict(self.event.locator, contrib_id=self.id) @property def verbose_title(self): return '#{} ({})'.format(self.friendly_id, self.title) @property def paper(self): return Paper(self) if self._paper_last_revision else None def is_paper_reviewer(self, user): return user in self.paper_content_reviewers or user in self.paper_layout_reviewers @return_ascii def __repr__(self): return format_repr(self, 'id', is_deleted=False, _text=self.title) def can_manage(self, user, role=None, allow_admin=True, check_parent=True, explicit_role=False): if super(Contribution, self).can_manage(user, role, allow_admin=allow_admin, check_parent=check_parent, explicit_role=explicit_role): return True if (check_parent and self.session_id is not None and self.session.can_manage(user, 'coordinate', allow_admin=allow_admin, explicit_role=explicit_role) and session_coordinator_priv_enabled(self.event, 'manage-contributions')): return True return False def get_non_inheriting_objects(self): """Get a set of child objects that do not inherit protection.""" return get_non_inheriting_objects(self) def is_user_associated(self, user, check_abstract=False): if user is None: return False if check_abstract and self.abstract and self.abstract.submitter == user: return True return any(pl.person.user == user for pl in self.person_links if pl.person.user)
class SurveyItem(db.Model): __tablename__ = 'items' __table_args__ = (db.CheckConstraint( "type != {type} OR (" "title IS NOT NULL AND " "is_required IS NOT NULL AND " "field_type IS NOT NULL AND " "parent_id IS NOT NULL AND " "display_as_section IS NULL)".format(type=SurveyItemType.question), 'valid_question'), db.CheckConstraint( "type != {type} OR (" "title IS NOT NULL AND " "is_required IS NULL AND " "field_type IS NULL AND " "field_data::text = '{{}}' AND " "parent_id IS NULL AND " "display_as_section IS NOT NULL)".format( type=SurveyItemType.section), 'valid_section'), db.CheckConstraint( "type != {type} OR (" "title IS NULL AND " "is_required IS NULL AND " "field_type IS NULL AND " "field_data::text = '{{}}' AND " "parent_id IS NOT NULL AND " "display_as_section IS NULL)".format( type=SurveyItemType.text), 'valid_text'), { 'schema': 'event_surveys' }) __mapper_args__ = {'polymorphic_on': 'type', 'polymorphic_identity': None} #: The ID of the item id = db.Column(db.Integer, primary_key=True) #: The ID of the survey survey_id = db.Column( db.Integer, db.ForeignKey('event_surveys.surveys.id'), index=True, nullable=False, ) #: The ID of the parent section item (NULL for top-level items, i.e. sections) parent_id = db.Column( db.Integer, db.ForeignKey('event_surveys.items.id'), index=True, nullable=True, ) #: The position of the item in the survey form position = db.Column(db.Integer, nullable=False, default=_get_next_position) #: The type of the survey item type = db.Column(PyIntEnum(SurveyItemType), nullable=False) #: The title of the item title = db.Column(db.String, nullable=True, default=_get_item_default_title) #: The description of the item description = db.Column(db.Text, nullable=False, default='') #: If a section should be rendered as a section display_as_section = db.Column(db.Boolean, nullable=True) # The following columns are only used for SurveyQuestion objects, but by # specifying them here we can access them withouy an extra query when we # query SurveyItem objects directly instead of going through a subclass. # This is done e.g. when using the Survey.top_level_items relationship. #: If the question must be answered (wtforms DataRequired) is_required = db.Column(db.Boolean, nullable=True) #: The type of the field used for the question field_type = db.Column(db.String, nullable=True) #: Field-specific data (such as choices for multi-select fields) field_data = db.Column(JSON, nullable=False, default={}) # relationship backrefs: # - parent (SurveySection.children) # - survey (Survey.items) def to_dict(self): """Return a json-serializable representation of this object. Subclasses must add their own data to the dict. """ return { 'type': self.type.name, 'title': self.title, 'description': self.description }
class Attachment(ProtectionMixin, VersionedResourceMixin, db.Model): __tablename__ = 'attachments' __table_args__ = ( # links: url but no file db.CheckConstraint( 'type != {} OR (link_url IS NOT NULL AND file_id IS NULL)'.format( AttachmentType.link.value), 'valid_link'), # we can't require the file_id to be NOT NULL for files because of the circular relationship... # but we can ensure that we never have both a file_id AND a link_url...for db.CheckConstraint('link_url IS NULL OR file_id IS NULL', 'link_or_file'), { 'schema': 'attachments' }) stored_file_table = 'attachments.files' stored_file_class = AttachmentFile stored_file_fkey = 'attachment_id' #: The ID of the attachment id = db.Column(db.Integer, primary_key=True) #: The ID of the folder the attachment belongs to folder_id = db.Column(db.Integer, db.ForeignKey('attachments.folders.id'), nullable=False, index=True) #: The ID of the user who created the attachment user_id = db.Column(db.Integer, db.ForeignKey('users.users.id'), index=True, nullable=False) #: If the attachment has been deleted is_deleted = db.Column(db.Boolean, nullable=False, default=False) #: The name of the attachment title = db.Column(db.String, nullable=False) #: The description of the attachment description = db.Column(db.Text, nullable=False, default='') #: The date/time when the attachment was created/modified modified_dt = db.Column(UTCDateTime, nullable=False, default=now_utc, onupdate=now_utc) #: The type of the attachment (file or link) type = db.Column(PyIntEnum(AttachmentType), nullable=False) #: The target URL for a link attachment link_url = db.Column(db.String, nullable=True) #: The user who created the attachment user = db.relationship('User', lazy=True, backref=db.backref('attachments', lazy='dynamic')) #: The folder containing the attachment folder = db.relationship('AttachmentFolder', lazy=True, backref=db.backref('all_attachments', lazy=True)) acl_entries = db.relationship('AttachmentPrincipal', backref='attachment', cascade='all, delete-orphan', collection_class=set) #: The ACL of the folder (used for ProtectionMode.protected) acl = association_proxy('acl_entries', 'principal', creator=lambda v: AttachmentPrincipal(principal=v)) # relationship backrefs: # - legacy_mapping (LegacyAttachmentMapping.attachment) @property def protection_parent(self): return self.folder @property def locator(self): return dict(self.folder.locator, attachment_id=self.id) def get_download_url(self, absolute=False): """Returns the download url for the attachment. During static site generation this returns a local URL for the file or the target URL for the link. :param absolute: If the returned URL should be absolute. """ if g.get('static_site'): return _offline_download_url(self) else: filename = self.file.filename if self.type == AttachmentType.file else 'go' return url_for('attachments.download', self, filename=filename, _external=absolute) @property def download_url(self): """The download url for the attachment""" return self.get_download_url() @property def absolute_download_url(self): """The absolute download url for the attachment""" return self.get_download_url(absolute=True) def can_access(self, user, *args, **kwargs): """Checks if the user is allowed to access the attachment. This is the case if the user has access to see the attachment or if the user can manage attachments for the linked object. """ return (super(Attachment, self).can_access(user, *args, **kwargs) or can_manage_attachments(self.folder.object, user)) @return_ascii def __repr__(self): return '<Attachment({}, {}, {}{}, {}, {})>'.format( self.id, self.title, self.file if self.type == AttachmentType.file else self.link_url, ', is_deleted=True' if self.is_deleted else '', self.protection_repr, self.folder_id)
class RegistrationInvitation(db.Model): """An invitation for someone to register""" __tablename__ = 'invitations' __table_args__ = (db.CheckConstraint( "(state = {state}) OR (registration_id IS NULL)".format( state=InvitationState.accepted), name='registration_state'), db.UniqueConstraint('registration_form_id', 'email'), { 'schema': 'event_registration' }) #: The ID of the invitation id = db.Column(db.Integer, primary_key=True) #: The UUID of the invitation uuid = db.Column(UUID, index=True, unique=True, nullable=False, default=lambda: unicode(uuid4())) #: The ID of the registration form registration_form_id = db.Column( db.Integer, db.ForeignKey('event_registration.forms.id'), index=True, nullable=False) #: The ID of the registration (if accepted) registration_id = db.Column( db.Integer, db.ForeignKey('event_registration.registrations.id'), index=True, unique=True, nullable=True) #: The state of the invitation state = db.Column(PyIntEnum(InvitationState), nullable=False, default=InvitationState.pending) #: Whether registration moderation should be skipped skip_moderation = db.Column(db.Boolean, nullable=False, default=False) #: The email of the invited person email = db.Column(db.String, nullable=False) #: The first name of the invited person first_name = db.Column(db.String, nullable=False) #: The last name of the invited person last_name = db.Column(db.String, nullable=False) #: The affiliation of the invited person affiliation = db.Column(db.String, nullable=False) #: The associated registration registration = db.relationship('Registration', lazy=True, backref=db.backref('invitation', lazy=True, uselist=False)) # relationship backrefs: # - registration_form (RegistrationForm.invitations) @locator_property def locator(self): return dict(self.registration_form.locator, invitation_id=self.id) @locator.uuid def locator(self): """A locator suitable for 'display' pages. Instead of the numeric ID it uses the UUID """ assert self.uuid is not None return dict(self.registration_form.locator, invitation=self.uuid) @return_ascii def __repr__(self): full_name = '{} {}'.format(self.first_name, self.last_name) return format_repr(self, 'id', 'registration_form_id', 'email', 'state', _text=full_name)
class Abstract(ProposalMixin, ProposalRevisionMixin, DescriptionMixin, CustomFieldsMixin, AuthorsSpeakersMixin, db.Model): """Represents an abstract that can be associated to a Contribution.""" __tablename__ = 'abstracts' __auto_table_args = ( db.Index(None, 'friendly_id', 'event_id', unique=True, postgresql_where=db.text('NOT is_deleted')), db.CheckConstraint( '(state = {}) OR (accepted_track_id IS NULL)'.format( AbstractState.accepted), name='accepted_track_id_only_accepted'), db.CheckConstraint( '(state = {}) OR (accepted_contrib_type_id IS NULL)'.format( AbstractState.accepted), name='accepted_contrib_type_id_only_accepted'), db.CheckConstraint( '(state = {}) = (merged_into_id IS NOT NULL)'.format( AbstractState.merged), name='merged_into_id_only_merged'), db.CheckConstraint( '(state = {}) = (duplicate_of_id IS NOT NULL)'.format( AbstractState.duplicate), name='duplicate_of_id_only_duplicate'), db.CheckConstraint( '(state IN ({}, {}, {}, {})) = (judge_id IS NOT NULL)'.format( AbstractState.accepted, AbstractState.rejected, AbstractState.merged, AbstractState.duplicate), name='judge_if_judged'), db.CheckConstraint( '(state IN ({}, {}, {}, {})) = (judgment_dt IS NOT NULL)'.format( AbstractState.accepted, AbstractState.rejected, AbstractState.merged, AbstractState.duplicate), name='judgment_dt_if_judged'), { 'schema': 'event_abstracts' }) possible_render_modes = {RenderMode.markdown} default_render_mode = RenderMode.markdown marshmallow_aliases = {'_description': 'content'} # Proposal mixin properties proposal_type = 'abstract' call_for_proposals_attr = 'cfa' delete_comment_endpoint = 'abstracts.delete_abstract_comment' create_comment_endpoint = 'abstracts.comment_abstract' edit_comment_endpoint = 'abstracts.edit_abstract_comment' create_review_endpoint = 'abstracts.review_abstract' edit_review_endpoint = 'abstracts.edit_review' create_judgment_endpoint = 'abstracts.judge_abstract' revisions_enabled = False @declared_attr def __table_args__(cls): return auto_table_args(cls) id = db.Column(db.Integer, primary_key=True) friendly_id = db.Column(db.Integer, nullable=False, default=_get_next_friendly_id) event_id = db.Column(db.Integer, db.ForeignKey('events.events.id'), index=True, nullable=False) title = db.Column(db.String, nullable=False) #: ID of the user who submitted the abstract submitter_id = db.Column(db.Integer, db.ForeignKey('users.users.id'), index=True, nullable=False) submitted_contrib_type_id = db.Column(db.Integer, db.ForeignKey( 'events.contribution_types.id', ondelete='SET NULL'), nullable=True, index=True) submitted_dt = db.Column(UTCDateTime, nullable=False, default=now_utc) modified_by_id = db.Column(db.Integer, db.ForeignKey('users.users.id'), nullable=True, index=True) modified_dt = db.Column( UTCDateTime, nullable=True, ) state = db.Column(PyIntEnum(AbstractState), nullable=False, default=AbstractState.submitted) submission_comment = db.Column(db.Text, nullable=False, default='') #: ID of the user who judged the abstract judge_id = db.Column(db.Integer, db.ForeignKey('users.users.id'), index=True, nullable=True) _judgment_comment = db.Column('judgment_comment', db.Text, nullable=False, default='') judgment_dt = db.Column( UTCDateTime, nullable=True, ) accepted_track_id = db.Column(db.Integer, db.ForeignKey('events.tracks.id', ondelete='SET NULL'), nullable=True, index=True) accepted_contrib_type_id = db.Column(db.Integer, db.ForeignKey( 'events.contribution_types.id', ondelete='SET NULL'), nullable=True, index=True) merged_into_id = db.Column(db.Integer, db.ForeignKey('event_abstracts.abstracts.id'), index=True, nullable=True) duplicate_of_id = db.Column(db.Integer, db.ForeignKey('event_abstracts.abstracts.id'), index=True, nullable=True) is_deleted = db.Column(db.Boolean, nullable=False, default=False) event = db.relationship( 'Event', lazy=True, backref=db.backref( 'abstracts', primaryjoin= '(Abstract.event_id == Event.id) & ~Abstract.is_deleted', cascade='all, delete-orphan', lazy=True)) #: User who submitted the abstract submitter = db.relationship( 'User', lazy=True, foreign_keys=submitter_id, backref=db.backref( 'abstracts', primaryjoin= '(Abstract.submitter_id == User.id) & ~Abstract.is_deleted', lazy='dynamic')) modified_by = db.relationship( 'User', lazy=True, foreign_keys=modified_by_id, backref=db.backref( 'modified_abstracts', primaryjoin= '(Abstract.modified_by_id == User.id) & ~Abstract.is_deleted', lazy='dynamic')) submitted_contrib_type = db.relationship( 'ContributionType', lazy=True, foreign_keys=submitted_contrib_type_id, backref=db.backref( 'proposed_abstracts', primaryjoin= '(Abstract.submitted_contrib_type_id == ContributionType.id) & ~Abstract.is_deleted', lazy=True, passive_deletes=True)) submitted_for_tracks = db.relationship( 'Track', secondary='event_abstracts.submitted_for_tracks', collection_class=set, backref=db.backref( 'abstracts_submitted', primaryjoin= 'event_abstracts.submitted_for_tracks.c.track_id == Track.id', secondaryjoin= '(event_abstracts.submitted_for_tracks.c.abstract_id == Abstract.id) & ~Abstract.is_deleted', collection_class=set, lazy=True, passive_deletes=True)) reviewed_for_tracks = db.relationship( 'Track', secondary='event_abstracts.reviewed_for_tracks', collection_class=set, backref=db.backref( 'abstracts_reviewed', primaryjoin= 'event_abstracts.reviewed_for_tracks.c.track_id == Track.id', secondaryjoin= '(event_abstracts.reviewed_for_tracks.c.abstract_id == Abstract.id) & ~Abstract.is_deleted', collection_class=set, lazy=True, passive_deletes=True)) #: User who judged the abstract judge = db.relationship( 'User', lazy=True, foreign_keys=judge_id, backref=db.backref( 'judged_abstracts', primaryjoin='(Abstract.judge_id == User.id) & ~Abstract.is_deleted', lazy='dynamic')) accepted_track = db.relationship( 'Track', lazy=True, backref=db.backref( 'abstracts_accepted', primaryjoin= '(Abstract.accepted_track_id == Track.id) & ~Abstract.is_deleted', lazy=True, passive_deletes=True)) accepted_contrib_type = db.relationship( 'ContributionType', lazy=True, foreign_keys=accepted_contrib_type_id, backref=db.backref( 'abstracts_accepted', primaryjoin= '(Abstract.accepted_contrib_type_id == ContributionType.id) & ~Abstract.is_deleted', lazy=True, passive_deletes=True)) merged_into = db.relationship( 'Abstract', lazy=True, remote_side=id, foreign_keys=merged_into_id, backref=db.backref('merged_abstracts', primaryjoin=(db.remote(merged_into_id) == id) & ~db.remote(is_deleted), lazy=True)) duplicate_of = db.relationship( 'Abstract', lazy=True, remote_side=id, foreign_keys=duplicate_of_id, backref=db.backref('duplicate_abstracts', primaryjoin=(db.remote(duplicate_of_id) == id) & ~db.remote(is_deleted), lazy=True)) #: Data stored in abstract/contribution fields field_values = db.relationship('AbstractFieldValue', lazy=True, cascade='all, delete-orphan', backref=db.backref('abstract', lazy=True)) #: Persons associated with this abstract person_links = db.relationship('AbstractPersonLink', lazy=True, cascade='all, delete-orphan', order_by='AbstractPersonLink.display_order', backref=db.backref('abstract', lazy=True)) # relationship backrefs: # - comments (AbstractComment.abstract) # - contribution (Contribution.abstract) # - duplicate_abstracts (Abstract.duplicate_of) # - email_logs (AbstractEmailLogEntry.abstract) # - files (AbstractFile.abstract) # - merged_abstracts (Abstract.merged_into) # - proposed_related_abstract_reviews (AbstractReview.proposed_related_abstract) # - reviews (AbstractReview.abstract) @property def candidate_contrib_types(self): contrib_types = set() for track in self.reviewed_for_tracks: if self.get_track_reviewing_state( track) == AbstractReviewingState.positive: review = next((x for x in self.reviews if x.track == track), None) contrib_types.add(review.proposed_contribution_type) return contrib_types @property def candidate_tracks(self): states = { AbstractReviewingState.positive, AbstractReviewingState.conflicting } return { t for t in self.reviewed_for_tracks if self.get_track_reviewing_state(t) in states } @property def edit_track_mode(self): if not inspect(self).persistent: return EditTrackMode.both elif self.state not in { AbstractState.submitted, AbstractState.withdrawn }: return EditTrackMode.none elif (self.public_state in (AbstractPublicState.awaiting, AbstractPublicState.withdrawn) and self.reviewed_for_tracks == self.submitted_for_tracks): return EditTrackMode.both else: return EditTrackMode.reviewed_for @property def public_state(self): if self.state != AbstractState.submitted: return getattr(AbstractPublicState, self.state.name) elif self.reviews: return AbstractPublicState.under_review else: return AbstractPublicState.awaiting @property def reviewing_state(self): if not self.reviews: return AbstractReviewingState.not_started track_states = { x: self.get_track_reviewing_state(x) for x in self.reviewed_for_tracks } positiveish_states = { AbstractReviewingState.positive, AbstractReviewingState.conflicting } if any(x == AbstractReviewingState.not_started for x in track_states.itervalues()): return AbstractReviewingState.in_progress elif all(x == AbstractReviewingState.negative for x in track_states.itervalues()): return AbstractReviewingState.negative elif all(x in positiveish_states for x in track_states.itervalues()): if len(self.reviewed_for_tracks) > 1: # Accepted for more than one track return AbstractReviewingState.conflicting elif any(x == AbstractReviewingState.conflicting for x in track_states.itervalues()): # The only accepted track is in conflicting state return AbstractReviewingState.conflicting else: return AbstractReviewingState.positive else: return AbstractReviewingState.mixed @property def score(self): scores = [x.score for x in self.reviews if x.score is not None] if not scores: return None return sum(scores) / len(scores) @property def data_by_field(self): return { value.contribution_field_id: value for value in self.field_values } @locator_property def locator(self): return dict(self.event.locator, abstract_id=self.id) @hybrid_property def judgment_comment(self): return MarkdownText(self._judgment_comment) @judgment_comment.setter def judgment_comment(self, value): self._judgment_comment = value @judgment_comment.expression def judgment_comment(cls): return cls._judgment_comment @property def verbose_title(self): return '#{} ({})'.format(self.friendly_id, self.title) @property def is_in_final_state(self): return self.state != AbstractState.submitted @return_ascii def __repr__(self): return format_repr(self, 'id', 'event_id', is_deleted=False, _text=text_to_repr(self.title)) def can_access(self, user): if not user: return False if self.submitter == user: return True if self.event.can_manage(user): return True if any(x.person.user == user for x in self.person_links): return True return self.can_judge(user) or self.can_convene( user) or self.can_review(user) def can_comment(self, user, check_state=False): if not user: return False if check_state and self.is_in_final_state: return False if not self.event.cfa.allow_comments: return False if self.user_owns( user) and self.event.cfa.allow_contributors_in_comments: return True return self.can_judge(user) or self.can_convene( user) or self.can_review(user) def can_convene(self, user): if not user: return False elif not self.event.can_manage( user, role='track_convener', explicit_role=True): return False elif self.event in user.global_convener_for_events: return True elif user.convener_for_tracks & self.reviewed_for_tracks: return True else: return False def can_review(self, user, check_state=False): # The total number of tracks/events a user is a reviewer for (fossir-wide) # is usually reasonably low so we just access the relationships instead of # sending a more specific query which would need to be cached to avoid # repeating it when performing this check on many abstracts. if not user: return False elif check_state and self.public_state not in ( AbstractPublicState.under_review, AbstractPublicState.awaiting): return False elif not self.event.can_manage( user, role='abstract_reviewer', explicit_role=True): return False elif self.event in user.global_abstract_reviewer_for_events: return True elif user.abstract_reviewer_for_tracks & self.reviewed_for_tracks: return True else: return False def can_judge(self, user, check_state=False): if not user: return False elif check_state and self.state != AbstractState.submitted: return False elif self.event.can_manage(user): return True elif self.event.cfa.allow_convener_judgment and self.can_convene(user): return True else: return False def can_edit(self, user): if not user: return False is_manager = self.event.can_manage(user) if not self.user_owns(user) and not is_manager: return False elif is_manager and self.public_state in ( AbstractPublicState.under_review, AbstractPublicState.withdrawn): return True elif (self.public_state == AbstractPublicState.awaiting and (is_manager or self.event.cfa.can_edit_abstracts(user))): return True else: return False def can_withdraw(self, user, check_state=False): if not user: return False elif self.event.can_manage(user) and ( not check_state or self.state != AbstractState.withdrawn): return True elif user == self.submitter and (not check_state or self.state == AbstractState.submitted): return True else: return False def can_see_reviews(self, user): return self.can_judge(user) or self.can_convene(user) def get_timeline(self, user=None): comments = [x for x in self.comments if x.can_view(user)] if user else self.comments reviews = [x for x in self.reviews if x.can_view(user)] if user else self.reviews return sorted(chain(comments, reviews), key=attrgetter('created_dt')) def get_track_reviewing_state(self, track): if track not in self.reviewed_for_tracks: raise ValueError("Abstract not in review for given track") reviews = self.get_reviews(group=track) if not reviews: return AbstractReviewingState.not_started rejections = any(x.proposed_action == AbstractAction.reject for x in reviews) acceptances = { x for x in reviews if x.proposed_action == AbstractAction.accept } if rejections and not acceptances: return AbstractReviewingState.negative elif acceptances and not rejections: proposed_contrib_types = { x.proposed_contribution_type for x in acceptances if x.proposed_contribution_type is not None } if len(proposed_contrib_types) <= 1: return AbstractReviewingState.positive else: return AbstractReviewingState.conflicting else: return AbstractReviewingState.mixed def get_track_question_scores(self): query = (db.session.query( AbstractReview.track_id, AbstractReviewQuestion, db.func.avg(AbstractReviewRating.value)).join( AbstractReviewRating.review).join( AbstractReviewRating.question).filter( AbstractReview.abstract == self, ~AbstractReviewQuestion.is_deleted, ~AbstractReviewQuestion.no_score).group_by( AbstractReview.track_id, AbstractReviewQuestion.id)) scores = defaultdict(lambda: defaultdict(lambda: None)) for track_id, question, score in query: scores[track_id][question] = score return scores def get_reviewed_for_groups(self, user, include_reviewed=False): already_reviewed = { each.track for each in self.get_reviews(user=user) } if include_reviewed else set() if self.event in user.global_abstract_reviewer_for_events: return self.reviewed_for_tracks | already_reviewed return (self.reviewed_for_tracks & user.abstract_reviewer_for_tracks) | already_reviewed def get_track_score(self, track): if track not in self.reviewed_for_tracks: raise ValueError("Abstract not in review for given track") reviews = [x for x in self.reviews if x.track == track] scores = [x.score for x in reviews if x.score is not None] if not scores: return None return sum(scores) / len(scores) def reset_state(self): self.state = AbstractState.submitted self.judgment_comment = '' self.judge = None self.judgment_dt = None self.accepted_track = None self.accepted_contrib_type = None self.merged_into = None self.duplicate_of = None def user_owns(self, user): if not user: return None return user == self.submitter or any(x.person.user == user for x in self.person_links)
def __auto_table_args(): return (db.CheckConstraint('module = lower(module)', 'lowercase_module'), db.CheckConstraint('name = lower(name)', 'lowercase_name'))
class SurveySubmission(db.Model): __tablename__ = 'submissions' __table_args__ = ( db.CheckConstraint('is_anonymous OR user_id IS NOT NULL', 'anonymous_or_user'), db.CheckConstraint('is_submitted = (submitted_dt IS NOT NULL)', 'dt_set_when_submitted'), db.CheckConstraint( '(is_submitted AND is_anonymous) = (user_id IS NULL)', 'submitted_and_anonymous_no_user'), { 'schema': 'event_surveys' }) #: The ID of the submission id = db.Column(db.Integer, primary_key=True) #: The human-friendly ID of the submission friendly_id = db.Column(db.Integer, nullable=False, default=_get_next_friendly_id) #: The ID of the survey survey_id = db.Column(db.Integer, db.ForeignKey('event_surveys.surveys.id'), index=True, nullable=False) #: The ID of the user who submitted the survey user_id = db.Column(db.Integer, db.ForeignKey('users.users.id'), index=True, nullable=True) #: The date/time when the survey was submitted submitted_dt = db.Column( UTCDateTime, nullable=True, ) #: Whether the survey submission is anonymous is_anonymous = db.Column(db.Boolean, nullable=False, default=False) #: Whether the survey was submitted is_submitted = db.Column(db.Boolean, nullable=False, default=False) #: List of non-submitted answers pending_answers = db.Column(JSON, default={}) #: The user who submitted the survey user = db.relationship('User', lazy=True, backref=db.backref('survey_submissions', lazy='dynamic')) #: The list of answers answers = db.relationship('SurveyAnswer', cascade='all, delete-orphan', lazy=True, backref=db.backref('submission', lazy=True)) # relationship backrefs: # - survey (Survey.submissions) @property def locator(self): return dict(self.survey.locator, submission_id=self.id) @return_ascii def __repr__(self): return '<SurveySubmission({}, {}, {})>'.format(self.id, self.survey_id, self.user_id)
class PaperRevision(ProposalRevisionMixin, RenderModeMixin, db.Model): __tablename__ = 'revisions' __table_args__ = ( db.Index(None, 'contribution_id', unique=True, postgresql_where=db.text('state = {}'.format( PaperRevisionState.accepted))), db.UniqueConstraint('contribution_id', 'submitted_dt'), db.CheckConstraint( '(state IN ({}, {}, {})) = (judge_id IS NOT NULL)'.format( PaperRevisionState.accepted, PaperRevisionState.rejected, PaperRevisionState.to_be_corrected), name='judge_if_judged'), db.CheckConstraint( '(state IN ({}, {}, {})) = (judgment_dt IS NOT NULL)'.format( PaperRevisionState.accepted, PaperRevisionState.rejected, PaperRevisionState.to_be_corrected), name='judgment_dt_if_judged'), { 'schema': 'event_paper_reviewing' }) possible_render_modes = {RenderMode.markdown} default_render_mode = RenderMode.markdown proposal_attr = 'paper' id = db.Column(db.Integer, primary_key=True) state = db.Column(PyIntEnum(PaperRevisionState), nullable=False, default=PaperRevisionState.submitted) _contribution_id = db.Column('contribution_id', db.Integer, db.ForeignKey('events.contributions.id'), index=True, nullable=False) submitter_id = db.Column(db.Integer, db.ForeignKey('users.users.id'), index=True, nullable=False) submitted_dt = db.Column(UTCDateTime, nullable=False, default=now_utc) judge_id = db.Column(db.Integer, db.ForeignKey('users.users.id'), index=True, nullable=True) judgment_dt = db.Column(UTCDateTime, nullable=True) _judgment_comment = db.Column('judgment_comment', db.Text, nullable=False, default='') _contribution = db.relationship('Contribution', lazy=True, backref=db.backref( '_paper_revisions', lazy=True, order_by=submitted_dt.asc())) submitter = db.relationship('User', lazy=True, foreign_keys=submitter_id, backref=db.backref('paper_revisions', lazy='dynamic')) judge = db.relationship('User', lazy=True, foreign_keys=judge_id, backref=db.backref('judged_papers', lazy='dynamic')) judgment_comment = RenderModeMixin.create_hybrid_property( '_judgment_comment') # relationship backrefs: # - comments (PaperReviewComment.paper_revision) # - files (PaperFile.paper_revision) # - reviews (PaperReview.revision) def __init__(self, *args, **kwargs): paper = kwargs.pop('paper', None) if paper: kwargs.setdefault('_contribution', paper.contribution) super(PaperRevision, self).__init__(*args, **kwargs) @return_ascii def __repr__(self): return format_repr(self, 'id', '_contribution_id', state=None) @locator_property def locator(self): return dict(self.paper.locator, revision_id=self.id) @property def paper(self): return self._contribution.paper @property def is_last_revision(self): return self == self.paper.last_revision @property def number(self): return self.paper.revisions.index(self) + 1 @paper.setter def paper(self, paper): self._contribution = paper.contribution def get_timeline(self, user=None): comments = [x for x in self.comments if x.can_view(user)] if user else self.comments reviews = [x for x in self.reviews if x.can_view(user)] if user else self.reviews judgment = [ PaperJudgmentProxy(self) ] if self.state == PaperRevisionState.to_be_corrected else [] return sorted(chain(comments, reviews, judgment), key=attrgetter('created_dt')) def get_reviews(self, group=None, user=None): reviews = [] if user and group: reviews = [ x for x in self.reviews if x.group.instance == group and x.user == user ] elif user: reviews = [x for x in self.reviews if x.user == user] elif group: reviews = [x for x in self.reviews if x.group.instance == group] return reviews def get_reviewed_for_groups(self, user, include_reviewed=False): from fossir.modules.events.papers.models.reviews import PaperTypeProxy reviewed_for = {x.type for x in self.reviews if x.user == user} if include_reviewed else set() if self.paper.cfp.content_reviewing_enabled and user in self.paper.cfp.content_reviewers: reviewed_for.add(PaperReviewType.content) if self.paper.cfp.layout_reviewing_enabled and user in self.paper.cfp.layout_reviewers: reviewed_for.add(PaperReviewType.layout) return set(map(PaperTypeProxy, reviewed_for)) def has_user_reviewed(self, user, review_type=None): from fossir.modules.events.papers.models.reviews import PaperReviewType if review_type: if isinstance(review_type, basestring): review_type = PaperReviewType[review_type] return any(review.user == user and review.type == review_type for review in self.reviews) else: layout_review = next( (review for review in self.reviews if review.user == user and review.type == PaperReviewType.layout), None) content_review = next( (review for review in self.reviews if review.user == user and review.type == PaperReviewType.content), None) if user in self._contribution.paper_layout_reviewers and user in self._contribution.paper_content_reviewers: return bool(layout_review and content_review) elif user in self._contribution.paper_layout_reviewers: return bool(layout_review) elif user in self._contribution.paper_content_reviewers: return bool(content_review) def get_spotlight_file(self): pdf_files = [ paper_file for paper_file in self.files if paper_file.content_type == 'application/pdf' ] return pdf_files[0] if len(pdf_files) == 1 else None
class Registration(db.Model): """Somebody's registration for an event through a registration form""" __tablename__ = 'registrations' __table_args__ = (db.CheckConstraint('email = lower(email)', 'lowercase_email'), db.Index(None, 'friendly_id', 'event_id', unique=True, postgresql_where=db.text('NOT is_deleted')), db.Index(None, 'registration_form_id', 'user_id', unique=True, postgresql_where=db.text('NOT is_deleted AND (state NOT IN (3, 4))')), db.Index(None, 'registration_form_id', 'email', unique=True, postgresql_where=db.text('NOT is_deleted AND (state NOT IN (3, 4))')), db.ForeignKeyConstraint(['event_id', 'registration_form_id'], ['event_registration.forms.event_id', 'event_registration.forms.id']), {'schema': 'event_registration'}) #: The ID of the object id = db.Column( db.Integer, primary_key=True ) #: The unguessable ID for the object uuid = db.Column( UUID, index=True, unique=True, nullable=False, default=lambda: unicode(uuid4()) ) #: The human-friendly ID for the object friendly_id = db.Column( db.Integer, nullable=False, default=_get_next_friendly_id ) #: The ID of the event event_id = db.Column( db.Integer, db.ForeignKey('events.events.id'), index=True, nullable=False ) #: The ID of the registration form registration_form_id = db.Column( db.Integer, db.ForeignKey('event_registration.forms.id'), index=True, nullable=False ) #: The ID of the user who registered user_id = db.Column( db.Integer, db.ForeignKey('users.users.id'), index=True, nullable=True ) #: The ID of the latest payment transaction associated with this registration transaction_id = db.Column( db.Integer, db.ForeignKey('events.payment_transactions.id'), index=True, unique=True, nullable=True ) #: The state a registration is in state = db.Column( PyIntEnum(RegistrationState), nullable=False, ) #: The base registration fee (that is not specific to form items) base_price = db.Column( db.Numeric(8, 2), # max. 999999.99 nullable=False, default=0 ) #: The price modifier applied to the final calculated price price_adjustment = db.Column( db.Numeric(8, 2), # max. 999999.99 nullable=False, default=0 ) #: Registration price currency currency = db.Column( db.String, nullable=False ) #: The date/time when the registration was recorded submitted_dt = db.Column( UTCDateTime, nullable=False, default=now_utc, ) #: The email of the registrant email = db.Column( db.String, nullable=False ) #: The first name of the registrant first_name = db.Column( db.String, nullable=False ) #: The last name of the registrant last_name = db.Column( db.String, nullable=False ) #: If the registration has been deleted is_deleted = db.Column( db.Boolean, nullable=False, default=False ) #: The unique token used in tickets ticket_uuid = db.Column( UUID, index=True, unique=True, nullable=False, default=lambda: unicode(uuid4()) ) #: Whether the person has checked in. Setting this also sets or clears #: `checked_in_dt`. checked_in = db.Column( db.Boolean, nullable=False, default=False ) #: The date/time when the person has checked in checked_in_dt = db.Column( UTCDateTime, nullable=True ) #: The Event containing this registration event = db.relationship( 'Event', lazy=True, backref=db.backref( 'registrations', lazy='dynamic' ) ) # The user linked to this registration user = db.relationship( 'User', lazy=True, backref=db.backref( 'registrations', lazy='dynamic' # XXX: a delete-orphan cascade here would delete registrations when NULLing the user ) ) #: The latest payment transaction associated with this registration transaction = db.relationship( 'PaymentTransaction', lazy=True, foreign_keys=[transaction_id], post_update=True ) #: The registration this data is associated with data = db.relationship( 'RegistrationData', lazy=True, cascade='all, delete-orphan', backref=db.backref( 'registration', lazy=True ) ) # relationship backrefs: # - invitation (RegistrationInvitation.registration) # - legacy_mapping (LegacyRegistrationMapping.registration) # - registration_form (RegistrationForm.registrations) # - transactions (PaymentTransaction.registration) @classmethod def get_all_for_event(cls, event): """Retrieve all registrations in all registration forms of an event.""" from fossir.modules.events.registration.models.forms import RegistrationForm return Registration.find_all(Registration.is_active, ~RegistrationForm.is_deleted, RegistrationForm.event_id == event.id, _join=Registration.registration_form) @hybrid_property def is_active(self): return not self.is_cancelled and not self.is_deleted @is_active.expression def is_active(cls): return ~cls.is_cancelled & ~cls.is_deleted @hybrid_property def is_cancelled(self): return self.state in (RegistrationState.rejected, RegistrationState.withdrawn) @is_cancelled.expression def is_cancelled(self): return self.state.in_((RegistrationState.rejected, RegistrationState.withdrawn)) @locator_property def locator(self): return dict(self.registration_form.locator, registration_id=self.id) @locator.registrant def locator(self): """A locator suitable for 'display' pages. It includes the UUID of the registration unless the current request doesn't contain the uuid and the registration is tied to the currently logged-in user. """ loc = self.registration_form.locator if (not self.user or not has_request_context() or self.user != session.user or request.args.get('token') == self.uuid): loc['token'] = self.uuid return loc @locator.uuid def locator(self): """A locator that uses uuid instead of id""" return dict(self.registration_form.locator, token=self.uuid) @property def can_be_modified(self): regform = self.registration_form return regform.is_modification_open and regform.is_modification_allowed(self) @property def data_by_field(self): return {x.field_data.field_id: x for x in self.data} @property def billable_data(self): return [data for data in self.data if data.price] @property def full_name(self): """Returns the user's name in 'Firstname Lastname' notation.""" return self.get_full_name(last_name_first=False) @property def display_full_name(self): """Return the full name using the user's preferred name format.""" return format_display_full_name(session.user, self) @property def is_ticket_blocked(self): """Check whether the ticket is blocked by a plugin""" return any(values_from_signal(signals.event.is_ticket_blocked.send(self), single_value=True)) @property def is_paid(self): """Returns whether the registration has been paid for.""" paid_states = {TransactionStatus.successful, TransactionStatus.pending} return self.transaction is not None and self.transaction.status in paid_states @property def payment_dt(self): """The date/time when the registration has been paid for""" return self.transaction.timestamp if self.is_paid else None @property def price(self): """The total price of the registration. This includes the base price, the field-specific price, and the custom price adjustment for the registrant. :rtype: Decimal """ # we convert the calculated price (float) to a string to avoid this: # >>> Decimal(100.1) # Decimal('100.099999999999994315658113919198513031005859375') # >>> Decimal('100.1') # Decimal('100.1') calc_price = Decimal(str(sum(data.price for data in self.data))) base_price = self.base_price or Decimal('0') price_adjustment = self.price_adjustment or Decimal('0') return (base_price + price_adjustment + calc_price).max(0) @property def summary_data(self): """Export registration data nested in sections and fields""" def _fill_from_regform(): for section in self.registration_form.sections: if not section.is_visible: continue summary[section] = OrderedDict() for field in section.fields: if not field.is_visible: continue summary[section][field] = field_summary[field] def _fill_from_registration(): for field, data in field_summary.iteritems(): section = field.parent summary.setdefault(section, OrderedDict()) if field not in summary[section]: summary[section][field] = data summary = OrderedDict() field_summary = {x.field_data.field: x for x in self.data} _fill_from_regform() _fill_from_registration() return summary @property def has_files(self): return any(item.storage_file_id is not None for item in self.data) @property def sections_with_answered_fields(self): return [x for x in self.registration_form.sections if any(child.id in self.data_by_field for child in x.children)] @classproperty @classmethod def order_by_name(cls): return db.func.lower(cls.last_name), db.func.lower(cls.first_name), cls.friendly_id @return_ascii def __repr__(self): return format_repr(self, 'id', 'registration_form_id', 'email', 'state', user_id=None, is_deleted=False, _text=self.full_name) def get_full_name(self, last_name_first=True, last_name_upper=False, abbrev_first_name=False): """Returns the user's in the specified notation. If not format options are specified, the name is returned in the 'Lastname, Firstname' notation. Note: Do not use positional arguments when calling this method. Always use keyword arguments! :param last_name_first: if "lastname, firstname" instead of "firstname lastname" should be used :param last_name_upper: if the last name should be all-uppercase :param abbrev_first_name: if the first name should be abbreviated to use only the first character """ return format_full_name(self.first_name, self.last_name, last_name_first=last_name_first, last_name_upper=last_name_upper, abbrev_first_name=abbrev_first_name) def get_personal_data(self): personal_data = {} for data in self.data: field = data.field_data.field if field.personal_data_type is not None and data.data: personal_data[field.personal_data_type.name] = data.friendly_data # might happen with imported legacy registrations (missing personal data) personal_data.setdefault('first_name', self.first_name) personal_data.setdefault('last_name', self.last_name) personal_data.setdefault('email', self.email) return personal_data def _render_price(self, price): return format_currency(price, self.currency, locale=session.lang or 'en_GB') def render_price(self): return self._render_price(self.price) def render_base_price(self): return self._render_price(self.base_price) def render_price_adjustment(self): return self._render_price(self.price_adjustment) def sync_state(self, _skip_moderation=True): """Sync the state of the registration""" initial_state = self.state regform = self.registration_form invitation = self.invitation moderation_required = (regform.moderation_enabled and not _skip_moderation and (not invitation or not invitation.skip_moderation)) with db.session.no_autoflush: payment_required = regform.event.has_feature('payment') and self.price and not self.is_paid if self.state is None: if moderation_required: self.state = RegistrationState.pending elif payment_required: self.state = RegistrationState.unpaid else: self.state = RegistrationState.complete elif self.state == RegistrationState.unpaid: if not self.price: self.state = RegistrationState.complete elif self.state == RegistrationState.complete: if payment_required: self.state = RegistrationState.unpaid if self.state != initial_state: signals.event.registration_state_updated.send(self, previous_state=initial_state) def update_state(self, approved=None, paid=None, rejected=None, _skip_moderation=False): """Update the state of the registration for a given action The accepted kwargs are the possible actions. ``True`` means that the action occured and ``False`` that it was reverted. """ if sum(action is not None for action in (approved, paid, rejected)) > 1: raise Exception("More than one action specified") initial_state = self.state regform = self.registration_form invitation = self.invitation moderation_required = (regform.moderation_enabled and not _skip_moderation and (not invitation or not invitation.skip_moderation)) with db.session.no_autoflush: payment_required = regform.event.has_feature('payment') and self.price if self.state == RegistrationState.pending: if approved and payment_required: self.state = RegistrationState.unpaid elif approved: self.state = RegistrationState.complete elif rejected: self.state = RegistrationState.rejected elif self.state == RegistrationState.unpaid: if paid: self.state = RegistrationState.complete elif approved is False: self.state = RegistrationState.pending elif self.state == RegistrationState.complete: if approved is False and payment_required is False and moderation_required: self.state = RegistrationState.pending elif paid is False and payment_required: self.state = RegistrationState.unpaid if self.state != initial_state: signals.event.registration_state_updated.send(self, previous_state=initial_state)
class RegistrationFormItem(db.Model): """Generic registration form item""" __tablename__ = 'form_items' __table_args__ = ( db.CheckConstraint( "(input_type IS NULL) = (type NOT IN ({t.field}, {t.field_pd}))". format(t=RegistrationFormItemType), name='valid_input'), db.CheckConstraint("NOT is_manager_only OR type = {type}".format( type=RegistrationFormItemType.section), name='valid_manager_only'), db.CheckConstraint( "(type IN ({t.section}, {t.section_pd})) = (parent_id IS NULL)". format(t=RegistrationFormItemType), name='top_level_sections'), db.CheckConstraint( "(type != {type}) = (personal_data_type IS NULL)".format( type=RegistrationFormItemType.field_pd), name='pd_field_type'), db.CheckConstraint( "NOT is_deleted OR (type NOT IN ({t.section_pd}, {t.field_pd}))". format(t=RegistrationFormItemType), name='pd_not_deleted'), db.CheckConstraint("is_enabled OR type != {type}".format( type=RegistrationFormItemType.section_pd), name='pd_section_enabled'), db.CheckConstraint( "is_enabled OR type != {type} OR personal_data_type NOT IN " "({pt.email}, {pt.first_name}, {pt.last_name})".format( type=RegistrationFormItemType.field_pd, pt=PersonalDataType), name='pd_field_enabled'), db.CheckConstraint( "is_required OR type != {type} OR personal_data_type NOT IN " "({pt.email}, {pt.first_name}, {pt.last_name})".format( type=RegistrationFormItemType.field_pd, pt=PersonalDataType), name='pd_field_required'), db.CheckConstraint( "current_data_id IS NULL OR type IN ({t.field}, {t.field_pd})". format(t=RegistrationFormItemType), name='current_data_id_only_field'), db.Index('ix_uq_form_items_pd_section', 'registration_form_id', unique=True, postgresql_where=db.text('type = {type}'.format( type=RegistrationFormItemType.section_pd))), db.Index('ix_uq_form_items_pd_field', 'registration_form_id', 'personal_data_type', unique=True, postgresql_where=db.text('type = {type}'.format( type=RegistrationFormItemType.field_pd))), { 'schema': 'event_registration' }) __mapper_args__ = {'polymorphic_on': 'type', 'polymorphic_identity': None} #: The ID of the object id = db.Column(db.Integer, primary_key=True) #: The ID of the registration form registration_form_id = db.Column( db.Integer, db.ForeignKey('event_registration.forms.id'), index=True, nullable=False) #: The type of the registration form item type = db.Column(PyIntEnum(RegistrationFormItemType), nullable=False) #: The type of a personal data field personal_data_type = db.Column(PyIntEnum(PersonalDataType), nullable=True) #: The ID of the parent form item parent_id = db.Column(db.Integer, db.ForeignKey('event_registration.form_items.id'), index=True, nullable=True) position = db.Column(db.Integer, nullable=False, default=_get_next_position) #: The title of this field title = db.Column(db.String, nullable=False) #: Description of this field description = db.Column(db.String, nullable=False, default='') #: Whether the field is enabled is_enabled = db.Column(db.Boolean, nullable=False, default=True) #: Whether field has been "deleted" is_deleted = db.Column(db.Boolean, nullable=False, default=False) #: determines if the field is mandatory is_required = db.Column(db.Boolean, nullable=False, default=False) #: if the section is only accessible to managers is_manager_only = db.Column(db.Boolean, nullable=False, default=False) #: input type of this field input_type = db.Column(db.String, nullable=True) #: unversioned field data data = db.Column(JSON, nullable=False, default=lambda: None) #: The ID of the latest data current_data_id = db.Column(db.Integer, db.ForeignKey( 'event_registration.form_field_data.id', use_alter=True), index=True, nullable=True) #: The latest value of the field current_data = db.relationship( 'RegistrationFormFieldData', primaryjoin= 'RegistrationFormItem.current_data_id == RegistrationFormFieldData.id', foreign_keys=current_data_id, lazy=True, post_update=True) #: The list of all versions of the field data data_versions = db.relationship( 'RegistrationFormFieldData', primaryjoin= 'RegistrationFormItem.id == RegistrationFormFieldData.field_id', foreign_keys='RegistrationFormFieldData.field_id', lazy=True, cascade='all, delete-orphan', backref=db.backref('field', lazy=False)) # The children of the item and the parent backref children = db.relationship('RegistrationFormItem', lazy=True, order_by='RegistrationFormItem.position', backref=db.backref('parent', lazy=False, remote_side=[id])) # relationship backrefs: # - parent (RegistrationFormItem.children) # - registration_form (RegistrationForm.form_items) @property def view_data(self): """Returns object with data that Angular can understand""" return dict(id=self.id, description=self.description, position=self.position) @hybrid_property def is_section(self): return self.type in { RegistrationFormItemType.section, RegistrationFormItemType.section_pd } @is_section.expression def is_section(cls): return cls.type.in_([ RegistrationFormItemType.section, RegistrationFormItemType.section_pd ]) @hybrid_property def is_field(self): return self.type in { RegistrationFormItemType.field, RegistrationFormItemType.field_pd } @is_field.expression def is_field(cls): return cls.type.in_([ RegistrationFormItemType.field, RegistrationFormItemType.field_pd ]) @hybrid_property def is_visible(self): return self.is_enabled and not self.is_deleted and ( self.parent_id is None or self.parent.is_visible) @is_visible.expression def is_visible(cls): sections = aliased(RegistrationFormSection) query = (db.session.query(literal(True)).filter( sections.id == cls.parent_id).filter(~sections.is_deleted).filter( sections.is_enabled).exists()) return cls.is_enabled & ~cls.is_deleted & ( (cls.parent_id == None) | query) # noqa @return_ascii def __repr__(self): return format_repr(self, 'id', 'registration_form_id', is_enabled=True, is_deleted=False, is_manager_only=False, _text=self.title)
class User(PersonMixin, db.Model): """fossir users""" # Useful when dealing with both users and groups in the same code is_group = False is_single_person = True is_network = False principal_order = 0 principal_type = PrincipalType.user __tablename__ = 'users' __table_args__ = ( db.Index(None, 'is_system', unique=True, postgresql_where=db.text('is_system')), db.CheckConstraint( 'NOT is_system OR (NOT is_blocked AND NOT is_pending AND NOT is_deleted)', 'valid_system_user'), db.CheckConstraint('id != merged_into_id', 'not_merged_self'), db.CheckConstraint( "is_pending OR (first_name != '' AND last_name != '')", 'not_pending_proper_names'), { 'schema': 'users' }) #: the unique id of the user id = db.Column(db.Integer, primary_key=True) #: the first name of the user first_name = db.Column(db.String, nullable=False, index=True) #: the last/family name of the user last_name = db.Column(db.String, nullable=False, index=True) # the title of the user - you usually want the `title` property! _title = db.Column('title', PyIntEnum(UserTitle), nullable=False, default=UserTitle.none) #: the phone number of the user phone = db.Column(db.String, nullable=False, default='') #: the address of the user address = db.Column(db.Text, nullable=False, default='') #: the id of the user this user has been merged into merged_into_id = db.Column(db.Integer, db.ForeignKey('users.users.id'), nullable=True) #: if the user is the default system user is_system = db.Column(db.Boolean, nullable=False, default=False) #: if the user is an administrator with unrestricted access to everything is_admin = db.Column(db.Boolean, nullable=False, default=False, index=True) #: if the user has been blocked is_blocked = db.Column(db.Boolean, nullable=False, default=False) #: if the user is pending (e.g. never logged in, only added to some list) is_pending = db.Column(db.Boolean, nullable=False, default=False) #: if the user is deleted (e.g. due to a merge) is_deleted = db.Column('is_deleted', db.Boolean, nullable=False, default=False) _affiliation = db.relationship('UserAffiliation', lazy=False, uselist=False, cascade='all, delete-orphan', backref=db.backref('user', lazy=True)) _primary_email = db.relationship( 'UserEmail', lazy=False, uselist=False, cascade='all, delete-orphan', primaryjoin='(User.id == UserEmail.user_id) & UserEmail.is_primary') _secondary_emails = db.relationship( 'UserEmail', lazy=True, cascade='all, delete-orphan', collection_class=set, primaryjoin='(User.id == UserEmail.user_id) & ~UserEmail.is_primary') _all_emails = db.relationship('UserEmail', lazy=True, viewonly=True, primaryjoin='User.id == UserEmail.user_id', collection_class=set, backref=db.backref('user', lazy=False)) #: the affiliation of the user affiliation = association_proxy('_affiliation', 'name', creator=lambda v: UserAffiliation(name=v)) #: the primary email address of the user email = association_proxy( '_primary_email', 'email', creator=lambda v: UserEmail(email=v, is_primary=True)) #: any additional emails the user might have secondary_emails = association_proxy('_secondary_emails', 'email', creator=lambda v: UserEmail(email=v)) #: all emails of the user. read-only; use it only for searching by email! also, do not use it between #: modifying `email` or `secondary_emails` and a session expire/commit! all_emails = association_proxy('_all_emails', 'email') # read-only! #: the user this user has been merged into merged_into_user = db.relationship( 'User', lazy=True, backref=db.backref('merged_from_users', lazy=True), remote_side='User.id', ) #: the users's favorite users favorite_users = db.relationship( 'User', secondary=favorite_user_table, primaryjoin=id == favorite_user_table.c.user_id, secondaryjoin=(id == favorite_user_table.c.target_id) & ~is_deleted, lazy=True, collection_class=set, backref=db.backref('favorite_of', lazy=True, collection_class=set), ) #: the users's favorite categories favorite_categories = db.relationship( 'Category', secondary=favorite_category_table, lazy=True, collection_class=set, backref=db.backref('favorite_of', lazy=True, collection_class=set), ) #: the user's category suggestions suggested_categories = db.relationship( 'SuggestedCategory', lazy='dynamic', order_by='SuggestedCategory.score.desc()', cascade='all, delete-orphan', backref=db.backref('user', lazy=True)) #: the active API key of the user api_key = db.relationship( 'APIKey', lazy=True, uselist=False, cascade='all, delete-orphan', primaryjoin='(User.id == APIKey.user_id) & APIKey.is_active', back_populates='user') #: the previous API keys of the user old_api_keys = db.relationship( 'APIKey', lazy=True, cascade='all, delete-orphan', order_by='APIKey.created_dt.desc()', primaryjoin='(User.id == APIKey.user_id) & ~APIKey.is_active', back_populates='user') #: the identities used by this user identities = db.relationship('Identity', lazy=True, cascade='all, delete-orphan', collection_class=set, backref=db.backref('user', lazy=False)) # relationship backrefs: # - _all_settings (UserSetting.user) # - abstract_comments (AbstractComment.user) # - abstract_email_log_entries (AbstractEmailLogEntry.user) # - abstract_reviewer_for_tracks (Track.abstract_reviewers) # - abstract_reviews (AbstractReview.user) # - abstracts (Abstract.submitter) # - agreements (Agreement.user) # - attachment_files (AttachmentFile.user) # - attachments (Attachment.user) # - blockings (Blocking.created_by_user) # - content_reviewer_for_contributions (Contribution.paper_content_reviewers) # - convener_for_tracks (Track.conveners) # - created_events (Event.creator) # - event_log_entries (EventLogEntry.user) # - event_notes_revisions (EventNoteRevision.user) # - event_persons (EventPerson.user) # - event_reminders (EventReminder.creator) # - favorite_of (User.favorite_users) # - global_abstract_reviewer_for_events (Event.global_abstract_reviewers) # - global_convener_for_events (Event.global_conveners) # - in_attachment_acls (AttachmentPrincipal.user) # - in_attachment_folder_acls (AttachmentFolderPrincipal.user) # - in_blocking_acls (BlockingPrincipal.user) # - in_category_acls (CategoryPrincipal.user) # - in_contribution_acls (ContributionPrincipal.user) # - in_event_acls (EventPrincipal.user) # - in_event_settings_acls (EventSettingPrincipal.user) # - in_session_acls (SessionPrincipal.user) # - in_settings_acls (SettingPrincipal.user) # - judge_for_contributions (Contribution.paper_judges) # - judged_abstracts (Abstract.judge) # - judged_papers (PaperRevision.judge) # - layout_reviewer_for_contributions (Contribution.paper_layout_reviewers) # - local_groups (LocalGroup.members) # - merged_from_users (User.merged_into_user) # - modified_abstract_comments (AbstractComment.modified_by) # - modified_abstracts (Abstract.modified_by) # - modified_review_comments (PaperReviewComment.modified_by) # - oauth_tokens (OAuthToken.user) # - owned_rooms (Room.owner) # - paper_competences (PaperCompetence.user) # - paper_reviews (PaperReview.user) # - paper_revisions (PaperRevision.submitter) # - registrations (Registration.user) # - requests_created (Request.created_by_user) # - requests_processed (Request.processed_by_user) # - reservations (Reservation.created_by_user) # - reservations_booked_for (Reservation.booked_for_user) # - review_comments (PaperReviewComment.user) # - static_sites (StaticSite.creator) # - survey_submissions (SurveySubmission.user) # - vc_rooms (VCRoom.created_by_user) @staticmethod def get_system_user(): return User.query.filter_by(is_system=True).one() @property def as_principal(self): """The serializable principal identifier of this user""" return 'User', self.id @property def as_avatar(self): # TODO: remove this after DB is free of Avatars from fossir.modules.users.legacy import AvatarUserWrapper avatar = AvatarUserWrapper(self.id) # avoid garbage collection avatar.user return avatar as_legacy = as_avatar @property def avatar_css(self): from fossir.modules.users.util import get_color_for_username return 'background-color: {};'.format( get_color_for_username(self.full_name)) @property def external_identities(self): """The external identities of the user""" return {x for x in self.identities if x.provider != 'fossir'} @property def local_identities(self): """The local identities of the user""" return {x for x in self.identities if x.provider == 'fossir'} @property def local_identity(self): """The main (most recently used) local identity""" identities = sorted(self.local_identities, key=attrgetter('safe_last_login_dt'), reverse=True) return identities[0] if identities else None @property def secondary_local_identities(self): """The local identities of the user except the main one""" return self.local_identities - {self.local_identity} @locator_property def locator(self): return {'user_id': self.id} @cached_property def settings(self): """Returns the user settings proxy for this user""" from fossir.modules.users import user_settings return user_settings.bind(self) @property def synced_fields(self): """The fields of the user whose values are currently synced. This set is always a subset of the synced fields define in synced fields of the idp in 'fossir.conf'. """ synced_fields = self.settings.get('synced_fields') # If synced_fields is missing or None, then all fields are synced if synced_fields is None: return multipass.synced_fields else: return set(synced_fields) & multipass.synced_fields @synced_fields.setter def synced_fields(self, value): value = set(value) & multipass.synced_fields if value == multipass.synced_fields: self.settings.delete('synced_fields') else: self.settings.set('synced_fields', list(value)) @property def synced_values(self): """The values from the synced identity for the user. Those values are not the actual user's values and might differ if they are not set as synchronized. """ identity = self._get_synced_identity(refresh=False) if identity is None: return {} return { field: (identity.data.get(field) or '') for field in multipass.synced_fields } def __contains__(self, user): """Convenience method for `user in user_or_group`.""" return self == user @return_ascii def __repr__(self): return format_repr(self, 'id', 'email', is_deleted=False, is_pending=False, _text=self.full_name) def can_be_modified(self, user): """If this user can be modified by the given user""" return self == user or user.is_admin def iter_identifiers(self, check_providers=False, providers=None): """Yields ``(provider, identifier)`` tuples for the user. :param check_providers: If True, providers are searched for additional identifiers once all existing identifiers have been yielded. :param providers: May be a set containing provider names to get only identifiers from the specified providers. """ done = set() for identity in self.identities: if providers is not None and identity.provider not in providers: continue item = (identity.provider, identity.identifier) done.add(item) yield item if not check_providers: return for identity_info in multipass.search_identities( providers=providers, exact=True, email=self.all_emails): item = (identity_info.provider.name, identity_info.identifier) if item not in done: yield item def get_full_name(self, *args, **kwargs): kwargs['_show_empty_names'] = True return super(User, self).get_full_name(*args, **kwargs) def make_email_primary(self, email): """Promotes a secondary email address to the primary email address :param email: an email address that is currently a secondary email """ secondary = next( (x for x in self._secondary_emails if x.email == email), None) if secondary is None: raise ValueError('email is not a secondary email address') self._primary_email.is_primary = False db.session.flush() secondary.is_primary = True db.session.flush() def synchronize_data(self, refresh=False): """Synchronize the fields of the user from the sync identity. This will take only into account :attr:`synced_fields`. :param refresh: bool -- Whether to refresh the synced identity with the sync provider before instead of using the stored data. (Only if the sync provider supports refresh.) """ identity = self._get_synced_identity(refresh=refresh) if identity is None: return for field in self.synced_fields: old_value = getattr(self, field) new_value = identity.data.get(field) or '' if field in ('first_name', 'last_name') and not new_value: continue if old_value == new_value: continue flash( _("Your {field_name} has been synchronised from '{old_value}' to '{new_value}'." ).format(field_name=syncable_fields[field], old_value=old_value, new_value=new_value)) setattr(self, field, new_value) def _get_synced_identity(self, refresh=False): sync_provider = multipass.sync_provider if sync_provider is None: return None identities = sorted( [x for x in self.identities if x.provider == sync_provider.name], key=attrgetter('safe_last_login_dt'), reverse=True) if not identities: return None identity = identities[0] if refresh and identity.multipass_data is not None: try: identity_info = sync_provider.refresh_identity( identity.identifier, identity.multipass_data) except IdentityRetrievalFailed: identity_info = None if identity_info: identity.data = identity_info.data return identity
class RegistrationRequest(db.Model): __tablename__ = 'registration_requests' __table_args__ = ( db.CheckConstraint('email = lower(email)', 'lowercase_email'), {'schema': 'users'} ) id = db.Column( db.Integer, primary_key=True ) comment = db.Column( db.Text, nullable=False, default='' ) email = db.Column( db.String, unique=True, nullable=False, index=True ) extra_emails = db.Column( ARRAY(db.String), nullable=False, default=[] ) user_data = db.Column( JSON, nullable=False ) _identity_data = db.Column( 'identity_data', JSON, nullable=False ) settings = db.Column( JSON, nullable=False ) @locator_property def locator(self): return {'request_id': self.id} @property def identity_data(self): identity_data = self._identity_data.copy() # if we have data in identity_data, it was converted from a # MultiDict so we need to convert it back. if 'data' in identity_data: tmp = MultiDict() tmp.update(self._identity_data['data']) identity_data['data'] = tmp return identity_data @identity_data.setter def identity_data(self, identity_data): identity_data = identity_data.copy() # `identity_data['data']` for multipass-based identities is a # MultiDict, but json-encoding it would lose all extra values # for a key, so we convert it to a dict of lists first if 'data' in identity_data: identity_data['data'] = dict(identity_data['data'].lists()) self._identity_data = identity_data @return_ascii def __repr__(self): return format_repr(self, 'id', 'email')
class PaymentTransaction(db.Model): """Payment transactions""" __tablename__ = 'payment_transactions' __table_args__ = (db.CheckConstraint('amount > 0', 'positive_amount'), {'schema': 'events'}) #: Entry ID id = db.Column( db.Integer, primary_key=True ) #: ID of the associated registration registration_id = db.Column( db.Integer, db.ForeignKey('event_registration.registrations.id'), index=True, nullable=False ) #: a :class:`TransactionStatus` status = db.Column( PyIntEnum(TransactionStatus), nullable=False ) #: the base amount the user needs to pay (without payment-specific fees) amount = db.Column( db.Numeric(8, 2), # max. 999999.99 nullable=False ) #: the currency of the payment (ISO string, e.g. EUR or USD) currency = db.Column( db.String, nullable=False ) #: the provider of the payment (e.g. manual, PayPal etc.) provider = db.Column( db.String, nullable=False, default='_manual' ) #: the date and time the transaction was recorded timestamp = db.Column( UTCDateTime, default=now_utc, nullable=False ) #: plugin-specific data of the payment data = db.Column( JSON, nullable=False ) #: The associated registration registration = db.relationship( 'Registration', lazy=True, foreign_keys=[registration_id], backref=db.backref( 'transactions', cascade='all, delete-orphan', lazy=True ) ) @property def plugin(self): from fossir.modules.events.payment.util import get_payment_plugins return get_payment_plugins().get(self.provider) @property def is_manual(self): return self.provider == '_manual' @return_ascii def __repr__(self): # in case of a new object we might not have the default status set status = TransactionStatus(self.status).name if self.status is not None else None return format_repr(self, 'id', 'registration_id', 'provider', 'amount', 'currency', 'timestamp', status=status) def render_details(self): """Renders the transaction details""" if self.is_manual: return render_template('events/payment/transaction_details_manual.html', transaction=self) plugin = self.plugin if plugin is None: return '[plugin not loaded: {}]'.format(self.provider) with plugin.plugin_context(): return plugin.render_transaction_details(self) @classmethod def create_next(cls, registration, amount, currency, action, provider=None, data=None): previous_transaction = registration.transaction new_transaction = PaymentTransaction(amount=amount, currency=currency, provider=provider, data=data) registration.transaction = new_transaction try: next_status = TransactionStatusTransition.next(previous_transaction, action, provider) except InvalidTransactionStatus as e: Logger.get('payment').exception("%s (data received: %r)", e, data) return None except InvalidManualTransactionAction as e: Logger.get('payment').exception("Invalid manual action code '%s' on initial status (data received: %r)", e, data) return None except InvalidTransactionAction as e: Logger.get('payment').exception("Invalid action code '%s' on initial status (data received: %r)", e, data) return None except IgnoredTransactionAction as e: Logger.get('payment').warning("%s (data received: %r)", e, data) return None except DoublePaymentTransaction: next_status = TransactionStatus.successful Logger.get('payment').info("Received successful payment for an already paid registration") new_transaction.status = next_status return new_transaction
class MenuEntry(MenuEntryMixin, db.Model): __tablename__ = 'menu_entries' __table_args__ = ( db.CheckConstraint( '(type IN ({type.internal_link.value}, {type.plugin_link.value}) AND name IS NOT NULL) OR ' '(type NOT IN ({type.internal_link.value}, {type.plugin_link.value}) and name IS NULL)' .format(type=MenuEntryType), 'valid_name'), db.CheckConstraint( '(type = {type.user_link.value}) = (link_url IS NOT NULL)'.format( type=MenuEntryType), 'valid_link_url'), db.CheckConstraint( '(type = {type.page.value} AND page_id IS NOT NULL) OR' ' (type != {type.page.value} AND page_id IS NULL)'.format( type=MenuEntryType), 'valid_page_id'), db.CheckConstraint( '(type = {type.plugin_link.value} AND plugin IS NOT NULL) OR' ' (type != {type.plugin_link.value} AND plugin IS NULL)'.format( type=MenuEntryType), 'valid_plugin'), db.CheckConstraint( '(type = {type.separator.value} AND title IS NULL) OR' ' (type IN ({type.user_link.value}, {type.page.value}) AND title IS NOT NULL) OR' ' (type NOT IN ({type.separator.value}, {type.user_link.value}, {type.page.value}))' .format(type=MenuEntryType), 'valid_title'), db.CheckConstraint("title != ''", 'title_not_empty'), db.Index( None, 'event_id', 'name', unique=True, postgresql_where=db.text( '(type = {type.internal_link.value} OR type = {type.plugin_link.value})' .format(type=MenuEntryType))), { 'schema': 'events' }) #: The ID of the menu entry id = db.Column(db.Integer, primary_key=True) #: The ID of the parent menu entry (NULL if root menu entry) parent_id = db.Column( db.Integer, db.ForeignKey('events.menu_entries.id'), index=True, nullable=True, ) #: The ID of the event which contains the menu event_id = db.Column(db.Integer, db.ForeignKey('events.events.id'), index=True, nullable=False) #: Whether the entry is visible in the event's menu is_enabled = db.Column(db.Boolean, nullable=False, default=True) #: The title of the menu entry (to be displayed to the user) title = db.Column( db.String, nullable=True, ) #: The name of the menu entry (to uniquely identify a default entry for a given event) name = db.Column(db.String, nullable=True) #: The relative position of the entry in the menu position = db.Column(db.Integer, nullable=False, default=_get_next_position) #: Whether the menu entry should be opened in a new tab or window new_tab = db.Column(db.Boolean, nullable=False, default=False) #: The target URL of a custom link link_url = db.Column(db.String, nullable=True, default=None) #: The name of the plugin from which the entry comes from (NULL if the entry does not come from a plugin) plugin = db.Column(db.String, nullable=True) #: The page ID if the entry is a page page_id = db.Column(db.Integer, db.ForeignKey('events.pages.id'), nullable=True, index=True, default=None) #: The type of the menu entry type = db.Column(PyIntEnum(MenuEntryType), nullable=False) #: The Event containing the menu entry event = db.relationship('Event', lazy=True, backref=db.backref('menu_entries', lazy='dynamic')) #: The page of the menu entry page = db.relationship( 'EventPage', lazy=True, cascade='all, delete-orphan', single_parent=True, backref=db.backref('menu_entry', lazy=False, uselist=False), ) #: The children menu entries and parent backref children = db.relationship( 'MenuEntry', order_by='MenuEntry.position', backref=db.backref('parent', remote_side=[id]), ) # relationship backrefs: # - parent (MenuEntry.children) @property def is_root(self): return self.parent_id is None @staticmethod def get_for_event(event): return (MenuEntry.query.with_parent(event).filter( MenuEntry.parent_id.is_(None)).options( joinedload('children')).order_by(MenuEntry.position).all()) def move(self, to): from_ = self.position new_pos = to value = -1 if to is None or to < 0: new_pos = to = -1 if from_ > to: new_pos += 1 from_, to = to, from_ to -= 1 value = 1 entries = (MenuEntry.query.with_parent(self.event).filter( MenuEntry.parent == self.parent, MenuEntry.position.between(from_ + 1, to))) for e in entries: e.position += value self.position = new_pos def insert(self, parent, position): if position is None or position < 0: position = -1 old_siblings = (MenuEntry.query.with_parent(self.event).filter( MenuEntry.position > self.position, MenuEntry.parent == self.parent)) for sibling in old_siblings: sibling.position -= 1 new_siblings = (MenuEntry.query.with_parent(self.event).filter( MenuEntry.position > position, MenuEntry.parent == parent)) for sibling in new_siblings: sibling.position += 1 self.parent = parent self.position = position + 1
class DesignerTemplate(db.Model): __tablename__ = 'designer_templates' __table_args__ = (db.CheckConstraint( "(event_id IS NULL) != (category_id IS NULL)", 'event_xor_category_id_null'), { 'schema': 'fossir' }) id = db.Column(db.Integer, primary_key=True) type = db.Column(PyIntEnum(TemplateType), nullable=False) title = db.Column(db.String, nullable=False) event_id = db.Column(db.Integer, db.ForeignKey('events.events.id'), index=True, nullable=True) category_id = db.Column(db.Integer, db.ForeignKey('categories.categories.id'), index=True, nullable=True) data = db.Column(JSON, nullable=False) background_image_id = db.Column( db.Integer, db.ForeignKey('fossir.designer_image_files.id'), index=False, nullable=True) backside_template_id = db.Column( db.ForeignKey('fossir.designer_templates.id'), index=True, nullable=True) is_clonable = db.Column(db.Boolean, nullable=False, default=True) is_system_template = db.Column(db.Boolean, nullable=False, default=False) category = db.relationship('Category', lazy=True, foreign_keys=category_id, backref=db.backref('designer_templates', cascade='all, delete-orphan', lazy=True)) event = db.relationship('Event', lazy=True, backref=db.backref('designer_templates', cascade='all, delete-orphan', lazy=True)) background_image = db.relationship('DesignerImageFile', lazy=True, foreign_keys=background_image_id, post_update=True) backside_template = db.relationship('DesignerTemplate', lazy=True, remote_side=id, backref='backside_template_of') # relationship backrefs: # - backside_template_of (DesignerTemplate.backside_template) # - default_ticket_template_of (Category.default_ticket_template) # - images (DesignerImageFile.template) # - ticket_for_regforms (RegistrationForm.ticket_template) def __init__(self, **kwargs): data = kwargs.pop('data', None) tpl_type = kwargs.get('type') if data is None: data = {'items': [], 'background_position': 'stretch'} size = DEFAULT_CONFIG[tpl_type]['tpl_size'] data.update({'width': size[0], 'height': size[1]}) super(DesignerTemplate, self).__init__(data=data, **kwargs) @hybrid_property def owner(self): return self.event if self.event else self.category @owner.comparator def owner(cls): return _OwnerComparator(cls) @locator_property def locator(self): return dict(self.owner.locator, template_id=self.id) @return_ascii def __repr__(self): return format_repr(self, 'id', 'event_id', 'category_id', _text=self.title)
from __future__ import unicode_literals from fossir.core.db import db _track_conveners_table = db.Table( 'track_conveners', db.metadata, db.Column('id', db.Integer, primary_key=True), db.Column('user_id', db.Integer, db.ForeignKey('users.users.id'), index=True, nullable=False), db.Column('event_id', db.Integer, db.ForeignKey('events.events.id'), index=True), db.Column('track_id', db.Integer, db.ForeignKey('events.tracks.id'), index=True), db.CheckConstraint('(track_id IS NULL) != (event_id IS NULL)', name='track_xor_event_id_null'), schema='events')
class Survey(db.Model): __tablename__ = 'surveys' __table_args__ = (db.CheckConstraint("anonymous OR require_user", 'valid_anonymous_user'), { 'schema': 'event_surveys' }) #: The ID of the survey id = db.Column(db.Integer, primary_key=True) #: The ID of the event event_id = db.Column(db.Integer, db.ForeignKey('events.events.id'), index=True, nullable=False) #: The title of the survey title = db.Column(db.String, nullable=False) uuid = db.Column(UUID, unique=True, nullable=False, default=lambda: unicode(uuid4())) # An introduction text for users of the survey introduction = db.Column(db.Text, nullable=False, default='') #: Whether submissions will not be linked to a user anonymous = db.Column(db.Boolean, nullable=False, default=False) #: Whether submissions must be done by logged users require_user = db.Column(db.Boolean, nullable=False, default=True) # #: Whether the survey is only for selected users private = db.Column(db.Boolean, nullable=False, default=False) #: Maximum number of submissions allowed submission_limit = db.Column(db.Integer, nullable=True) #: Datetime when the survey is open start_dt = db.Column(UTCDateTime, nullable=True) #: Datetime when the survey is closed end_dt = db.Column(UTCDateTime, nullable=True) #: Whether the survey has been marked as deleted is_deleted = db.Column(db.Boolean, nullable=False, default=False) #: Whether start notification has been already sent start_notification_sent = db.Column(db.Boolean, nullable=False, default=False) #: Whether to send survey related notifications to users notifications_enabled = db.Column(db.Boolean, nullable=False, default=False) #: Whether include Participants / Registrants when sending start notifications notify_participants = db.Column(db.Boolean, nullable=False, default=False) #: Email addresses to notify about the start of a survey start_notification_emails = db.Column(ARRAY(db.String), nullable=False, default=[]) #: Email addresses to notify about new submissions new_submission_emails = db.Column(ARRAY(db.String), nullable=False, default=[]) #: Whether answers can be saved without submitting the survey partial_completion = db.Column(db.Boolean, nullable=False, default=False) #: The last user-friendly submission ID _last_friendly_submission_id = db.deferred( db.Column('last_friendly_submission_id', db.Integer, nullable=False, default=0)) #: The list of submissions submissions = db.relationship('SurveySubmission', cascade='all, delete-orphan', lazy=True, backref=db.backref('survey', lazy=True)) #: The list of items items = db.relationship('SurveyItem', cascade='all, delete-orphan', lazy=True, backref=db.backref('survey', lazy=True)) #: The list of sections sections = db.relationship('SurveySection', lazy=True, viewonly=True, order_by='SurveySection.position') #: The list of questions questions = db.relationship('SurveyQuestion', lazy=True, viewonly=True) #: The Event containing this survey event = db.relationship('Event', lazy=True, backref=db.backref('surveys', lazy=True)) @hybrid_property def has_ended(self): return self.end_dt is not None and self.end_dt <= now_utc() @has_ended.expression def has_ended(cls): return (cls.end_dt != None) & (cls.end_dt <= now_utc()) # noqa @hybrid_property def has_started(self): return self.start_dt is not None and self.start_dt <= now_utc() @has_started.expression def has_started(cls): return (cls.start_dt != None) & (cls.start_dt <= now_utc()) # noqa @locator_property def locator(self): return {'confId': self.event_id, 'survey_id': self.id} @locator.token def locator(self): """A locator that adds the UUID if the survey is private""" token = self.uuid if self.private else None return dict(self.locator, token=token) @property def state(self): if not self.questions: return SurveyState.not_ready if not self.has_started: return SurveyState.ready_to_open if not self.has_ended: if not self.submissions: return SurveyState.active_and_clean return SurveyState.active_and_answered return SurveyState.finished @property def start_notification_recipients(self): """Returns all recipients of the notifications. This includes both explicit recipients and, if enabled, participants of the event. """ recipients = set(self.start_notification_emails) if self.notify_participants: recipients.update( reg.email for reg in Registration.get_all_for_event(self.event)) recipients.discard( '') # just in case there was an empty email address somewhere return recipients @hybrid_property def is_active(self): return not self.is_deleted and self.state in { SurveyState.active_and_answered, SurveyState.active_and_clean } @is_active.expression def is_active(cls): return ~cls.is_deleted & cls.questions.any( ) & cls.has_started & ~cls.has_ended @hybrid_property def is_visible(self): return (not self.is_deleted and self.state in { SurveyState.active_and_answered, SurveyState.active_and_clean, SurveyState.finished }) @is_visible.expression def is_visible(cls): return ~cls.is_deleted & cls.questions.any() & cls.has_started @return_ascii def __repr__(self): return '<Survey({}, {}): {}>'.format(self.id, self.event_id, self.title) def can_submit(self, user): return self.is_active and (not self.require_user or user) def open(self): if self.state != SurveyState.ready_to_open: raise fossirError("Survey can't be opened") self.start_dt = now_utc() def close(self): if self.state not in (SurveyState.active_and_clean, SurveyState.active_and_answered): raise fossirError("Survey can't be closed") self.end_dt = now_utc() def send_start_notification(self): if not self.notifications_enabled or self.start_notification_sent or not self.event.has_feature( 'surveys'): return template_module = get_template_module( 'events/surveys/emails/start_notification_email.txt', survey=self) email = make_email(bcc_list=self.start_notification_recipients, template=template_module) send_email(email, event=self.event, module='Surveys') logger.info('Sending start notification for survey %s', self) self.start_notification_sent = True def send_submission_notification(self, submission): if not self.notifications_enabled: return template_module = get_template_module( 'events/surveys/emails/new_submission_email.txt', submission=submission) email = make_email(bcc_list=self.new_submission_emails, template=template_module) send_email(email, event=self.event, module='Surveys') logger.info('Sending submission notification for survey %s', self)