Esempio n. 1
0
 def checkEmail(self):
     session = Session()
     users = session.query(User).filter(User.email==self.email)
     if users.count() > 1:
         raise interface.Invalid(_("Email already taken!"),"email")
     if users.count() == 1 and users.first().user_id != get_db_user().user_id:
         raise interface.Invalid(_("Email already taken!"),"email")
Esempio n. 2
0
    def validate(self, values):
        if values is None:
            return super(VocabularyValuesValidator, self).validate(values)

        by_value = {}
        by_token = {}
        for value in values:
            term = vocabulary.SimpleTerm(token=value.encode('unicode_escape'),
                                         value=value,
                                         title=value)
            if term.value in by_value:
                raise interface.Invalid(
                    _('field_edit_error_conflicting_values',
                      default=
                      u"The '${value1}' vocabulary value conflicts with '${value2}'.",
                      mapping={
                          'value1': value,
                          'value2': by_value[term.value].value
                      }))

            if term.token in by_token:
                raise interface.Invalid(
                    _('field_edit_error_conflicting_values',
                      default=
                      u"The '${value1}' vocabulary value conflicts with '${value2}'.",
                      mapping={
                          'value1': value,
                          'value2': by_value[term.token].value
                      }))

            by_value[term.value] = term
            by_token[term.token] = term

        return super(VocabularyValuesValidator, self).validate(values)
Esempio n. 3
0
    def validate(self, action, data):
        errors = super(ReportView, self).validate(action, data)
        time_span = self.time_span(data)
        if IGroupSitting.providedBy(self.context):
            if not self.context.items:
                errors.append(
                    interface.Invalid(
                        _(u"The sitting has no scheduled items")))
        else:
            start_date = data["date"] if "date" in data else \
                                                datetime.datetime.today().date()
            end_date = self.get_end_date(start_date, time_span)
            try:
                ctx = ISchedulingContext(self.context)
            except:
                errors.append(
                    interface.Invalid(
                        _(u"You are trying to generate a report "
                          "outside scheduling")))
            sittings = ctx.get_sittings(start_date, end_date).values()
            if not sittings:
                errors.append(
                    interface.Invalid(
                        _(u"The period selected has no sittings"), "date"))

            parliament = queries.get_parliament_by_date_range(
                start_date, end_date)
            if parliament is None:
                errors.append(
                    interface.Invalid(
                        _(u"A parliament must be active in the period"),
                        "date"))
        return errors
Esempio n. 4
0
 def verifyFluxo(tramite):
     if not tramite.protocolo_id:
         raise interface.Invalid(_(u'O parâmetro protocolo_id não foi informado.'))
     if not tramite.areas:
         raise interface.Invalid(_(u'O parâmetro areas não foi informado.'))
     sc = getUtility(ISecurityChecker)
     if not sc.check('fluxo_rigoroso', protocolo_id=tramite.protocolo_id, areas=tramite.areas):
         raise interface.Invalid(_(u'Não é possível tramitar esse protocolo para as áreas escolhidas. O fluxo de tramitação definido para o tipo de protocolo e documento não é flexível.'))
Esempio n. 5
0
 def checkEmail(self):
     session = Session()
     users = session.query(User).filter(User.email==self.email)
     message = _("error_profile_email_taken", "Email already taken!")
     if users.count() > 1:
         raise interface.Invalid(message,"email")
     if users.count() == 1 and users.first().user_id != get_db_user().user_id:
         raise interface.Invalid(message,"email")
Esempio n. 6
0
 def verifyFluxo(protocolo):
     if not protocolo.tipoprotocolo:
         raise interface.Invalid(_(u'O parâmetro tipoprotocolo não foi informado.'))
     if not protocolo.tipodocumento_id:
         raise interface.Invalid(_(u'O parâmetro tipodocumento_id não foi informado.'))
     sc = getUtility(ISecurityChecker)
     if not sc.check('fluxo_rigoroso_area_inicial', tipoprotocolo=protocolo.tipoprotocolo, tipodocumento_id=protocolo.tipodocumento_id):
         raise interface.Invalid(_(u'Esse tipo de protocolo e/ou tipo de documento não pode ser protocolado pela sua área.'))
Esempio n. 7
0
 def url_validation(content):
     if content.relative and not content.target:
         raise interface.Invalid(
             _(u"Relative link selected without target."))
     if not content.relative and not content.url:
         raise interface.Invalid(
             _(u"Absolute link selected without URL. "
               u"If the link goes to an internal item in Silva, "
               u"put a checkmark in the relative link field."))
Esempio n. 8
0
 def verifyApenso(apenso):
     if not apenso.apenso_id:
         return
     if not apenso.protocolo_id:
         raise interface.Invalid(_(u'O parâmetro protocolo_id não foi informado.'))
     if apenso.protocolo_id == apenso.apenso_id:
         raise interface.Invalid(_(u'O protocolo não pode ser apensado a ele mesmo.'))
     sc = getUtility(ISecurityChecker)
     if not sc.check('ciclo_apenso', protocolo_id=apenso.protocolo_id, apenso_id=apenso.apenso_id):
         raise interface.Invalid(_(u'Ciclo de apensos detectado!'))
     if not sc.check('momento_tramitacao', protocolo_id=apenso.protocolo_id, apenso_id=apenso.apenso_id):
         raise interface.Invalid(_(u'Para que um protocolo seja apensado em outro é necessário que ambos compartilhem o mesmo momento na tramitação, ou seja, estejam tramitando nas mesmas áreas e tenham o mesmo tipo de documento e protocolo.'))
Esempio n. 9
0
    def validate(self, action, data):
        errors = super(ReportView, self).validate(action, data)
        self.time_span = TIME_SPAN.daily
        if 'doc_type' in data:
            if data['doc_type'] == "Order of the day":
                self.time_span = TIME_SPAN.daily
            elif data['doc_type'] == "Proceedings of the day":
                self.time_span = TIME_SPAN.daily
            elif data['doc_type'] == "Weekly Business":
                self.time_span = TIME_SPAN.weekly
            elif data['doc_type'] == "Questions of the week":
                self.time_span = TIME_SPAN.weekly

        if IGroupSitting.providedBy(self.context):
            self.start_date = datetime.date(self.context.start_date.year,
                                            self.context.start_date.month,
                                            self.context.start_date.day)
        elif ISchedulingContext.providedBy(self.context):
            if 'date' in data:
                self.start_date = data['date']
        else:
            self.start_date = datetime.today().date()

        self.end_date = self.get_end_date(self.start_date, self.time_span)

        parliament = queries.get_parliament_by_date_range(
            self, self.start_date, self.end_date)
        #session = queries.get_session_by_date_range(self, start_date, end_date)

        if parliament is None:
            errors.append(
                interface.Invalid(
                    _(u"A parliament must be active in the period"), "date"))

        return errors
Esempio n. 10
0
 def must_limit_recurrence(recurring):
     if recurring.weekdays or recurring.monthly:
         if recurring.repeat or recurring.repeat_until:
             return
         raise interface.Invalid(
             _(u"Must limit recurrence (by number or date)"), "repeat",
             "repeat_until")
Esempio n. 11
0
def validate_non_overlapping_sitting(action, data, context, container,
                                     *fields):
    start = data.get('start_date')
    end = data.get('end_date', None)

    if not fields:
        fields = "start_date", "end_date"

    session = Session()
    group_id = container.__parent__.group_id
    group = session.query(domain.Group).get(group_id)
    sittings = group.sittings

    for sitting in queries.get_sittings_between(sittings, start, end):
        if context != sitting:
            return [
                interface.Invalid(
                    _(
                        u"One or more events would be scheduled for $F, which "
                        "overlaps with an existing sitting",
                        mapping={'F': datetimedict.fromdatetime(start)}),
                    *fields)
            ]

    return []
Esempio n. 12
0
def validate_venues(action, data, context, container):
    """A venue can only be booked for one sitting at once."""

    errors = []
    if interfaces.IGroupSitting.providedBy(context):
        sitting = context
    else:
        sitting = None
    venue_id = data.get('venue_id')
    if venue_id is not None:
        venue_id = long(venue_id)
        session = Session()
        svenue = session.query(domain.Venue).get(venue_id)
    else:
        return []

    start = data.get('start_date')
    end = data.get('end_date')
    if not (start and end):
        return []

    for booking in venue.check_venue_bookings(start, end, svenue, sitting):
        errors.append(
            interface.Invalid(
                _(u'Venue "$venue" already booked in this time slot',
                  mapping={'venue': booking.short_name}), "venue_id"))
    return errors
Esempio n. 13
0
    def validate(self, action, data):
        errors = super(ReportingView, self).validate(action, data)
        time_span = TIME_SPAN.daily
        if 'doc_type' in data:
            if data['doc_type'] == "Order of the day":
                time_span = TIME_SPAN.daily
            elif data['doc_type'] == "Proceedings of the day":
                time_span = TIME_SPAN.daily
            elif data['doc_type'] == "Weekly Business":
                time_span = TIME_SPAN.weekly
            elif data['doc_type'] == "Questions of the week":
                time_span = TIME_SPAN.weekly

        if 'date' in data:
            start_date = data['date']
        else:
            start_date = self.date
        end_date = self.get_end_date(start_date, time_span)

        parliament = queries.get_parliament_by_date_range(
            self, start_date, end_date)
        session = queries.get_session_by_date_range(self, start_date, end_date)

        if parliament is None:
            errors.append(
                interface.Invalid(
                    _(u"A parliament must be active in the period"), "date"))
        #elif session is None:
        #    errors.append(interface.Invalid(
        #        _(u"A session must be active in the period."),
        #        "date"))

        return errors
Esempio n. 14
0
def validate_government_dates(action, data, context, container):
    errors = []
    if interfaces.IGovernment.providedBy(context):
        government = context
    else:
        government = None

    if container.__parent__.end_date is not None:
        if data['start_date'] > container.__parent__.end_date:
            errors.append(
                interface.Invalid(
                    _("Start date cannot be after the parliaments dissolution (%s)"
                      ) % container.__parent__.end_date, "start_date"))
    if container.__parent__.start_date > data['start_date']:
        errors.append(
            interface.Invalid(
                _("Start date must start after the swearing in of the parliament (%s)"
                  ) % container.__parent__.start_date, "start_date"))
    results = queries.validate_date_in_interval(government, domain.Government,
                                                data['start_date'])
    for result in results:
        overlaps = result.short_name
        errors.append(
            interface.Invalid(
                _("The start date overlaps with (%s)") % overlaps,
                "start_date"))
    if data['end_date']:
        results = queries.validate_date_in_interval(government,
                                                    domain.Government,
                                                    data['start_date'])
        for result in results:
            overlaps = result.short_name
            errors.append(
                interface.Invalid(
                    _("The end date overlaps with (%s)") % overlaps,
                    "end_date"))

    if government is None:
        results = queries.validate_open_interval(government, domain.Government)
        for result in results:
            overlaps = result.short_name
            errors.append(
                interface.Invalid(
                    _("Another government is not yet dissolved (%s)") %
                    overlaps, "start_date"))

    return errors
Esempio n. 15
0
 def _checkForm(self, data):
     if data['company'] is None and data['new_company'] is None:
         raise interfaces.WidgetActionExecutionError(
             'new_company',
             interface.Invalid(
                 _(u"You need to specify your company name.")
             )
         )
Esempio n. 16
0
def validate_parliament_dates(action, data, context, container):
    """Parliaments must not overlap."""
    errors = []
    if interfaces.IParliament.providedBy(context):
        parliament = context
    else:
        parliament = None
    results = queries.validate_date_in_interval(parliament, domain.Parliament,
                                                data['start_date'])
    for result in results:
        overlaps = result.short_name
        errors.append(
            interface.Invalid(
                _("The start date overlaps with (%s)") % overlaps,
                "start_date"))
    if data['end_date']:
        results = queries.validate_date_in_interval(parliament,
                                                    domain.Parliament,
                                                    data['start_date'])
        for result in results:
            overlaps = result.short_name
            errors.append(
                interface.Invalid(
                    _("The end date overlaps with (%s)") % overlaps,
                    "end_date"))

    results = queries.validate_date_in_interval(parliament, domain.Parliament,
                                                data['election_date'])
    for result in results:
        overlaps = result.short_name
        errors.append(
            interface.Invalid(
                _("The election date overlaps with (%s)") % overlaps,
                "election_date"))

    if parliament is None:
        results = queries.validate_open_interval(parliament, domain.Parliament)
        for result in results:
            overlaps = result.short_name
            errors.append(
                interface.Invalid(
                    _("Another parliament is not yet dissolved (%s)") %
                    overlaps, "election_date"))

    return errors
Esempio n. 17
0
def email_validator(action, data, context, container):
    session = Session()
    users = session.query(domain.User)\
                   .filter(domain.User.email==data.get("email",""))
    if users.count() > 1:
        return [
            interface.Invalid(_(u"Email already taken!"), "email"),
        ]
    if context:
        if users.count() == 1 and users.first().user_id != context.user_id:
            return [
                interface.Invalid(_(u"Email already taken!"), "email"),
            ]
    elif users.count() > 0:
        return [
            interface.Invalid(_(u"Email already taken!"), "email"),
        ]
    return []
Esempio n. 18
0
def validate_apply_until_item_number(value):
    '''This method does validate the 'apply_until_item_number' field.
       It will check that given number is a number among existing item numbers
       using a correct format.'''
    try:
        _itemNumber_to_storedItemNumber(value)
    except ValueError:
        raise interface.Invalid(_(u'Please provide a valid number.'))
    return True
Esempio n. 19
0
 def handleApply(self, action):
     data, errors = self.extractData()
     if errors:
         return
     folder = self._getFolder(data['folder'])
     if folder is None:
         error = interface.Invalid(_(u'Unknown folder.'))
         raise ActionExecutionError(error)
     try:
         self._createUrl(folder, data)
     except Unauthorized:
         error = interface.Invalid(_(u'Permission denied.'))
         raise ActionExecutionError(error)
     except ValueError:
         error = interface.Invalid(_(u'Could not add to folder.'))
         raise ActionExecutionError(error)
     else:
         self.request.response.redirect('@@collective_readitlater_urladded')
Esempio n. 20
0
def validate_party_membership(action, data, context, container):
    errors = []
    parent_id = getattr(container.__parent__, 'parent_group_id', None)
    if interfaces.IPartyMember.providedBy(context):
        party_member = context
        user_id = context.user_id
    else:
        party_member = None
        user_id = data['user_id']
    if data.get('start_date', None):
        for r in queries.validate_membership_in_interval(party_member,
                                                         AllPartyMemberships,
                                                         data['start_date'],
                                                         user_id,
                                                         parent_id=parent_id,
                                                         with_parent=True):
            overlaps = r.short_name
            errors.append(
                interface.Invalid(
                    _("The person is a member in (%s) at that date") %
                    overlaps, "start_date"))
    if data.get('end_date', None):
        for r in queries.validate_membership_in_interval(party_member,
                                                         AllPartyMemberships,
                                                         data['end_date'],
                                                         user_id,
                                                         parent_id=parent_id,
                                                         with_parent=True):
            overlaps = r.short_name
            errors.append(
                interface.Invalid(
                    _("The person is a member in (%s) at that date") %
                    overlaps, "end_date"))
    for r in queries.validate_open_membership(party_member,
                                              AllPartyMemberships,
                                              user_id,
                                              parent_id=parent_id,
                                              with_parent=True):
        overlaps = r.short_name
        errors.append(
            interface.Invalid(
                _("The person is a member in (%s) at that date") % overlaps,
                "end_date"))
    return errors
Esempio n. 21
0
 def validate(self, action, data):
     errors = super(GenerateTakes, self).validate(action, data)
     if ((len(get_assigned_staff(self.context, "Reporter")) == 0)
             or (len(get_assigned_staff(self.context, "Reader")) == 0)
             or (len(get_assigned_staff(self.context, "Editor")) == 0)):
         errors.append(
             interface.Invalid(
                 _(u"Staff have not been assigned to work on this sitting yet"
                   ), "duration"))
     return errors
Esempio n. 22
0
def choice_constraint(value):
    """if the selection is left on default value, raise error message
    In order for this to work the 1st list item must be a generic choice
    Ex: 'Select One'
    for ease # if value == value[0]:
    """
    if value == (u'Select One'):
        raise interface.Invalid(_(u"Please select a choice"))
    else:
        return True
Esempio n. 23
0
 def _registerUser(self, data):
     regtool = getToolByName(self.context, 'portal_registration')
     try:
         regtool.addMember(data['login'], data['password'])
         self.portal_url = getToolByName(self.context, "portal_url")
         self.status = _(u"Your can now log in.")
         self.request.response.redirect('%s/login' % self.portal_url())
     except ValueError, e:
         raise interfaces.ActionExecutionError(
             interface.Invalid(unicode(e))
         )
Esempio n. 24
0
def validate_start_date_within_parent( parent, data ):
    """ Check that the start date is inside the restrictictions.
    It must not start before the contextParents start date or end
    after the contextsParents end date"""
    errors =[]
    if data.get('start_date',None):
        start = ui_date.get_date(data['start_date'])
        if getattr(parent, 'start_date', None):
            pstart = ui_date.get_date(parent.start_date)
            if start < pstart:
                errors.append( interface.Invalid( 
                _(u"Start date must be after (%s)") % pstart, 
                "start_date" ))
        if getattr(parent, 'end_date', None):
            pend = ui_date.get_date(parent.end_date)
            if start > pend:
                errors.append( interface.Invalid( 
                _(u"Start date must be prior to (%s)") % pend, 
                "start_date" ))
    return errors
Esempio n. 25
0
    def validate(self, values):
        if values is None:
            return super(VocabularyNameValidator, self).validate(values)

        if values and self.request.form.get('form.widgets.values', None):
            raise interface.Invalid(
                _('field_edit_error_values_and_name',
                  default=
                  u"You can't set a vocabulary name AND vocabulary values. "
                  u"Please clear values field or set no value here."))

        return super(VocabularyNameValidator, self).validate(values)
Esempio n. 26
0
def validate_sub_role_unique(action, data, context, container):
    errors = []
    sub_role_id = data["role_id"]
    if sub_role_id:
        group_id = container.__parent__.group_id
        session = Session()
        title_types = session.query(domain.TitleType).filter(schema.title_types.c.group_id==group_id).all()
        if sub_role_id in [title_type.role_id for title_type in title_types]:
            errors.append(interface.Invalid(
                        _(u"A title with %s sub role already exists") % 
                        sub_role_id))
    return errors
Esempio n. 27
0
def validate_group_membership_dates(action, data, context, container):
    """ A User must be member of a group only once at a time """
    errors = []
    group_id = container.__parent__.group_id
    if interfaces.IBungeniGroupMembership.providedBy(context):
        group_membership = context
    else:
        group_membership = None
    #!(murithi, apr-2011) VALIDATION - this may be improved
    user_id = data.get('user_id', None)
    if user_id is None:
        return errors
    session = Session()
    if data['start_date']:
        for r in queries.validate_membership_in_interval(
                group_membership, domain.GroupMembership, data['start_date'],
                user_id, group_id):
            overlaps = r.group.short_name
            errors.append(
                interface.Invalid(
                    _("The person is a member in (%s) at that date") %
                    overlaps, "start_date", "user_id"))
    if data['end_date']:
        for r in queries.validate_membership_in_interval(
                group_membership, domain.GroupMembership, data['end_date'],
                user_id, group_id):
            overlaps = r.group.short_name
            errors.append(
                interface.Invalid(
                    _("The person is a member in (%s) at that date") %
                    overlaps, "end_date", "user_id"))
    for r in queries.validate_open_membership(group_membership,
                                              domain.GroupMembership, user_id,
                                              group_id):
        overlaps = r.group.short_name
        errors.append(
            interface.Invalid(
                _("The person is a member in (%s) at that date") % overlaps,
                "end_date", "user_id"))
    return errors
Esempio n. 28
0
def readmission_limit_constraint(value):
    """determine if field value exists in catalog index."""
    catalog = api.portal.get_tool('portal_catalog')
    results = catalog.searchResults(**{
        'portal_type': 'Readmission',
        'emplID': value
    })
    if len(results) > 3:
        raise interface.Invalid(
            _(u"Petition limit exceeded. Please contact [email protected] for further help"
              ))
    else:
        return True
Esempio n. 29
0
def validate_start_date_equals_end_date(action, data, context, container):
    """ Check that the start date is inside the restrictictions.
    It must not start before the contextParents start date or end
    after the contextsParents end date"""
    errors = []
    if data.get('start_date', None) and data.get('end_date', None):
        start = ui_date.get_date(data['end_date'])
        end = ui_date.get_date(data['start_date'])
        if start != end:
            errors.append(
                interface.Invalid(_(u"End date must be equal to start date"),
                                  "end_date"))
    return errors
Esempio n. 30
0
 def handleRegister(self, action):
     data, errors = self.extractData()
     self._checkForm(data)
     if errors:
         return
     if data['password'] != data['password_confirm']:
         raise interfaces.WidgetActionExecutionError(
             'password', interface.Invalid(_(u'Passwords do not match.'))
         )
     self._registerUser(data)
     self._updateDataCompany(data, data['login'])
     self._updateUser(data['login'], data)
     self._renameUserContent()
     self._sendMailToUser()
     self._sendNotificationToAdmin()
     portal_url = getToolByName(self.context, "portal_url")
     self.request.response.redirect('%s/login' % portal_url())