Пример #1
0
 def __init__(self, value):
     Invalid.__init__(self)
     self.value = value
Пример #2
0
def validate_maxtime(value):
    if value == 0:
        raise Invalid(
            _(u'Eine Angabe von 0 Stunden ergibt in diesem Kontext keinen Sinn. Bitte korrigieren.'
              ))
    return True
Пример #3
0
 def validate_same_value(data):
     if data.test_invariant_field1 != data.test_invariant_field2:
         raise Invalid(u"Must have same values")
Пример #4
0
 def dossier_manager_filled_if_protection(self):
     if ((self.reading_and_writing or self.reading)
             and not self.dossier_manager):
         raise Invalid(
             _("A dossier manager must be selected "
               " when protecting a dossier"))
Пример #5
0
def validate_email(value):
    regex = re.compile('^.+@.+\.[^.]{2,}$')
    if not regex.match(value):
        raise Invalid(_(u'Bitte geben Sie eine korrekte E-Mail-Adresse an.'))
    return True
Пример #6
0
def substituted_end_date(obj):
    """If a person is substituted he must have an end date."""
    if not obj.end_date and obj.replaced_id:
        raise Invalid(_("If a person is substituted End Date must be set"),
                      "replaced_id", "end_date")
Пример #7
0
def parliament_start_after_election(obj):
    """Start Date must be after Election Date."""
    if obj.election_date >= obj.start_date:
        raise Invalid(
            _("The life of a parliament must start after its election"),
            "election_date", "start_date")
Пример #8
0
 def validateDateFields(data):
     if data.end < data.start:
         message = 'Invalid Dates: the Star Date must be greater that End Date, please correct it.'
         raise Invalid(_('label_applications_error_datesbefore', default=message))
    def handleSaveImport(self, action):
        """Create and handle form button "Save and Import"."""

        # Extract form field values and errors from HTTP request
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return False

        import_file = data["import_file"]

        if not import_file:
            raise WidgetActionExecutionError(
                'import_file',
                Invalid(_(u"Please provide a csv file to import")))
            return

        # File upload is not saved in settings
        file_resource = import_file.data
        file_name = import_file.filename

        if not (import_file.contentType.startswith("text/") or \
            import_file.contentType.startswith("application/csv")):
            raise WidgetActionExecutionError(
                'import_file',
                Invalid(_(u"Please provide a file of type CSV")))
            return
        if import_file.contentType.startswith("application/vnd.ms-excel"):
            raise WidgetActionExecutionError(
                'import_file',
                Invalid(_(u"Please convert your Excel file to CSV first")))
            return

        if data["object_type"] in ['__ignore__', '__stop__']:
            create_new = False
            object_type = None
        else:
            create_new = True
            object_type = data["object_type"]

        # list all the dexterity types
        #dx_types = get_portal_types(self.request)
        #log.debug(dx_types)

        # based from the types, display all the fields
        # fields = get_schema_info(CREATION_TYPE)
        # log.debug(fields)

        # blank header or field means we don't want it
        header_mapping = [
            d for d in data['header_mapping'] if d['field'] and d['header']
        ]

        matching_headers = dict([(d['field'], d['header'])
                                 for d in header_mapping])

        if create_new and not (matching_headers.get('id')
                               or matching_headers.get('title')):
            raise WidgetActionExecutionError(
                'header_mapping',
                Invalid(
                    _(u"If creating new content you need either 'Short Name"
                      u" or 'Title' in your data.")))
            return

        if not matching_headers:
            raise WidgetActionExecutionError(
                'header_mapping',
                Invalid(
                    _(u"You must pick which fields should contain your data")))
            return

        primary_key = data["primary_key"]
        if primary_key and not matching_headers.get(primary_key):
            raise WidgetActionExecutionError(
                'primary_key',
                Invalid(_(u"Must be a field selected in Header Mapping")))
            return

        # based from the matching fields, get all the values.
        matching_fields = dict([(d['header'], d['field'])
                                for d in header_mapping])
        import_metadata = dexterity_import(self.context, file_resource,
                                           matching_fields, object_type,
                                           create_new, primary_key)

        existing_count = import_metadata["existing_count"]
        new_count = import_metadata["new_count"]
        ignore_count = import_metadata["ignore_count"]

        api.portal.show_message(
            message=_(
                "import_message_csv_info",  # nopep8
                default=u"""${new_num} items added,
                    ${existing_num} items updated and
                    ${ignore_num} items skipped
                    from ${filename}""",
                mapping={
                    "new_num": new_count,
                    "existing_num": existing_count,
                    "ignore_num": ignore_count,
                    "filename": file_name
                }),
            request=self.request,
            type="info")

        self.import_metadata = import_metadata

        # Save our sucessful settings to save time next import
        annotations = IAnnotations(self.context)
        settings = annotations.setdefault(KEY, {})
        settings['header_list'] = [d['header'] for d in header_mapping]
        # we will keep making this bigger in case they switch between several CSVs
        settings.setdefault("matching_fields", {}).update(matching_fields)
        settings['primary_key'] = primary_key
        settings['object_type'] = object_type

        return True
Пример #10
0
 def check_users_folder(self):
     """Check for open registration"""
     if self.open_registration and not self.users_folder:
         raise Invalid(
             _("You can't activate open registration without selecting a users "
               "folder"))
Пример #11
0
    def _init(self, resource_class, resource_interface, resource_type, **kw):
        """ """

        if "default" in kw:

            if (isinstance(kw["default"],
                           (str, dict)) or kw["default"] is None) is False:
                msg = ("Only dict or string or None is accepted as "
                       "default value but got {0}".format(type(kw["default"])))

                raise Invalid(msg)

        field_attributes = get_fields(IFhirField)

        attribute = field_attributes['resource_class'].bind(self)
        if resource_class is None:
            attribute.validate(resource_class)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(resource_class)
        attribute.set(self, attribute_val)

        attribute = field_attributes['resource_interface'].bind(self)
        if resource_interface is None:
            attribute.validate(resource_interface)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(resource_interface)
        attribute.set(self, attribute_val)

        attribute = field_attributes['resource_type'].bind(self)
        if resource_type is None:
            attribute.validate(resource_type)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(resource_type)
        attribute.set(self, attribute_val)

        if self.resource_type and self.resource_class is not None:
            raise Invalid(
                "Either `resource_class` or `resource_type` value is acceptable! you cannot provide both!"
            )

        if self.resource_class:
            try:
                klass = import_string(self.resource_class)
            except ImportError:
                msg = "Invalid FHIR Resource class `{0}`! Please check the module or class name.".format(
                    self.resource_class)

                t, v, tb = sys.exc_info()
                try:
                    reraise(Invalid(msg), None, tb)
                finally:
                    del t, v, tb

            if not IFhirResource.implementedBy(klass):

                raise Invalid(
                    "{0!r} must be valid resource class from fhir.resources".
                    format(klass))
            self._resource_class = klass

        if self.resource_type:

            try:
                self._resource_class = resource_type_to_resource_cls(
                    self.resource_type)
            except ImportError:
                msg = "{0} is not valid fhir resource type!".format(
                    self.resource_type)
                t, v, tb = sys.exc_info()
                try:
                    reraise(Invalid(msg), None, tb)
                finally:
                    del t, v, tb
                raise Invalid(msg)

        if self.resource_interface:
            try:
                klass = import_string(self.resource_interface)
            except ImportError:
                msg = "Invalid FHIR Resource Interface`{0}`! Please check the module or class name.".format(
                    self.resource_interface)
                t, v, tb = sys.exc_info()
                try:
                    reraise(Invalid(msg), None, tb)
                finally:
                    del t, v, tb

            if not IInterface.providedBy(klass):
                raise WrongType("An interface is required", klass,
                                self.__name__)

            if klass is not IFhirResource and not issubclass(
                    klass, IFhirResource):
                msg = "`{0!r}` must be derived from {1}".format(
                    klass,
                    IFhirResource.__module__ + "." +
                    IFhirResource.__class__.__name__,
                )

                raise Invalid(msg)

            self._resource_interface_class = klass
Пример #12
0
 def check_activated_user(self):
     """Check for missing password of activated user"""
     if not self.password and not self.wait_confirmation:
         raise Invalid(
             _("You can't activate an account without setting a password!"))
Пример #13
0
 def check_email(self):
     """Check for invalid email address"""
     if not EMAIL_REGEX.match(self.email):
         raise Invalid(_("Given email address is not valid!"))
Пример #14
0
 def check_password(self):
     """Check for password confirmation"""
     if self.password != self.confirmed_password:
         raise Invalid(_("You didn't confirmed your password correctly!"))
     check_password(self.password)
Пример #15
0
 def __init__(self, value, allowed):
     Invalid.__init__(self)
     self.value = value
     self.allowed = allowed
Пример #16
0
 def validate_start_end(obj):
     if not (obj.start is None or obj.end is None) and obj.start > obj.end:
         raise Invalid(_(u"Start date cannot be after end date."))
Пример #17
0
def validate_recurring_sittings(action, data, context, container):
    """Validate recurring sittings.

    This validator determines the sittings that will be created and
    confirms the validity of them.
    """

    start = data.get("start_date")
    end = data.get("end_date")
    weekdays = data.get("weekdays")
    monthly = data.get("monthly")
    repeat = data.get("repeat")
    repeat_until = data.get("repeat_until")
    exceptions = data.get("exceptions", ())

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

    errors = []
    if weekdays or monthly:
        # this should be an invariant, but due to formlib's requirement
        # that invariant methods pertain to a single schema, it's not
        # possible
        if repeat_until is not None and repeat_until < start.date():
            #session.close()
            return [
                Invalid(
                    _(u"If recurrence is limited by date, it "
                      "must lie after the starting date"), "repeat_until")
            ]

        # verify that dates do not violate group's end date
        for date in generate_recurring_sitting_dates(start.date(), repeat,
                                                     repeat_until, weekdays,
                                                     monthly, exceptions):
            if group.end_date is not None and date > group.end_date:
                errors.append(
                    Invalid(
                        _(
                            u"One or more events would be scheduled for $F, which is "
                            "after the scheduling group's end date",
                            mapping={"F": datetimedict.fromdate(date)}),
                        "repeat" if repeat else "repeat_until"))
                break
            event_data = {
                "start_date":
                datetime.datetime(date.year, date.month, date.day, start.hour,
                                  start.minute),
                "end_date":
                datetime.datetime(date.year, date.month, date.day, end.hour,
                                  end.minute),
            }
            errors.extend(
                validate_non_overlapping_sitting(
                    action, event_data, context, container,
                    "weekdays" if weekdays else "monthly"))
            if errors:
                break
            errors.extend(validate_venues(action, data, context, container))
            if errors:
                break
    return logged_errors(errors, "validate_recurring_sittings")
    def emailAddressValidation(self):
        #pattern = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"

        if self.email1 != self.email2:
            raise Invalid(_("Both email addresses do not match"))
Пример #19
0
def inactive_no_end_date(obj):
    """If you set a person inactive you must provide an end date."""
    if not obj.active_p:
        if not (obj.end_date):
            raise Invalid(_("If a person is inactive End Date must be set"),
                          "end_date", "active_p")
Пример #20
0
def valid_filing_year(value):
    if tryint(value):
        if 1900 < int(value) < 3000:
            if str(int(value)) == value:
                return True
    raise Invalid(_(u'The given value is not a valid Year.'))
Пример #21
0
def active_and_substituted(obj):
    """A person cannot be active and substituted at the same time."""
    if obj.active_p and obj.replaced_id:
        raise Invalid(
            _("A person cannot be active and substituted at the same time"),
            "active_p", "replaced_id")
Пример #22
0
 def licensenotchoosen(value):
     if not value.licenses_choice:
         raise Invalid(_(safe_unicode('Please choose a license for your release.')))
Пример #23
0
    def _init(
        self, resource_class, resource_interface, resource_type, fhir_release, **kw
    ):
        """ """
        if "default" in kw:

            if (
                isinstance(kw["default"], (str, dict)) or kw["default"] is None
            ) is False:
                msg = (
                    "Only dict or string or None is accepted as "
                    "default value but got {0}".format(type(kw["default"]))
                )

                raise Invalid(msg)

        field_attributes = get_fields(IFhirField)

        attribute = field_attributes["resource_class"].bind(self)
        if resource_class is None:
            attribute.validate(resource_class)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(resource_class)
        attribute.set(self, attribute_val)

        attribute = field_attributes["resource_interface"].bind(self)
        if resource_interface is None:
            attribute.validate(resource_interface)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(resource_interface)
        attribute.set(self, attribute_val)

        attribute = field_attributes["resource_type"].bind(self)
        if resource_type is None:
            attribute.validate(resource_type)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(resource_type)
        attribute.set(self, attribute_val)

        attribute = field_attributes["fhir_release"].bind(self)
        if fhir_release is None:
            attribute.validate(fhir_release)
            attribute_val = None
        else:
            attribute_val = attribute.from_unicode(fhir_release)
            # just for ensure correct value
            FHIR_VERSION[attribute_val]
        attribute.set(self, attribute_val)

        if self.resource_type and self.resource_class is not None:
            raise Invalid(
                "Either `resource_class` or `resource_type` value is acceptable! "
                "you cannot provide both!"
            )

        if self.resource_class:
            try:
                klass = import_string(self.resource_class)
                self.ensure_fhir_abstract(klass)

            except ImportError:
                msg = (
                    "Invalid FHIR Resource class `{0}`! "
                    "Please check the module or class name."
                ).format(self.resource_class)

                return reraise(Invalid, msg)

            if not IFhirResource.implementedBy(klass):

                raise Invalid(
                    "{0!r} must be valid resource class from fhir.resources".format(
                        klass
                    )
                )
            self._resource_class = klass

        if self.resource_type:

            try:
                self._resource_class = implementer(IFhirResource)(
                    lookup_fhir_class(self.resource_type)
                )
            except ImportError:
                msg = "{0} is not valid fhir resource type!".format(self.resource_type)
                return reraise(Invalid, msg)

        if self.resource_interface:
            try:
                klass = implementer(IFhirResource)(
                    import_string(self.resource_interface)
                )
            except ImportError:
                msg = (
                    "Invalid FHIR Resource Interface`{0}`! "
                    "Please check the module or class name."
                ).format(self.resource_interface)
                return reraise(Invalid, msg)

            if not IInterface.providedBy(klass):
                raise WrongType("An interface is required", klass, self.__name__)

            if klass is not IFhirResource and not issubclass(klass, IFhirResource):
                msg = "`{0!r}` must be derived from {1}".format(
                    klass,
                    IFhirResource.__module__ + "." + IFhirResource.__class__.__name__,
                )

                raise Invalid(msg)

            self._resource_interface_class = klass
Пример #24
0
 def compatibilitynotchoosen(data):
     if not data.compatibility_choice:
         raise Invalid(_(safe_unicode(
             'Please choose one or more compatible product '
             'versions for your release.')))
Пример #25
0
def validate_adressen(value):
    regex = re.compile('^.+@.+\.[^.]{2,}$')
    for i in value:
        if not regex.match(i):
            raise Invalid(_(u'%s ist keine korrekte E-Mail-Adresse' % i))
    return True
Пример #26
0
 def noOSChosen(data):
     if data.link_to_file is not None and data.platform_choice == []:
         raise Invalid(_(
             safe_unicode(
                 'Please choose a compatible platform for the '
                 'linked file.')))
Пример #27
0
def validate_feed_uri(feed):
    result = urlparse(feed)
    if not all([result.scheme, result.netloc]):
        raise Invalid(_(u'The feed URI is invalid: ') + feed)
    return True
Пример #28
0
 def check_skin(self):
     """Check for required skin if not inherited"""
     if self.no_inherit_skin and not self.skin:
         raise Invalid(
             _("You must select a custom skin or inherit from parent!"))
Пример #29
0
 def validate_content(data):
     if data.content and len(data.content) != 1:
         raise Invalid("Must select 1 item")
 def password_invariant(data):
     if data.confirm_password != data.password:
         raise Invalid(_(u'Password fields do not match'))
Пример #31
0
 def __init__(self, obj, iface):
     Invalid.__init__(self)
     self.obj = obj
     self.iface = iface
Пример #32
0
 def validate_location_required(data):
     if data.meeting_type != 'webinar' and data.location is None:
         raise Invalid(_(
             u"Event location input is missing." +
             " This field is not required only in " +
             "'Meeting type: webinar' case."))
Пример #33
0
 def __init__(self, obj, attr):
     Invalid.__init__(self)
     self.obj = obj
     self.attr = attr
Пример #34
0
def validate_member_titles(action, data, context, container):
    """Titles for members follow the restrictions:
    A person must have the same title only once (e.g. you cannot
    be chairperson in a group twice at a time)
    If a Title is unique (e.g. chairperson) there can be only one person 
    at a time in this group holding this title, other titles like member 
    may be applied to several persons at the same time"""
    def get_q_user(date):
        return session.query(GroupMemberTitle).filter(
            rdb.and_(
                GroupMemberTitle.group_id == group_id,
                GroupMemberTitle.membership_id == membership_id,
                GroupMemberTitle.title_type_id == title_type_id,
                rdb.or_(
                    rdb.between(date, schema.member_title.c.start_date,
                                schema.member_title.c.end_date),
                    schema.member_title.c.end_date == None)))

    def get_q_unique(date):
        return session.query(GroupMemberTitle).filter(
            rdb.and_(
                GroupMemberTitle.group_id == group_id,
                schema.title_type.c.user_unique == True,
                GroupMemberTitle.title_type_id == title_type_id,
                rdb.or_(
                    rdb.between(date, schema.member_title.c.start_date,
                                schema.member_title.c.end_date),
                    schema.member_title.c.end_date == None)))

    start_date = data.get("start_date")
    end_date = data.get("end_date")
    errors = []
    group_id = container.__parent__.group_id
    membership_id = container.__parent__.membership_id
    session = Session()
    title_type_id = data.get("title_type_id")
    if interfaces.IMemberTitle.providedBy(context):
        title = context
    else:
        title = None
    if start_date:
        q = get_q_user(start_date)
        results = q.all()
        for result in results:
            overlaps = result.title_name
            if title:
                if title.member_title_id == result.member_title_id:
                    continue
                else:
                    errors.append(
                        Invalid(
                            _(u"This persons already has the title %s") %
                            (overlaps), "start_date"))
            else:
                errors.append(
                    Invalid(
                        _(u"This persons already has the title %s") %
                        (overlaps), "start_date"))
    if end_date:
        q = get_q_user(end_date)
        results = q.all()
        for result in results:
            overlaps = result.title_name
            if title:
                if title.member_title_id == result.member_title_id:
                    continue
                else:
                    errors.append(
                        Invalid(
                            _(u"This persons already has the title %s") %
                            (overlaps), "end_date"))
            else:
                errors.append(
                    Invalid(
                        _(u"This persons already has the title %s") %
                        (overlaps), "end_date"))
    if start_date:
        q = get_q_unique(start_date)
        results = q.all()
        for result in results:
            overlaps = result.title_name
            if title:
                if title.member_title_id == result.member_title_id:
                    continue
                else:
                    errors.append(
                        Invalid(
                            _(u"A person with the title %s already exists") %
                            (overlaps), "start_date"))
            else:
                errors.append(
                    Invalid(
                        _(u"A person with the title %s already exists") %
                        (overlaps), "start_date"))
    if end_date:
        q = get_q_unique(end_date)
        results = q.all()
        for result in results:
            overlaps = result.title_name
            if title:
                if title.member_title_id == result.member_title_id:
                    continue
                else:
                    errors.append(
                        Invalid(
                            _(u"A person with the title %s already exists") %
                            (overlaps), "end_date"))
            else:
                errors.append(
                    Invalid(
                        _(u"A person with the title %s already exists") %
                        (overlaps), "end_date"))
    return logged_errors(errors, "validate_member_titles")