Exemple #1
0
def create_contribution_from_abstract(abstract, contrib_session=None):
    event = abstract.event
    contrib_person_links = set()
    person_link_attrs = {
        '_title', 'address', 'affiliation', 'first_name', 'last_name', 'phone',
        'author_type', 'is_speaker', 'display_order'
    }
    for abstract_person_link in abstract.person_links:
        link = ContributionPersonLink(person=abstract_person_link.person)
        link.populate_from_attrs(abstract_person_link, person_link_attrs)
        contrib_person_links.add(link)

    duration = contrib_session.default_contribution_duration if contrib_session else timedelta(
        minutes=15)
    custom_fields_data = {
        'custom_{}'.format(field_value.contribution_field.id): field_value.data
        for field_value in abstract.field_values
    }
    return create_contribution(event, {
        'friendly_id': abstract.friendly_id,
        'title': abstract.title,
        'duration': duration,
        'description': abstract.description,
        'type': abstract.accepted_contrib_type,
        'track': abstract.accepted_track,
        'session': contrib_session,
        'person_link_data': {link: True
                             for link in contrib_person_links}
    },
                               custom_fields_data=custom_fields_data)
Exemple #2
0
def create_contribution_from_abstract(abstract, contrib_session=None):
    event = abstract.event
    contrib_person_links = set()
    person_link_attrs = {'_title', 'address', 'affiliation', 'first_name', 'last_name', 'phone', 'author_type',
                         'is_speaker', 'display_order'}
    for abstract_person_link in abstract.person_links:
        link = ContributionPersonLink(person=abstract_person_link.person)
        link.populate_from_attrs(abstract_person_link, person_link_attrs)
        contrib_person_links.add(link)

    if contrib_session:
        duration = contrib_session.default_contribution_duration
    else:
        duration = contribution_settings.get(event, 'default_duration')
    custom_fields_data = {'custom_{}'.format(field_value.contribution_field.id): field_value.data for
                          field_value in abstract.field_values}
    return create_contribution(event, {'friendly_id': abstract.friendly_id,
                                       'title': abstract.title,
                                       'duration': duration,
                                       'description': abstract.description,
                                       'type': abstract.accepted_contrib_type,
                                       'track': abstract.accepted_track,
                                       'session': contrib_session,
                                       'person_link_data': {link: True for link in contrib_person_links}},
                               custom_fields_data=custom_fields_data)
Exemple #3
0
def test_access_everyone(dummy_contribution, dummy_user, dummy_event):
    menu_entry = MenuEntry(event=dummy_event,
                           type=MenuEntryType.page,
                           access=MenuEntryAccess.everyone)
    person = EventPerson.create_from_user(dummy_user, dummy_event)
    assert menu_entry.can_access(dummy_user)
    contrib_person_link = ContributionPersonLink(person=person)
    dummy_contribution.person_links.append(contrib_person_link)
    assert menu_entry.can_access(dummy_user)
    contrib_person_link.is_speaker = True
    assert menu_entry.can_access(dummy_user)
Exemple #4
0
def test_access_participants_not_registered(dummy_contribution, dummy_user,
                                            dummy_event):
    menu_entry = MenuEntry(event=dummy_event,
                           type=MenuEntryType.page,
                           access=MenuEntryAccess.registered_participants)
    person = EventPerson.create_from_user(dummy_user, dummy_event)
    assert not menu_entry.can_access(dummy_user)
    contrib_person_link = ContributionPersonLink(person=person)
    dummy_contribution.person_links.append(contrib_person_link)
    assert not menu_entry.can_access(dummy_user)
    contrib_person_link.is_speaker = True
    assert not menu_entry.can_access(dummy_user)
Exemple #5
0
def create_contribution_from_abstract(abstract, contrib_session=None):
    from indico.modules.events.abstracts.settings import abstracts_settings

    event = abstract.event
    contrib_person_links = set()
    author_submission_rights = (
        event.cfa.contribution_submitters == SubmissionRightsType.all)
    person_link_attrs = {
        '_title', 'address', 'affiliation', 'first_name', 'last_name', 'phone',
        'author_type', 'is_speaker', 'display_order'
    }
    for abstract_person_link in abstract.person_links:
        link = ContributionPersonLink(person=abstract_person_link.person)
        link.populate_from_attrs(abstract_person_link, person_link_attrs)
        contrib_person_links.add(link)
    if contrib_session:
        duration = contrib_session.default_contribution_duration
    else:
        duration = contribution_settings.get(event, 'default_duration')
    custom_fields_data = {
        f'custom_{field_value.contribution_field.id}': field_value.data
        for field_value in abstract.field_values
    }
    contrib = create_contribution(event, {
        'friendly_id': abstract.friendly_id,
        'title': abstract.title,
        'duration': duration,
        'description': abstract.description,
        'type': abstract.accepted_contrib_type,
        'track': abstract.accepted_track,
        'session': contrib_session,
        'person_link_data': {
            link: (author_submission_rights or link.is_speaker)
            for link in contrib_person_links
        }
    },
                                  custom_fields_data=custom_fields_data)
    if abstracts_settings.get(event, 'copy_attachments') and abstract.files:
        folder = AttachmentFolder.get_or_create_default(contrib)
        for abstract_file in abstract.files:
            attachment = Attachment(user=abstract.submitter,
                                    type=AttachmentType.file,
                                    folder=folder,
                                    title=abstract_file.filename)
            attachment.file = AttachmentFile(
                user=abstract.submitter,
                filename=abstract_file.filename,
                content_type=abstract_file.content_type)
            with abstract_file.open() as fd:
                attachment.file.save(fd)
    db.session.flush()
    return contrib
Exemple #6
0
def test_access_speakers_contrib(dummy_contribution, dummy_user, dummy_event):
    set_feature_enabled(dummy_event, 'registration', True)
    menu_entry = MenuEntry(event=dummy_event,
                           type=MenuEntryType.page,
                           access=MenuEntryAccess.speakers)
    person = EventPerson.create_from_user(dummy_user, dummy_event)
    assert not menu_entry.can_access(dummy_user)
    contrib_person_link = ContributionPersonLink(person=person)
    dummy_contribution.person_links.append(contrib_person_link)
    assert not menu_entry.can_access(dummy_user)
    contrib_person_link.is_speaker = True
    assert menu_entry.can_access(dummy_user)
    dummy_contribution.is_deleted = True
    assert not menu_entry.can_access(dummy_user)
Exemple #7
0
    def _process(self):
        contribution_persons = (ContributionPersonLink.find(
            ContributionPersonLink.contribution.has(
                self._membership_filter)).all())
        contribution_persons.extend(
            SubContributionPersonLink.find(
                SubContributionPersonLink.subcontribution.has(
                    SubContribution.contribution.has(
                        self._membership_filter))).all())

        contribution_persons_dict = defaultdict(lambda: {
            'speaker': False,
            'primary_author': False,
            'secondary_author': False
        })
        for contrib_person in contribution_persons:
            person_roles = contribution_persons_dict[contrib_person.person]
            person_roles['speaker'] |= contrib_person.is_speaker
            person_roles[
                'primary_author'] |= contrib_person.author_type == AuthorType.primary
            person_roles[
                'secondary_author'] |= contrib_person.author_type == AuthorType.secondary
        return jsonify_template(
            'events/management/contribution_person_list.html',
            event_persons=contribution_persons_dict,
            event=self.event_new)
Exemple #8
0
    def _process(self):
        contribution_persons = (ContributionPersonLink.find(
            ContributionPersonLink.contribution.has(
                self._membership_filter)).all())
        contribution_persons.extend(
            SubContributionPersonLink.find(
                SubContributionPersonLink.subcontribution.has(
                    SubContribution.contribution.has(
                        self._membership_filter))).all())

        registered_persons = get_registered_event_persons(self.event)

        contribution_persons_dict = defaultdict(
            lambda: {
                'speaker': False,
                'primary_author': False,
                'secondary_author': False,
                'not_registered': True
            })
        for contrib_person in contribution_persons:
            person_roles = contribution_persons_dict[contrib_person.person]
            person_roles['speaker'] |= contrib_person.is_speaker
            person_roles[
                'primary_author'] |= contrib_person.author_type == AuthorType.primary
            person_roles[
                'secondary_author'] |= contrib_person.author_type == AuthorType.secondary
            person_roles[
                'not_registered'] = contrib_person.person not in registered_persons

        return jsonify_template(self.template,
                                event_persons=contribution_persons_dict,
                                event=self.event)
Exemple #9
0
def contribution_from_abstract(abstract, sess):
    from MaKaC.review import AbstractStatusAccepted

    event = abstract.as_new.event_new
    duration = sess.default_contribution_duration if sess else timedelta(
        minutes=15)
    links = []

    for auth in abstract.getAuthorList():
        author_type = AuthorType.primary if abstract.isPrimaryAuthor(
            auth) else AuthorType.secondary
        person_data = {
            'title': UserTitle.from_legacy(to_unicode(auth.getTitle())),
            'email': to_unicode(auth.getEmail()),
            'address': to_unicode(auth.getAddress()),
            'affiliation': to_unicode(auth.getAffiliation()),
            'first_name': to_unicode(auth.getFirstName()),
            'last_name': to_unicode(auth.getSurName()),
            'phone': to_unicode(auth.getTelephone())
        }

        person = person_from_data(person_data, event)
        person_data.pop('email')
        links.append(
            ContributionPersonLink(author_type=author_type,
                                   person=person,
                                   is_speaker=abstract.isSpeaker(auth),
                                   **person_data))

    custom_fields_data = {
        'custom_{}'.format(field_val.contribution_field.id): field_val.data
        for field_val in abstract.as_new.field_values
    }
    contrib = create_contribution(event, {
        'friendly_id': abstract.as_new.friendly_id,
        'title': to_unicode(abstract.getTitle()),
        'duration': duration,
        'person_link_data': {link: True
                             for link in links}
    },
                                  custom_fields_data=custom_fields_data)
    contrib.abstract = abstract.as_new
    contrib.description = abstract.as_new.description

    # if this is an accepted abstract, set track and type if present
    status = abstract.getCurrentStatus()
    if isinstance(status, AbstractStatusAccepted):
        track = abstract.as_new.accepted_track
        contrib_type = abstract.as_new.accepted_type
        if track:
            contrib.track_id = int(track.getId())
        if contrib_type:
            contrib.type = contrib_type

    if sess:
        contrib.session = sess

    return contrib
Exemple #10
0
def test_unused_event_person(db, dummy_user, dummy_event, create_contribution,
                             create_subcontribution, create_abstract):
    person = EventPerson.create_from_user(dummy_user, event=dummy_event)
    assert not person.has_links

    dummy_event.person_links.append(EventPersonLink(person=person))
    db.session.flush()
    assert person.has_links

    dummy_event.person_links.clear()
    db.session.flush()
    assert not person.has_links

    set_feature_enabled(dummy_event, 'abstracts', True)
    abstract = create_abstract(dummy_event,
                               'Dummy abstract',
                               submitter=dummy_user,
                               person_links=[
                                   AbstractPersonLink(
                                       person=person,
                                       is_speaker=True,
                                       author_type=AuthorType.primary)
                               ])
    assert person.has_links
    abstract.is_deleted = True
    assert not person.has_links

    contrib = create_contribution(
        dummy_event,
        'Dummy contribution',
        person_links=[ContributionPersonLink(person=person, is_speaker=True)])
    assert person.has_links
    contrib.is_deleted = True
    assert not person.has_links
    db.session.delete(contrib)

    contrib = create_contribution(dummy_event,
                                  'Dummy contribution',
                                  person_links=[])
    assert not person.has_links
    create_subcontribution(contrib,
                           'Dummy subcontribution',
                           person_links=[
                               SubContributionPersonLink(person=person,
                                                         is_speaker=True)
                           ])
    assert person.has_links

    contrib.is_deleted = True
    assert not person.has_links

    db.session.delete(contrib)
    assert not person.has_links
Exemple #11
0
 def _migrate_contribution_person_links(self, old_entry):
     person_link_map = {}
     person_link_data_map = defaultdict(list)
     for speaker in getattr(old_entry, '_speakers', []):
         person = self._get_person(speaker)
         if not person:
             continue
         person_link_data = self._get_person_data(speaker)
         person_link_data_map[person].append(person_link_data)
         link = person_link_map.get(person)
         if link:
             self._update_link_data(link, person_link_data_map[person])
             link.is_speaker = True
         else:
             link = ContributionPersonLink(person=person, is_speaker=True, **person_link_data)
             person_link_map[person] = link
             yield link
     for author in getattr(old_entry, '_primaryAuthors', []):
         person = self._get_person(author)
         if not person:
             continue
         person_link_data = self._get_person_data(author)
         person_link_data_map[person].append(person_link_data)
         link = person_link_map.get(person)
         if link:
             self._update_link_data(link, person_link_data_map[person])
             link.author_type = AuthorType.primary
         else:
             link = ContributionPersonLink(person=person, author_type=AuthorType.primary, **person_link_data)
             person_link_map[person] = link
             yield link
     for coauthor in getattr(old_entry, '_coAuthors', []):
         person = self._get_person(coauthor)
         if not person:
             continue
         person_link_data = self._get_person_data(coauthor)
         person_link_data_map[person].append(person_link_data)
         link = person_link_map.get(person)
         if link:
             self._update_link_data(link, person_link_data_map[person])
             if link.author_type == AuthorType.primary:
                 self.print_warning('%[yellow!]Primary author "{}" is also co-author'
                                    .format(person.full_name))
             else:
                 link.author_type = AuthorType.secondary
         else:
             link = ContributionPersonLink(person=person, author_type=AuthorType.secondary, **person_link_data)
             person_link_map[person] = link
             yield link
Exemple #12
0
def create_contribution_from_abstract(abstract, contrib_session=None):
    from indico.modules.events.abstracts.settings import abstracts_settings

    event = abstract.event
    contrib_person_links = set()
    person_link_attrs = {'_title', 'address', 'affiliation', 'first_name', 'last_name', 'phone', 'author_type',
                         'is_speaker', 'display_order'}
    for abstract_person_link in abstract.person_links:
        link = ContributionPersonLink(person=abstract_person_link.person)
        link.populate_from_attrs(abstract_person_link, person_link_attrs)
        contrib_person_links.add(link)

    if contrib_session:
        duration = contrib_session.default_contribution_duration
    else:
        duration = contribution_settings.get(event, 'default_duration')
    custom_fields_data = {'custom_{}'.format(field_value.contribution_field.id): field_value.data for
                          field_value in abstract.field_values}
    contrib = create_contribution(event, {'friendly_id': abstract.friendly_id,
                                          'title': abstract.title,
                                          'duration': duration,
                                          'description': abstract.description,
                                          'type': abstract.accepted_contrib_type,
                                          'track': abstract.accepted_track,
                                          'session': contrib_session,
                                          'person_link_data': {link: True for link in contrib_person_links}},
                                  custom_fields_data=custom_fields_data)
    if abstracts_settings.get(event, 'copy_attachments') and abstract.files:
        folder = AttachmentFolder.get_or_create_default(contrib)
        for abstract_file in abstract.files:
            attachment = Attachment(user=abstract.submitter, type=AttachmentType.file, folder=folder,
                                    title=abstract_file.filename)
            attachment.file = AttachmentFile(user=abstract.submitter, filename=abstract_file.filename,
                                             content_type=abstract_file.content_type)
            with abstract_file.open() as fd:
                attachment.file.save(fd)
    db.session.flush()
    return contrib
Exemple #13
0
    def _process(self):
        contribution_persons = ContributionPersonLink.find(
            ContributionPersonLink.contribution.has(self._membership_filter)
        ).all()
        contribution_persons.extend(
            SubContributionPersonLink.find(
                SubContributionPersonLink.subcontribution.has(SubContribution.contribution.has(self._membership_filter))
            ).all()
        )

        contribution_persons_dict = defaultdict(
            lambda: {"speaker": False, "primary_author": False, "secondary_author": False}
        )
        for contrib_person in contribution_persons:
            person_roles = contribution_persons_dict[contrib_person.person]
            person_roles["speaker"] |= contrib_person.is_speaker
            person_roles["primary_author"] |= contrib_person.author_type == AuthorType.primary
            person_roles["secondary_author"] |= contrib_person.author_type == AuthorType.secondary
        return jsonify_template(
            "events/management/contribution_person_list.html",
            event_persons=contribution_persons_dict,
            event=self.event_new,
        )
Exemple #14
0
 def _process_args(self):
     RHContributionDisplayBase._process_args(self)
     self.author = (ContributionPersonLink.find_one(
         ContributionPersonLink.author_type != AuthorType.none,
         id=request.view_args['person_id'],
         contribution=self.contrib))
Exemple #15
0
def import_contributions_from_csv(event, f):
    """Import timetable contributions from a CSV file into an event."""
    with csv_text_io_wrapper(f) as ftxt:
        reader = csv.reader(ftxt.read().splitlines())

    contrib_data = []
    for num_row, row in enumerate(reader, 1):
        try:
            start_dt, duration, title, first_name, last_name, affiliation, email = (
                value.strip() for value in row)
            email = email.lower()
        except ValueError:
            raise UserValueError(
                _('Row {}: malformed CSV data - please check that the number of columns is correct'
                  ).format(num_row))
        try:
            parsed_start_dt = event.tzinfo.localize(
                dateutil.parser.parse(start_dt)) if start_dt else None
        except ValueError:
            raise UserValueError(
                _('Row {row}: can\'t parse date: "{date}"').format(
                    row=num_row, date=start_dt))

        try:
            parsed_duration = timedelta(
                minutes=int(duration)) if duration else None
        except ValueError:
            raise UserValueError(
                _("Row {row}: can't parse duration: {duration}").format(
                    row=num_row, duration=duration))

        if not title:
            raise UserValueError(
                _('Row {}: contribution title is required').format(num_row))

        if email and not validate_email(email):
            raise UserValueError(
                _('Row {row}: invalid email address: {email}').format(
                    row=num_row, email=email))

        contrib_data.append({
            'start_dt':
            parsed_start_dt,
            'duration':
            parsed_duration or timedelta(minutes=20),
            'title':
            title,
            'speaker': {
                'first_name': first_name,
                'last_name': last_name,
                'affiliation': affiliation,
                'email': email
            }
        })

    # now that we're sure the data is OK, let's pre-allocate the friendly ids
    # for the contributions in question
    Contribution.allocate_friendly_ids(event, len(contrib_data))
    contributions = []
    all_changes = defaultdict(list)

    for contrib_fields in contrib_data:
        speaker_data = contrib_fields.pop('speaker')

        with track_time_changes() as changes:
            contribution = create_contribution(event,
                                               contrib_fields,
                                               extend_parent=True)

        contributions.append(contribution)
        for key, val in changes[event].items():
            all_changes[key].append(val)

        email = speaker_data['email']
        if not email:
            continue

        # set the information of the speaker
        person = get_event_person(event, speaker_data)
        link = ContributionPersonLink(person=person, is_speaker=True)
        link.populate_from_dict({
            'first_name': speaker_data['first_name'],
            'last_name': speaker_data['last_name'],
            'affiliation': speaker_data['affiliation']
        })
        contribution.person_links.append(link)

    return contributions, all_changes
Exemple #16
0
def test_dump_contribution(db, dummy_user, dummy_event, dummy_contribution,
                           create_entry, scheduled):
    from indico.modules.search.schemas import ContributionSchema

    person = EventPerson.create_from_user(dummy_user, dummy_event)
    dummy_contribution.person_links.append(
        ContributionPersonLink(person=person))
    dummy_contribution.description = 'A dummy contribution'

    extra = {'start_dt': None, 'end_dt': None}
    if scheduled:
        create_entry(dummy_contribution,
                     utc.localize(datetime(2020, 4, 20, 4, 20)))
        extra = {
            'start_dt': dummy_contribution.start_dt.isoformat(),
            'end_dt': dummy_contribution.end_dt.isoformat(),
        }

    db.session.flush()
    category_id = dummy_contribution.event.category_id
    schema = ContributionSchema()
    assert schema.dump(dummy_contribution) == {
        'description':
        'A dummy contribution',
        'location': {
            'address': '',
            'room_name': '',
            'venue_name': ''
        },
        'persons': [{
            'affiliation': None,
            'name': 'Guinea Pig'
        }],
        'title':
        'Dummy Contribution',
        'category_id':
        category_id,
        'category_path': [
            {
                'id': 0,
                'title': 'Home',
                'url': '/'
            },
            {
                'id': category_id,
                'title': 'dummy',
                'url': f'/category/{category_id}/'
            },
        ],
        'contribution_id':
        dummy_contribution.id,
        'duration':
        20,
        'event_id':
        0,
        'type':
        'contribution',
        'url':
        f'/event/0/contributions/{dummy_contribution.id}/',
        **extra
    }
Exemple #17
0
 def _checkParams(self, params):
     RHContributionDisplayBase._checkParams(self, params)
     self.author = (ContributionPersonLink.find_one(ContributionPersonLink.author_type != AuthorType.none,
                                                    id=request.view_args['person_id'],
                                                    contribution=self.contrib))
Exemple #18
0
def import_contributions_from_csv(event, f):
    """Import timetable contributions from a CSV file into an event."""
    reader = csv.reader(f.read().splitlines())
    contrib_data = []

    for num_row, row in enumerate(reader, 1):
        try:
            start_dt, duration, title, first_name, last_name, affiliation, email = \
                [to_unicode(value).strip() for value in row]
            email = email.lower()
        except ValueError:
            raise UserValueError(_('Row {}: malformed CSV data - please check that the number of columns is correct')
                                 .format(num_row))
        try:
            parsed_start_dt = event.tzinfo.localize(dateutil.parser.parse(start_dt)) if start_dt else None
        except ValueError:
            raise UserValueError(_("Row {row}: can't parse date: \"{date}\"").format(row=num_row, date=start_dt))

        try:
            parsed_duration = timedelta(minutes=int(duration)) if duration else None
        except ValueError:
            raise UserValueError(_("Row {row}: can't parse duration: {duration}").format(row=num_row,
                                                                                         duration=duration))

        if not title:
            raise UserValueError(_("Row {}: contribution title is required").format(num_row))

        if email and not validate_email(email):
            raise UserValueError(_("Row {row}: invalid email address: {email}").format(row=num_row, email=email))

        contrib_data.append({
            'start_dt': parsed_start_dt,
            'duration': parsed_duration or timedelta(minutes=20),
            'title': title,
            'speaker': {
                'first_name': first_name,
                'last_name': last_name,
                'affiliation': affiliation,
                'email': email
            }
        })

    # now that we're sure the data is OK, let's pre-allocate the friendly ids
    # for the contributions in question
    Contribution.allocate_friendly_ids(event, len(contrib_data))
    contributions = []
    all_changes = defaultdict(list)

    for contrib_fields in contrib_data:
        speaker_data = contrib_fields.pop('speaker')

        with track_time_changes() as changes:
            contribution = create_contribution(event, contrib_fields, extend_parent=True)

        contributions.append(contribution)
        for key, val in changes[event].viewitems():
            all_changes[key].append(val)

        email = speaker_data['email']
        if not email:
            continue

        # set the information of the speaker
        person = get_event_person(event, {
            'firstName': speaker_data['first_name'],
            'familyName': speaker_data['last_name'],
            'affiliation': speaker_data['affiliation'],
            'email': email
        })
        link = ContributionPersonLink(person=person, is_speaker=True)
        link.populate_from_dict({
            'first_name': speaker_data['first_name'],
            'last_name': speaker_data['last_name'],
            'affiliation': speaker_data['affiliation']
        })
        contribution.person_links.append(link)

    return contributions, all_changes
Exemple #19
0
 def _process_args(self):
     RHContributionDisplayBase._process_args(self)
     self.author = (ContributionPersonLink.find_one(ContributionPersonLink.author_type != AuthorType.none,
                                                    id=request.view_args['person_id'],
                                                    contribution=self.contrib))
Exemple #20
0
def test_filter_contrib_entries(app, db, dummy_event, create_user,
                                create_contribution, create_registration):
    registered_user = create_user(1)
    registered_speaker = create_user(2)
    unregistered_user = create_user(3)
    dummy_regform = RegistrationForm(event=dummy_event,
                                     title='Registration Form',
                                     currency='USD')
    dummy_event.registrations.append(
        create_registration(registered_user, dummy_regform))
    dummy_event.registrations.append(
        create_registration(registered_speaker, dummy_regform))
    registered_speaker_contribution = create_contribution(
        dummy_event,
        'Registered Speaker',
        person_links=[
            ContributionPersonLink(person=EventPerson.create_from_user(
                registered_speaker, dummy_event),
                                   is_speaker=True)
        ])
    registered_speaker_author_contribution = create_contribution(
        dummy_event,
        'Registered Speaker Author',
        person_links=[
            ContributionPersonLink(person=EventPerson.for_user(
                registered_speaker, dummy_event),
                                   is_speaker=True,
                                   author_type=AuthorType.primary)
        ])
    unregistered_speaker_registered_author_contribution = create_contribution(
        dummy_event,
        'Unregistered Speaker, Registered Author',
        person_links=[
            ContributionPersonLink(person=EventPerson.for_user(
                unregistered_user, dummy_event),
                                   is_speaker=True),
            ContributionPersonLink(person=EventPerson.for_user(
                registered_user, dummy_event),
                                   author_type=AuthorType.primary)
        ])
    registered_speaker_unregistered_author_contribution = create_contribution(
        dummy_event,
        'Registered Speaker, Unregistered Author',
        person_links=[
            ContributionPersonLink(person=EventPerson.for_user(
                registered_user, dummy_event),
                                   is_speaker=True),
            ContributionPersonLink(person=EventPerson.for_user(
                unregistered_user, dummy_event),
                                   author_type=AuthorType.primary)
        ])
    # Filter contributions with registered users
    with app.test_request_context():
        list_gen = ContributionListGenerator(dummy_event)
        list_gen.list_config['filters'] = {'items': {'people': {'registered'}}}
        result = list_gen.get_list_kwargs()
    assert result['contribs'] == [
        registered_speaker_contribution,
        registered_speaker_author_contribution,
        unregistered_speaker_registered_author_contribution,
        registered_speaker_unregistered_author_contribution
    ]

    # Filter contributions with registered speakers
    list_gen.list_config['filters'] = {'items': {'speakers': {'registered'}}}
    with app.test_request_context():
        result = list_gen.get_list_kwargs()
    assert result['contribs'] == [
        registered_speaker_contribution,
        registered_speaker_author_contribution,
        registered_speaker_unregistered_author_contribution
    ]

    # Filter contributions with unregistered speakers and registered users
    list_gen.list_config['filters'] = {
        'items': {
            'speakers': {'not_registered'},
            'people': {'registered'}
        }
    }
    with app.test_request_context():
        result = list_gen.get_list_kwargs()
    assert result['contribs'] == [
        unregistered_speaker_registered_author_contribution
    ]
Exemple #21
0
def import_contributions_from_csv(event, f):
    """Import timetable contributions from a CSV file into an event."""
    reader = csv.reader(f)
    contributions = []
    all_changes = defaultdict(list)
    for num_row, row in enumerate(reader, 1):
        try:
            start_dt, duration, title, first_name, last_name, affiliation, email = row
        except ValueError:
            raise UserValueError(
                _('Row {}: malformed CSV data - please check that the number of columns is correct'
                  ).format(num_row))
        try:
            parsed_start_dt = event.tzinfo.localize(
                dateutil.parser.parse(start_dt)) if start_dt else None
        except ValueError:
            raise UserValueError(
                _("Row {}: can't parse date: \"{}\"").format(
                    num_row, start_dt))

        try:
            parsed_duration = timedelta(
                minutes=int(duration)) if duration else None
        except ValueError:
            raise UserValueError(
                _("Row {}: can't parse duration: {}").format(
                    num_row, duration))

        if not title:
            raise UserValueError(
                _("Row {}: contribution title is required").format(num_row))

        with track_time_changes() as changes:
            contribution = create_contribution(
                event, {
                    'start_dt': parsed_start_dt,
                    'duration': parsed_duration or timedelta(minutes=20),
                    'title': title
                },
                extend_parent=True)

        contributions.append(contribution)
        for key, val in changes[event].viewitems():
            all_changes[key].append(val)

        if not email:
            continue

        # set the information of the speaker
        person = get_event_person(
            event, {
                'firstName': first_name,
                'familyName': last_name,
                'affiliation': affiliation,
                'email': email
            })
        link = ContributionPersonLink(person=person, is_speaker=True)
        link.populate_from_dict({
            'first_name': first_name,
            'last_name': last_name,
            'affiliation': affiliation,
            'email': email
        })
        contribution.person_links.append(link)

    return contributions, all_changes
Exemple #22
0
def test_dump_contribution(db, dummy_user, dummy_event, dummy_contribution,
                           create_entry, scheduled):
    from .schemas import ContributionRecordSchema

    person = EventPerson.create_from_user(dummy_user, dummy_event)
    dummy_contribution.person_links.append(
        ContributionPersonLink(person=person))
    dummy_contribution.description = 'A dummy <strong>contribution</strong>'

    extra = {}
    if scheduled:
        create_entry(dummy_contribution,
                     utc.localize(datetime(2020, 4, 20, 4, 20)))
        extra = {
            'start_dt': dummy_contribution.start_dt.isoformat(),
            'end_dt': dummy_contribution.end_dt.isoformat(),
        }

    db.session.flush()
    category_id = dummy_contribution.event.category_id
    schema = ContributionRecordSchema(context={'schema': 'test-contribs'})
    assert schema.dump(dummy_contribution) == {
        '$schema':
        'test-contribs',
        '_access': {
            'delete': ['IndicoAdmin'],
            'owner': ['IndicoAdmin'],
            'update': ['IndicoAdmin'],
        },
        '_data': {
            'description': 'A dummy contribution',
            'location': {
                'address': '',
                'room_name': '',
                'venue_name': ''
            },
            'persons': [{
                'name': 'Guinea Pig'
            }],
            'site': 'http://localhost',
            'title': 'Dummy Contribution',
        },
        'category_id':
        category_id,
        'category_path': [
            {
                'id': 0,
                'title': 'Home',
                'url': '/'
            },
            {
                'id': category_id,
                'title': 'dummy',
                'url': f'/category/{category_id}/'
            },
        ],
        'contribution_id':
        dummy_contribution.id,
        'duration':
        20,
        'event_id':
        0,
        'type':
        'contribution',
        'url':
        f'http://localhost/event/0/contributions/{dummy_contribution.id}/',
        **extra
    }
Exemple #23
0
 def _checkParams(self, params):
     RHContributionDisplayBase._checkParams(self, params)
     self.author = (ContributionPersonLink.find_one(
         ContributionPersonLink.author_type != AuthorType.none,
         id=request.view_args['person_id'],
         contribution=self.contrib))