コード例 #1
0
class AttachmentPackageForm(IndicoForm):
    added_since = IndicoDateField(
        _('Added Since'), [Optional()],
        description=_('Include only attachments uploaded after this date'))

    filter_type = IndicoRadioField(_('Include'), [DataRequired()])

    sessions = IndicoSelectMultipleCheckboxField(
        _('Sessions'),
        [HiddenUnless('filter_type', 'sessions'),
         DataRequired()],
        description=_('Include materials from selected sessions'),
        coerce=int)
    contributions = IndicoSelectMultipleCheckboxField(
        _('Contributions'),
        [HiddenUnless('filter_type', 'contributions'),
         DataRequired()],
        description=_('Include materials from selected contributions'),
        coerce=int)
    dates = IndicoSelectMultipleCheckboxField(
        _('Events scheduled on'),
        [HiddenUnless('filter_type', 'dates'),
         DataRequired()],
        description=_(
            'Include materials from sessions/contributions scheduled '
            'on the selected dates'))
コード例 #2
0
ファイル: choices.py プロジェクト: vireshbackup/indico
class MultiSelectConfigForm(object):
    options = MultiStringField(_('Options'), [DataRequired()], field=('option', _('option')), unique=True,
                               uuid_field='id', sortable=True, description=_('Specify the answers the user can select'))
    min_choices = IntegerField(_("Minimum choices"), [HiddenUnless('is_required'), Optional(), NumberRange(min=0)],
                               description=_("The minimum amount of options the user has to choose."))
    max_choices = IntegerField(_("Maximum choices"), [HiddenUnless('is_required'), Optional(), NumberRange(min=1)],
                               description=_("The maximum amount of options the user may choose."))

    def _validate_min_max_choices(self):
        if (self.min_choices.data is not None and self.max_choices.data is not None and
                self.min_choices.data > self.max_choices.data):
            raise ValidationError(_('Maximum choices must be greater than minimum choices.'))

    def validate_min_choices(self, field):
        if field.data is None:
            return
        if field.data >= len(self.options.data):
            raise ValidationError(_("Minimum choices must be fewer than the total number of options."))

    def validate_max_choices(self, field):
        if field.data is None:
            return
        self._validate_min_max_choices()
        if field.data > len(self.options.data):
            raise ValidationError(_("Maximum choices must be fewer or equal than the total number of options."))
コード例 #3
0
class TicketsForm(IndicoForm):
    tickets_enabled = BooleanField(_('Enable Tickets'), widget=SwitchWidget(),
                                   description=_('Create tickets for registrations using this registration form.'))
    ticket_on_email = BooleanField(_('Send with an e-mail'), [HiddenUnless('tickets_enabled',
                                                                           preserve_data=True)],
                                   widget=SwitchWidget(),
                                   description=_('Attach PDF ticket to the email sent to a user after completing '
                                                 'their registration.'))
    ticket_on_event_page = BooleanField(_('Download from event homepage'), [HiddenUnless('tickets_enabled',
                                                                                         preserve_data=True)],
                                        widget=SwitchWidget(),
                                        description=_('Allow users to download their ticket from the '
                                                      'conference homepage.'))
    ticket_on_summary_page = BooleanField(_('Download from summary page'), [HiddenUnless('tickets_enabled',
                                                                                         preserve_data=True)],
                                          widget=SwitchWidget(),
                                          description=_('Allow users to download their ticket from the registration '
                                                        'summary page.'))

    ticket_template_id = SelectField(_('Ticket template'), [HiddenUnless('tickets_enabled', preserve_data=True),
                                                            Optional()], coerce=int)

    def __init__(self, *args, **kwargs):
        event = kwargs.pop('event')
        super(TicketsForm, self).__init__(*args, **kwargs)
        default_tpl = get_default_template_on_category(event.category)
        all_templates = set(event.designer_templates) | get_inherited_templates(event)
        badge_templates = [(tpl.id, tpl.title) for tpl in all_templates
                           if tpl.type == TemplateType.badge and tpl != default_tpl]
        # Show the default template first
        badge_templates.insert(0, (default_tpl.id, '{} ({})'.format(default_tpl.title, _('Default category template'))))
        self.ticket_template_id.choices = badge_templates
コード例 #4
0
ファイル: forms.py プロジェクト: javfg/indico
class NewsSettingsForm(IndicoForm):
    show_recent = BooleanField(
        'Show headlines',
        widget=SwitchWidget(),
        description=_(
            'Whether to show the latest news headlines on the Indico home page.'
        ))
    max_entries = IntegerField(
        _('Max. headlines'),
        [HiddenUnless('show_recent'),
         DataRequired(),
         NumberRange(min=1)],
        description=
        _('The maximum number of news headlines to show on the Indico home page.'
          ))
    max_age = IntegerField(
        _('Max. age'),
        [HiddenUnless('show_recent'),
         InputRequired(),
         NumberRange(min=0)],
        description=_(
            'The maximum age in days for news to show up on the Indico home page. '
            'Setting it to 0 will show news no matter how old they are.'))
    new_days = IntegerField(
        _('"New" threshold'),
        [InputRequired(), NumberRange(min=0)],
        description=_(
            'The maximum age in days for news to be considered "new". Setting it to 0 '
            'will disable the "new" label altogether.'))
コード例 #5
0
ファイル: forms.py プロジェクト: stomanin/indico
class TicketsForm(IndicoForm):
    tickets_enabled = BooleanField(
        _('Enable Tickets'),
        widget=SwitchWidget(),
        description=_(
            'Create tickets for registrations using this registration form.'))
    ticket_on_email = BooleanField(
        _('Attach to registration e-mail'),
        [HiddenUnless('tickets_enabled', preserve_data=True)],
        widget=SwitchWidget(),
        description=_(
            'Attach PDF ticket to the email sent to a user after completing '
            'their registration.'))
    ticket_on_event_page = BooleanField(
        _('Download from event homepage'),
        [HiddenUnless('tickets_enabled', preserve_data=True)],
        widget=SwitchWidget(),
        description=_('Allow users to download their ticket from the '
                      'conference homepage.'))
    ticket_on_summary_page = BooleanField(
        _('Download from summary page'),
        [HiddenUnless('tickets_enabled', preserve_data=True)],
        widget=SwitchWidget(),
        description=_(
            'Allow users to download their ticket from the registration '
            'summary page.'))
コード例 #6
0
class AttachmentFolderForm(IndicoForm):
    title = HiddenField(_('Name'), [DataRequired()],
                        widget=TypeaheadWidget(),
                        description=_('The name of the folder.'))
    description = TextAreaField(
        _('Description'),
        description=_('Description of the folder and its content'))
    protected = BooleanField(_('Protected'), widget=SwitchWidget())
    acl = AccessControlListField(
        _('Access control list'),
        [UsedIf(lambda form, field: form.protected.data)],
        allow_groups=True,
        allow_external_users=True,
        allow_event_roles=True,
        allow_category_roles=True,
        allow_registration_forms=True,
        event=lambda form: form.event,
        description=_(
            'The list of users and groups allowed to access the folder'))
    is_always_visible = BooleanField(
        _('Always Visible'), [HiddenUnless('is_hidden', value=False)],
        widget=SwitchWidget(),
        description=_(
            'By default, folders are always visible, even if a user cannot '
            'access them. You can disable this behavior here, hiding the folder '
            'for anyone who does not have permission to access it.'))
    is_hidden = BooleanField(
        _('Always hidden'), [HiddenUnless('is_always_visible', value=False)],
        widget=SwitchWidget(),
        description=
        _('Always hide the folder and its contents from public display areas of '
          'the event. You can use this for folders to store non-image files used '
          'e.g. in download links. The access permissions still apply.'))

    def __init__(self, *args, **kwargs):
        self.linked_object = kwargs.pop('linked_object')
        self.event = getattr(self.linked_object, 'event',
                             None)  # not present in categories
        super().__init__(*args, **kwargs)
        self.title.choices = self._get_title_suggestions()

    def _get_title_suggestions(self):
        query = db.session.query(AttachmentFolder.title).filter_by(
            is_deleted=False, is_default=False, object=self.linked_object)
        existing = {x[0] for x in query}
        suggestions = set(get_default_folder_names()) - existing
        if self.title.data:
            suggestions.add(self.title.data)
        return sorted(suggestions)

    def validate_is_always_visible(self, field):
        if self.is_always_visible.data and self.is_hidden.data:
            raise ValidationError(
                'These two options cannot be used at the same time')

    validate_is_hidden = validate_is_always_visible

    @generated_data
    def protection_mode(self):
        return ProtectionMode.protected if self.protected.data else ProtectionMode.inheriting
コード例 #7
0
class InvitedAbstractMixin(object):
    users_with_no_account = IndicoRadioField(_('Type of user'), [DataRequired()], default='existing',
                                             choices=(('existing', _('Existing user')),
                                                      ('new', _('New user'))))
    submitter = PrincipalField(_('Submitter'),
                               [HiddenUnless('users_with_no_account', 'existing'), DataRequired()], allow_external=True,
                               description=_('The person invited to submit the abstract'))
    first_name = StringField(_('First name'), [HiddenUnless('users_with_no_account', 'new'), DataRequired()])
    last_name = StringField(_('Family name'), [HiddenUnless('users_with_no_account', 'new'), DataRequired()])
    email = EmailField(_('Email address'), [HiddenUnless('users_with_no_account', 'new'), DataRequired()],
                       filters=[lambda x: x.lower() if x else x])

    def __init__(self, *args, **kwargs):
        self.event = kwargs['event']
        super(InvitedAbstractMixin, self).__init__(*args, **kwargs)

    def validate_email(self, field):
        if get_user_by_email(field.data):
            raise ValidationError(_('There is already a user with this email address'))

    def validate(self):
        from indico.modules.events.abstracts.util import can_create_invited_abstracts
        if not can_create_invited_abstracts(self.event):
            raise ValidationError(_('You have to create an "Invited" abstract notification template in order to '
                                    'be able to create invited abstracts.'))
        else:
            return super(InvitedAbstractMixin, self).validate()
コード例 #8
0
class SettingsForm(IndicoForm):
    bucket_info_enabled = BooleanField(_("Bucket info API"),
                                       widget=SwitchWidget())
    username = StringField(
        _("Username"), [
            HiddenUnless('bucket_info_enabled', preserve_data=True),
            DataRequired()
        ],
        description=_("The username to access the S3 bucket info endpoint"))
    password = IndicoPasswordField(
        _('Password'), [
            HiddenUnless('bucket_info_enabled', preserve_data=True),
            DataRequired()
        ],
        toggle=True,
        description=_("The password to access the S3 bucket info endpoint"))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        url = Markup('<strong><code>{}</code></strong>').format(
            url_for_plugin('storage_s3.buckets'))
        self.bucket_info_enabled.description = _(
            "Enables an API on {url} that returns information on all S3 buckets "
            "currently in use, including dynamically-named ones.").format(
                url=url)
コード例 #9
0
ファイル: forms.py プロジェクト: uniteddiversity/indico
class SectionForm(IndicoForm):
    display_as_section = BooleanField(_("Display as section"), widget=SwitchWidget(), default=True,
                                      description=_("Whether this is going to be displayed as a section or standalone"))
    title = StringField(_('Title'), [HiddenUnless('display_as_section', preserve_data=True), DataRequired()],
                        description=_("The title of the section."))
    description = TextAreaField(_('Description'), [HiddenUnless('display_as_section', preserve_data=True)],
                                description=_("The description text of the section."))
コード例 #10
0
class PluginSettingsForm(PaymentPluginSettingsFormBase):
    """Configuration form for the Plugin across all events."""

    url = URLField(
        label=gettext('SixPay Saferpay URL'),
        validators=[DataRequired()],
        description=gettext('URL to contact the Six Payment Service'),
    )
    credentials_in_db = BooleanField(
        label=gettext("API credentials in Database"),
        widget=SwitchWidget(),
        description=gettext(
            'Note that the API password will be saved as plain text in the database.'
            'If not set, the credentials must be put into the .netrc file of the user running the Indico server.'
        ))
    username = StringField(label=gettext('Username'),
                           validators=[
                               HiddenUnless('credentials_in_db',
                                            preserve_data=False),
                               DataRequired()
                           ],
                           description=gettext('SaferPay JSON API User name.'))
    password = IndicoPasswordField(
        label=gettext('Password'),
        validators=[
            HiddenUnless('credentials_in_db', preserve_data=False),
            DataRequired()
        ],
        description=gettext('SaferPay JSON API User password.'),
        toggle=True,
    )
    account_id = StringField(
        label='Account ID',
        # can be set EITHER or BOTH globally and per event
        validators=[
            Optional(),
            Regexp(r'[0-9-]{0,15}',
                   message='Field must contain up to 15 digits or "-".')
        ],
        description=gettext('Default ID of your Saferpay account,'
                            ' such as "401860-17795278".'))
    order_description = StringField(
        label=gettext('Order Description'),
        validators=[DataRequired(), FormatField(max_length=80)],
        description=gettext(
            'The description of each order in a human readable way. '
            'This description is presented to the registrant during the '
            'transaction with SixPay.'))
    order_identifier = StringField(
        label=gettext('Order Identifier'),
        validators=[DataRequired(), FormatField(max_length=80)],
        description=gettext(
            'The identifier of each order for further processing.'))
    notification_mail = StringField(
        label=gettext('Notification Email'),
        validators=[Optional(), Email(), Length(0, 50)],
        description=gettext(
            'Mail address to receive notifications of transactions.'
            'This is independent of Indico\'s own payment notifications.'))
コード例 #11
0
class AbstractReviewForm(IndicoForm):
    """Form for reviewing an abstract"""

    _order = ('proposed_action', 'proposed_contribution_type', 'proposed_related_abstract', 'proposed_tracks',
              'comment')

    comment = TextAreaField(_("Comment"), render_kw={'placeholder': _("You may leave a comment (only visible to "
                                                                      "conveners and judges)..."),
                                                     'class': 'grow'})
    proposed_action = IndicoEnumSelectField(_("Proposed Action"), [DataRequired()], enum=AbstractAction)
    proposed_related_abstract = AbstractField(
        _("Target Abstract"),
        [HiddenUnless('proposed_action', {AbstractAction.mark_as_duplicate, AbstractAction.merge}), DataRequired()],
        description=_("The current abstract should be marked as duplicate of the selected one"),
        ajax_endpoint='abstracts.other_abstracts')
    proposed_contribution_type = QuerySelectField(
        _("Contribution type"),
        [HiddenUnless('proposed_action', AbstractAction.accept)],
        get_label=lambda x: x.name.title(), allow_blank=True, blank_text=_("You may propose a contribution type..."))
    proposed_tracks = IndicoQuerySelectMultipleCheckboxField(
        _("Propose for tracks"),
        [HiddenUnless('proposed_action', AbstractAction.change_tracks), DataRequired()],
        collection_class=set, get_label='title')

    def __init__(self, edit=False, *args, **kwargs):
        abstract = kwargs.pop('abstract')
        super(AbstractReviewForm, self).__init__(*args, **kwargs)
        self.event = abstract.event
        if not edit:
            self.proposed_action.none = _("Propose an action...")
        self.proposed_related_abstract.excluded_abstract_ids = {abstract.id}
        self.proposed_contribution_type.query = (ContributionType.query
                                                 .with_parent(self.event)
                                                 .order_by(ContributionType.name))
        if not self.proposed_contribution_type.query.count():
            del self.proposed_contribution_type
        reviewed_for_track_ids = {t.id for t in abstract.reviewed_for_tracks}
        existing_prop_track_cond = (Track.id.in_(t.id for t in self.proposed_tracks.object_data)
                                    if self.proposed_tracks.object_data else False)
        self.proposed_tracks.query = (Track.query
                                      .with_parent(self.event)
                                      .filter(db.or_(Track.id.notin_(reviewed_for_track_ids),
                                                     existing_prop_track_cond))
                                      .order_by(Track.position))
        if not self.proposed_tracks.query.count():
            del self.proposed_tracks
            self.proposed_action.skip.add(AbstractAction.change_tracks)

    @property
    def split_data(self):
        data = self.data
        return {'questions_data': {k: v for k, v in data.iteritems() if k.startswith('question_')},
                'review_data': {k: v for k, v in data.iteritems() if not k.startswith('question_')}}

    @property
    def has_questions(self):
        return any(x.startswith('question_') for x in self.data)
コード例 #12
0
ファイル: forms.py プロジェクト: wtakase/indico
class TimetablePDFExportForm(IndicoForm):
    _pdf_options_fields = {'pagesize', 'fontsize', 'firstPageNumber'}

    advanced = BooleanField(_("Advanced timetable"),
                            widget=SwitchWidget(),
                            description=_("Advanced customization options"))
    document_settings = IndicoSelectMultipleCheckboxField(
        _('Document settings'), [HiddenUnless('advanced')],
        choices=_DOCUMENT_SETTINGS_CHOICES)
    contribution_info = IndicoSelectMultipleCheckboxField(
        _('Contributions related info'), [HiddenUnless('advanced')],
        choices=_CONTRIBUTION_CHOICES)
    session_info = IndicoSelectMultipleCheckboxField(
        _('Sessions related info'), [HiddenUnless('advanced')],
        choices=_SESSION_CHOICES)
    visible_entries = IndicoSelectMultipleCheckboxField(
        _('Breaks and contributions'), [HiddenUnless('advanced')],
        choices=_VISIBLE_ENTRIES_CHOICES)
    other = IndicoSelectMultipleCheckboxField(_('Miscellaneous'),
                                              choices=_OTHER_CHOICES)
    pagesize = SelectField(_('Page size'),
                           choices=[('A0', 'A0'), ('A1', 'A1'), ('A2', 'A2'),
                                    ('A3', 'A3'), ('A4', 'A4'), ('A5', 'A5'),
                                    ('Letter', 'Letter')],
                           default='A4')
    fontsize = SelectField(_('Font size'),
                           choices=[('xxx-small', _('xxx-small')),
                                    ('xx-small', _('xx-small')),
                                    ('x-small', _('x-small')),
                                    ('smaller', _('smaller')),
                                    ('small', _('small')),
                                    ('normal', _('normal')),
                                    ('large', _('large')),
                                    ('larger', _('larger'))],
                           default='normal')
    firstPageNumber = IntegerField(_('Number for the first page'),
                                   [NumberRange(min=1)],
                                   default=1,
                                   widget=NumberInput(step=1))
    submitted = HiddenField()

    def is_submitted(self):
        return 'submitted' in request.args

    @property
    def data_for_format(self):
        if not self.advanced.data:
            fields = ('visible_entries', )
        else:
            fields = set(
                get_form_field_names(TimetablePDFExportForm)
            ) - self._pdf_options_fields - {'csrf_token', 'advanced'}
        return defaultdict(
            bool, {
                option: True
                for field in fields for option in getattr(self, field).data
            })
コード例 #13
0
class AbstractSubmissionSettingsForm(IndicoForm):
    """Settings form for abstract submission"""

    announcement = IndicoMarkdownField(_('Announcement'), editor=True)
    allow_multiple_tracks = BooleanField(
        _('Multiple tracks'),
        widget=SwitchWidget(),
        description=_("Allow the selection of multiple tracks"))
    tracks_required = BooleanField(
        _('Require tracks'),
        widget=SwitchWidget(),
        description=_("Make the track selection mandatory"))
    contrib_type_required = BooleanField(
        _('Require contrib. type'),
        widget=SwitchWidget(),
        description=_("Make the selection of a contribution type mandatory"))
    allow_attachments = BooleanField(
        _('Allow attachments'),
        widget=SwitchWidget(),
        description=_("Allow files to be attached to the abstract"))
    copy_attachments = BooleanField(
        _('Copy attachments'), [HiddenUnless('allow_attachments')],
        widget=SwitchWidget(),
        description=_(
            "Copy attachments to the contribution when accepting an abstract"))
    allow_speakers = BooleanField(
        _('Allow speakers'),
        widget=SwitchWidget(),
        description=_("Allow the selection of the abstract speakers"))
    speakers_required = BooleanField(
        _('Require a speaker'), [HiddenUnless('allow_speakers')],
        widget=SwitchWidget(),
        description=_(
            "Make the selection of at least one author as speaker mandatory"))
    authorized_submitters = PrincipalListField(
        _("Authorized submitters"),
        description=_("These users may always submit abstracts, even outside "
                      "the regular submission period."))
    submission_instructions = IndicoMarkdownField(
        _('Instructions'),
        editor=True,
        description=_("These instructions will be displayed right before the "
                      "submission form."))

    @generated_data
    def announcement_render_mode(self):
        return RenderMode.markdown

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        super(AbstractSubmissionSettingsForm, self).__init__(*args, **kwargs)

    def validate_contrib_type_required(self, field):
        if field.data and not self.event.contribution_types.count():
            raise ValidationError(
                _('The event has no contribution types defined.'))
コード例 #14
0
class CERNAccessForm(RequestFormBase):
    regforms = IndicoSelectMultipleCheckboxField(
        _('Registration forms'),
        [DataRequired(_('At least one registration form has to be selected'))],
        widget=JinjaWidget('regform_list_widget.html', 'cern_access'))
    during_registration = BooleanField(
        _('Show during user registration'),
        widget=SwitchWidget(),
        description=_(
            "When enabled, users can request site access while registering "
            "and provide their additional personal data in the registration "
            "form. In any case, site access is only granted after a manager "
            "explicitly enables it for the registrants."))
    during_registration_preselected = BooleanField(
        _('Preselect during user registration'),
        [HiddenUnless('during_registration')],
        widget=SwitchWidget(),
        description=_("Preselect the option to request site access during "
                      "registration. Recommended if most registrants will "
                      "need it."))
    during_registration_required = BooleanField(
        _('Require during user registration'),
        [HiddenUnless('during_registration_preselected')],
        widget=SwitchWidget(),
        description=_("Require all users to provide data for site access. "
                      "Registration without entering the data will not be "
                      "possible."))
    start_dt_override = IndicoDateTimeField(
        _('Start date override'), [Optional()],
        description=_("If set, CERN access will be granted starting at the "
                      "specified date instead of the event's start date"))
    end_dt_override = IndicoDateTimeField(
        _('End date override'),
        [Optional(),
         LinkedDateTime('start_dt_override', not_equal=True)],
        description=_(
            "If set, CERN access will be granted until the specified date "
            "instead of the event's end date"))

    def __init__(self, *args, **kwargs):
        super(CERNAccessForm, self).__init__(*args, **kwargs)
        regforms = get_regforms(self.event)
        self._regform_map = {unicode(rf.id): rf for rf in regforms}
        self.regforms.choices = [(unicode(rf.id), rf.title) for rf in regforms]
        self.start_dt_override.default_time = self.event.start_dt_local.time()
        self.end_dt_override.default_time = self.event.end_dt_local.time()

    def validate_start_dt_override(self, field):
        if bool(self.start_dt_override.data) != bool(
                self.end_dt_override.data):
            raise ValidationError(
                _('You need to specify both date overrides or neither of them.'
                  ))

    validate_end_dt_override = validate_start_dt_override
コード例 #15
0
class EventSettingsForm(PaymentEventSettingsFormBase):

    use_event_api_keys = BooleanField(
        _('Use event API keys'),
        [Optional()],
        default=False,
        description=_(
            'Override the organization Stripe API keys.'
        ),
        widget=SwitchWidget(),
    )
    pub_key = StringField(
        _('Publishable key'),
        [
            HiddenUnless('use_event_api_keys'),
            UsedIf(lambda form, _: form.use_event_api_keys.data),
            DataRequired(),
        ],
        description=_('Publishable API key for the stripe.com account')
    )
    sec_key = StringField(
        _('Secret key'),
        [
            HiddenUnless('use_event_api_keys'),
            UsedIf(lambda form, _: form.use_event_api_keys.data),
            DataRequired(),
        ],
        description=_('Secret API key for the stripe.com account')
       )
    org_name = StringField(
        _('Organizer name'),
        [Optional()],
        default='Organization',
        description=_('Name of the event organizer')
    )
    description = StringField(
        _('Description'),
        [Optional()],
        default='Payment for conference',
        description=_('A description of the product or service being purchased')
    )
    require_postal_code = BooleanField(
        _('Require postal code input'),
        [Optional()],
        default=False,
        description=_(
            'Require registrants to input their postal code when filling the'
            ' payment form. Enabling this will decrease the chance of the'
            ' payment being marked as fraudulent.'
        ),
        widget=SwitchWidget(),
    )
コード例 #16
0
class CloneRepeatUntilFormBase(CloneRepeatOnceForm):
    stop_criterion = IndicoRadioField(_('Clone'), [DataRequired()], default='num_times',
                                      choices=(('day', _('Until a given day (inclusive)')),
                                               ('num_times', _('A number of times'))))
    until_dt = IndicoDateField(_('Day'), [HiddenUnless('stop_criterion', 'day'), DataRequired()])
    num_times = IntegerField(_('Number of times'),
                             [HiddenUnless('stop_criterion', 'num_times'), DataRequired(),
                              NumberRange(1, 100, message=_("You can clone a maximum of 100 times"))],
                             default=2)

    def __init__(self, event, **kwargs):
        kwargs.setdefault('until_dt', (self._calc_start_dt(event) + timedelta(days=14)).date())
        super().__init__(event, **kwargs)
コード例 #17
0
ファイル: forms.py プロジェクト: javfg/indico
class UnlistedEventsForm(IndicoForm):
    enabled = BooleanField(_('Enabled'), widget=SwitchWidget(), default=False)
    restricted = BooleanField(
        _('Restrict creation'), [HiddenUnless('enabled', preserve_data=True)],
        widget=SwitchWidget(),
        description=
        _('Restrict creation of unlisted events to the authorized users below.'
          ))
    authorized_creators = PrincipalListField(
        _('Authorized users'), [HiddenUnless('enabled', preserve_data=True)],
        allow_external_users=True,
        allow_groups=True,
        description=_('These users may create unlisted events.'))
コード例 #18
0
class AbstractReviewingSettingsForm(IndicoForm):
    """Settings form for abstract reviewing."""

    scale_lower = IntegerField(_('Scale (from)'), [InputRequired()])
    scale_upper = IntegerField(_('Scale (to)'), [InputRequired()])
    allow_convener_judgment = BooleanField(_('Allow track conveners to judge'), widget=SwitchWidget(),
                                           description=_('Enabling this allows track conveners to make a judgment '
                                                         'such as accepting or rejecting an abstract.'))
    allow_convener_track_change = BooleanField(_('Allow conveners to change tracks'),
                                               [HiddenUnless('allow_convener_judgment',
                                                             value=False, preserve_data=True)],
                                               widget=SwitchWidget(),
                                               description=_('Enabling this allows track conveners to update the track '
                                                             'an abstract is part of.'))
    allow_comments = BooleanField(_('Allow comments'), widget=SwitchWidget(),
                                  description=_('Enabling this allows judges, conveners and reviewers to leave '
                                                'comments on abstracts.'))
    allow_contributors_in_comments = BooleanField(_('Allow contributors in comments'),
                                                  [HiddenUnless('allow_comments', preserve_data=True)],
                                                  widget=SwitchWidget(),
                                                  description=_('Enabling this allows submitters, authors, and '
                                                                'speakers to also participate in the comments.'))
    notify_on_new_comments = BooleanField(_('Comment notifications'),
                                          [HiddenUnless('allow_comments', preserve_data=True)],
                                          widget=SwitchWidget(),
                                          description=_('Send email notifications when new comments are posted.'))
    reviewing_instructions = IndicoMarkdownField(_('Reviewing Instructions'), editor=True,
                                                 description=_('These instructions will be displayed right before the '
                                                               'reviewing form.'))
    judgment_instructions = IndicoMarkdownField(_('Judgment Instructions'), editor=True,
                                                description=_('These instructions will be displayed right before the '
                                                              'decision box.'))

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        self.has_ratings = kwargs.pop('has_ratings', False)
        super().__init__(*args, **kwargs)
        if self.has_ratings:
            self.scale_upper.warning = _('Changing the ratings scale will proportionally affect existing ratings.')

    def validate_scale_upper(self, field):
        lower = self.scale_lower.data
        upper = self.scale_upper.data
        if lower is None or upper is None:
            return
        if lower >= upper:
            raise ValidationError(_("The scale's 'to' value must be greater than the 'from' value."))
        if upper - lower > 20:
            raise ValidationError(_("The difference between 'to' and' from' may not be greater than 20."))
コード例 #19
0
class DeadlineForm(IndicoForm):
    deadline = IndicoDateTimeField(_("Deadline"), [Optional()], default_time=time(23, 59))
    enforce = BooleanField(_("Enforce deadline"), [HiddenUnless('deadline')], widget=SwitchWidget())

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        super(DeadlineForm, self).__init__(*args, **kwargs)
コード例 #20
0
 def _add_contrib_type_hidden_unless(cls):
     # In the bulk form we need to hide/disable the contrib type selector unless we want to
     # override the type specified in the abstract.  However, multiple HiddenUnless validators
     # are not supported in the client-side JS so we only add it to this form - it removes
     # inactive fields on the server side so it still works (the JavaScript picks up the last
     # HiddenUnless validator)
     inject_validators(BulkAbstractJudgmentForm, 'accepted_contrib_type', [HiddenUnless('override_contrib_type')])
コード例 #21
0
class OutlookUserPreferences(ExtraUserPreferences):
    fields = {
        'outlook_active':
        BooleanField(
            _('Sync with Outlook'),
            widget=SwitchWidget(),
            description=_(
                'Add Indico events in which I participate to my Outlook '
                'calendar')),
        'outlook_status':
        SelectField(_('Outlook entry status'),
                    [HiddenUnless('extra_outlook_active', preserve_data=True)],
                    choices=_status_choices,
                    description=_('The status for Outlook Calendar entries'))
    }

    def load(self):
        default_status = OutlookPlugin.settings.get('status')
        return {
            'outlook_active':
            OutlookPlugin.user_settings.get(self.user, 'enabled'),
            'outlook_status':
            OutlookPlugin.user_settings.get(self.user, 'status',
                                            default_status)
        }

    def save(self, data):
        OutlookPlugin.user_settings.set_multi(self.user, {
            'enabled': data['outlook_active'],
            'status': data['outlook_status']
        })
コード例 #22
0
class AccessIdentityDataForm(IndicoForm):
    birth_date = IndicoDateField(_('Birth date'), [DataRequired()])
    nationality = SelectField(_('Country of birth'), [DataRequired()])
    birth_place = StringField(_('Place of birth'), [DataRequired()])
    by_car = BooleanField(_('Are you bringing your own car?'), [Optional()], widget=SwitchWidget())
    license_plate = StringField(
        _('License plate'),
        [
            HiddenUnless('by_car'),
            Length(min=3),
            IndicoRegexp(r'^[0-9A-Za-z]+([- ][ ]*[0-9A-Za-z]+)*$',
                         message=_('Wrong format. Only letters and numbers separated by dashes (-) or spaces allowed'))
        ]
    )

    def __init__(self, *args, **kwargs):
        super(AccessIdentityDataForm, self).__init__(*args, **kwargs)
        self.nationality.choices = [('', '')] + sorted(get_countries().iteritems(), key=itemgetter(1))

    def validate_birth_date(self, field):
        if field.data > datetime.now().date():
            raise ValidationError(_('The specified date is in the future'))

    def validate_license_plate(self, field):
        if self.by_car.data and not sanitize_license_plate(field.data):
            raise ValidationError(_('Please insert a valid license plate number!'))
コード例 #23
0
ファイル: reservations.py プロジェクト: vireshbackup/indico
class NewBookingConfirmForm(NewBookingPeriodForm):
    room_usage = RadioField(
        [DataRequired()],
        choices=[('current_user', _("I'll be using the room myself")),
                 ('other_user', _("I'm booking the room for someone else"))])
    booked_for_user = PrincipalField(
        _('User'), [HiddenUnless('room_usage', 'other_user'),
                    DataRequired()],
        allow_external=True)
    booking_reason = TextAreaField(_('Reason'), [DataRequired()])
    uses_vc = BooleanField(_('I will use videoconference equipment'))
    used_equipment = IndicoQuerySelectMultipleCheckboxField(
        _('VC equipment'), get_label=lambda x: x.name)
    needs_vc_assistance = BooleanField(
        _('Request assistance for the startup of the videoconference session. '
          'This support is usually performed remotely.'))
    needs_assistance = BooleanField(
        _('Request personal assistance for meeting startup'))
    submit_book = SubmitField(_('Create booking'))
    submit_prebook = SubmitField(_('Create pre-booking'))

    def validate_used_equipment(self, field):
        if field.data and not self.uses_vc.data:
            raise ValidationError(_('Videoconference equipment is not used.'))
        elif not field.data and self.uses_vc.data:
            raise ValidationError(
                _('Please select the type of videoconference that you will use.'
                  ))

    def validate_needs_vc_assistance(self, field):
        if field.data and not self.uses_vc.data:
            raise ValidationError(_('Videoconference equipment is not used.'))
コード例 #24
0
ファイル: forms.py プロジェクト: uniteddiversity/indico
class SurveyForm(IndicoForm):
    _notification_fields = ('notifications_enabled', 'notify_participants', 'start_notification_emails',
                            'new_submission_emails')

    title = StringField(_("Title"), [DataRequired()], description=_("The title of the survey"))
    introduction = TextAreaField(_("Introduction"), description=_("An introduction to be displayed before the survey"))
    anonymous = BooleanField(_("Anonymous submissions"), widget=SwitchWidget(),
                             description=_("User information will not be attached to submissions"))
    require_user = BooleanField(_("Only logged-in users"), [HiddenUnless('anonymous')], widget=SwitchWidget(),
                                description=_("Require users to be logged in for submitting the survey"))
    limit_submissions = BooleanField(_("Limit submissions"), widget=SwitchWidget(),
                                     description=_("Whether there is a submission cap"))
    submission_limit = IntegerField(_("Capacity"),
                                    [HiddenUnless('limit_submissions'), DataRequired(), NumberRange(min=1)],
                                    description=_("Maximum number of submissions accepted"))
    private = BooleanField(_("Private survey"), widget=SwitchWidget(),
                           description=_("Only selected people can answer the survey."))
    partial_completion = BooleanField(_('Partial completion'), widget=SwitchWidget(),
                                      description=_('Allow to save answers without submitting the survey.'))
    notifications_enabled = BooleanField(_('Enabled'), widget=SwitchWidget(),
                                         description=_('Send email notifications for specific events related to the '
                                                       'survey.'))
    notify_participants = BooleanField(_('Participants'), [HiddenUnless('notifications_enabled', preserve_data=True)],
                                       widget=SwitchWidget(),
                                       description=_('Notify participants of the event when this survey starts.'))
    start_notification_emails = EmailListField(_('Start notification recipients'),
                                               [HiddenUnless('notifications_enabled', preserve_data=True)],
                                               description=_('Email addresses to notify about the start of the survey'))
    new_submission_emails = EmailListField(_('New submission notification recipients'),
                                           [HiddenUnless('notifications_enabled', preserve_data=True)],
                                           description=_('Email addresses to notify when a new submission is made'))

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        super().__init__(*args, **kwargs)

    def validate_title(self, field):
        query = (Survey.query.with_parent(self.event)
                 .filter(db.func.lower(Survey.title) == field.data.lower(),
                         Survey.title != field.object_data,
                         ~Survey.is_deleted))
        if query.count():
            raise ValidationError(_('There is already a survey named "{}" on this event').format(escape(field.data)))

    def post_validate(self):
        if not self.anonymous.data:
            self.require_user.data = True
コード例 #25
0
class AbstractSubmissionSettingsForm(IndicoForm):
    """Settings form for abstract submission."""

    announcement = IndicoMarkdownField(_('Announcement'), editor=True)
    allow_multiple_tracks = BooleanField(_('Multiple tracks'), widget=SwitchWidget(),
                                         description=_('Allow the selection of multiple tracks'))
    tracks_required = BooleanField(_('Require tracks'), widget=SwitchWidget(),
                                   description=_('Make the track selection mandatory'))
    contrib_type_required = BooleanField(_('Require contrib. type'), widget=SwitchWidget(),
                                         description=_('Make the selection of a contribution type mandatory'))
    allow_attachments = BooleanField(_('Allow attachments'), widget=SwitchWidget(),
                                     description=_('Allow files to be attached to the abstract'))
    copy_attachments = BooleanField(_('Copy attachments'), [HiddenUnless('allow_attachments')], widget=SwitchWidget(),
                                    description=_('Copy attachments to the contribution when accepting an abstract'))
    allow_speakers = BooleanField(_('Allow speakers'), widget=SwitchWidget(),
                                  description=_('Allow the selection of the abstract speakers'))
    speakers_required = BooleanField(_('Require a speaker'), [HiddenUnless('allow_speakers')], widget=SwitchWidget(),
                                     description=_('Make the selection of at least one author as speaker mandatory'))
    allow_editing = IndicoEnumSelectField(_('Allow editing'), enum=AllowEditingType, sorted=True,
                                          description=_('Specify who will be able to edit the abstract'))
    contribution_submitters = IndicoEnumSelectField(_('Contribution submitters'),
                                                    enum=SubmissionRightsType, sorted=True,
                                                    description=_('Specify who will get contribution submission rights '
                                                                  'once an abstract has been accepted'))
    authorized_submitters = PrincipalListField(_('Authorized submitters'), event=lambda form: form.event,
                                               allow_external_users=True, allow_groups=True,
                                               allow_event_roles=True, allow_category_roles=True,
                                               description=_('These users may always submit abstracts, '
                                                             'even outside the regular submission period.'))
    submission_instructions = IndicoMarkdownField(_('Instructions'), editor=True,
                                                  description=_('These instructions will be displayed right before the '
                                                                'submission form'))

    @generated_data
    def announcement_render_mode(self):
        return RenderMode.markdown

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        super().__init__(*args, **kwargs)
        if self.event and self.event.is_unlisted:
            self.authorized_submitters.allow_category_roles = False

    def validate_contrib_type_required(self, field):
        if field.data and not self.event.contribution_types.count():
            raise ValidationError(_('The event has no contribution types defined.'))
コード例 #26
0
ファイル: reservations.py プロジェクト: qroques/indico
class NewBookingSimpleForm(NewBookingConfirmForm):
    submit_check = SubmitField(_('Check conflicts'))
    booking_reason = TextAreaField(_('Reason'), [UsedIf(lambda form, field: not form.submit_check.data),
                                                 DataRequired()])
    room_usage = RadioField(validators=[UsedIf(lambda form, field: not form.submit_check.data), DataRequired()],
                            choices=[('current_user', _("I'll be using the room myself")),
                                     ('other_user', _("I'm booking the room for someone else"))])
    booked_for_user = PrincipalField(_('User'), [UsedIf(lambda form, field: not form.submit_check.data),
                                                 HiddenUnless('room_usage', 'other_user'),
                                                 DataRequired()], allow_external=True)
コード例 #27
0
ファイル: forms.py プロジェクト: manikm/indico2
 def __init__(self, *args, **kwargs):
     if config.LOCAL_IDENTITIES:
         for field in ('username', 'password', 'confirm_password'):
             inject_validators(self, field, [HiddenUnless('create_identity')], early=True)
     super(AdminAccountRegistrationForm, self).__init__(*args, **kwargs)
     del self.comment
     if not config.LOCAL_IDENTITIES:
         del self.username
         del self.password
         del self.confirm_password
         del self.create_identity
コード例 #28
0
ファイル: forms.py プロジェクト: javfg/indico
class UserPreferencesForm(IndicoForm):
    lang = SelectField(_('Language'))
    timezone = SelectField(_('Timezone'))

    force_timezone = BooleanField(
        _('Use my timezone'),
        widget=SwitchWidget(),
        description=_(
            "Always use my current timezone instead of an event's timezone."))

    show_future_events = BooleanField(
        _('Show future events'),
        widget=SwitchWidget(),
        description=_('Show future events by default.'))

    show_past_events = BooleanField(
        _('Show past events'),
        widget=SwitchWidget(),
        description=_('Show past events by default.'))

    name_format = IndicoEnumSelectField(
        _('Name format'),
        enum=NameFormat,
        description=_('Default format in which names are displayed'))

    use_previewer_pdf = BooleanField(
        _('Use previewer for PDF files'),
        widget=SwitchWidget(),
        description=
        _('The previewer is used by default for image and text files, but not for PDF files.'
          ))

    add_ical_alerts = BooleanField(
        _('Add alerts to iCal'),
        widget=SwitchWidget(),
        description=_('Add an event reminder to exported iCal files/URLs.'))

    add_ical_alerts_mins = IntegerField(
        _('iCal notification time'),
        [HiddenUnless('add_ical_alerts'),
         NumberRange(min=0)],
        description=_('Number of minutes to notify before an event.'))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        locales = [(code, f'{name} ({territory})' if territory else name)
                   for code, (name, territory,
                              __) in get_all_locales().items()]
        self.lang.choices = sorted(locales, key=itemgetter(1))
        self.timezone.choices = list(zip(common_timezones, common_timezones))
        if self.timezone.object_data and self.timezone.object_data not in common_timezones_set:
            self.timezone.choices.append(
                (self.timezone.object_data, self.timezone.object_data))
コード例 #29
0
class BulkAbstractJudgmentForm(AbstractJudgmentFormBase):
    _order = ('judgment', 'accepted_track', 'override_contrib_type', 'accepted_contrib_type', 'session', 'duplicate_of',
              'merged_into', 'merge_persons', 'judgment_comment', 'send_notifications')

    judgment = HiddenEnumField(enum=AbstractAction, skip={AbstractAction.change_tracks})
    abstract_id = HiddenFieldList()
    submitted = HiddenField()
    override_contrib_type = BooleanField(_("Override contribution type"),
                                         [HiddenUnless('judgment', AbstractAction.accept)], widget=SwitchWidget(),
                                         description=_("Override the contribution type for all selected abstracts"))

    def __init__(self, *args, **kwargs):
        self.event = kwargs.pop('event')
        super(BulkAbstractJudgmentForm, self).__init__(*args, **kwargs)
        if self.accepted_track:
            self.accepted_track.description = _("The abstracts will be accepted in this track")
        if self.accepted_contrib_type:
            self.accepted_contrib_type.description = _("The abstracts will be converted into a contribution of this "
                                                       "type")
        else:
            del self.override_contrib_type
        if self.session:
            self.session.description = _("The generated contributions will be allocated in this session")
        self.duplicate_of.description = _("The selected abstracts will be marked as duplicate of the specified "
                                          "abstract")
        self.merged_into.description = _("The selected abstracts will be merged into the specified abstract")
        self.merge_persons.description = _("Authors and speakers of the selected abstracts will be added to the "
                                           "specified abstract")
        self.duplicate_of.excluded_abstract_ids = set(kwargs['abstract_id'])
        self.merged_into.excluded_abstract_ids = set(kwargs['abstract_id'])
        if kwargs['judgment']:
            self._remove_unused_fields(kwargs['judgment'])

    def _remove_unused_fields(self, judgment):
        for field in list(self):
            validator = next((v for v in field.validators if isinstance(v, HiddenUnless) and v.field == 'judgment'),
                             None)
            if validator is None:
                continue
            if not any(v.name == judgment for v in validator.value):
                delattr(self, field.name)

    def is_submitted(self):
        return super(BulkAbstractJudgmentForm, self).is_submitted() and 'submitted' in request.form

    @classmethod
    def _add_contrib_type_hidden_unless(cls):
        # In the bulk form we need to hide/disable the contrib type selector unless we want to
        # override the type specified in the abstract.  However, multiple HiddenUnless validators
        # are not supported in the client-side JS so we only add it to this form - it removes
        # inactive fields on the server side so it still works (the JavaScript picks up the last
        # HiddenUnless validator)
        inject_validators(BulkAbstractJudgmentForm, 'accepted_contrib_type', [HiddenUnless('override_contrib_type')])
コード例 #30
0
ファイル: choices.py プロジェクト: vireshbackup/indico
class SingleChoiceConfigForm(object):
    display_type = IndicoRadioField(_('Display type'), [DataRequired()],
                                    description=_('Widget that will be used to render the available options'),
                                    choices=[('radio', _('Radio buttons')),
                                             ('select', _('Drop-down list'))],
                                    default='radio')
    radio_display_type = IndicoRadioField(_('Alignment'),
                                          [DataRequired(), HiddenUnless('display_type', 'radio')],
                                          description=_('The arrangement of the options'),
                                          choices=[('vertical', _('Vertical')),
                                                   ('horizontal', _('Horizontal'))])
    options = MultiStringField(_('Options'), [DataRequired()], field=('option', _('option')), unique=True,
                               uuid_field='id', sortable=True,
                               description=_('Specify the options the user can choose from'))