class CreateActivitySchema(colander.MappingSchema): """ Activity creation schema """ come_from = forms.come_from_node() conseillers = ConseillerSequence( title=u"Conseillers menant le rendez-vous", widget=deform.widget.SequenceWidget(min_len=1) ) datetime = forms.now_node(title=u"Date de rendez-vous") type_id = colander.SchemaNode( colander.Integer(), widget=get_deferred_select_type(), title=u"Nature du rendez-vous", ) action_id = colander.SchemaNode( colander.Integer(), widget=deferred_select_action, title=u"Intitulé de l'action (financée)", ) subaction_id = colander.SchemaNode( colander.Integer(), widget=deferred_select_subaction, title=u"Intitulé sous-action", missing=None, ) mode = colander.SchemaNode( colander.String(), widget=deferred_select_mode, title=u"Mode d'entretien", ) participants = ParticipantsSequence( title=u"Participants", description=u"Participants attendus au rendez-vous", widget=deform.widget.SequenceWidget(min_len=1) ) companies = CompanySequence( title=u"Entreprises concernées (donner le droit de consultation)", description=u"Les membres de ces entreprises qui ne participent \ pas au rendez-vous peuvent quand même le consulter.", )
class ValidCellKeySchema(ValidCellAreaKeySchema): cid = DefaultNode( colander.Integer(), missing=None, validator=colander.Range(constants.MIN_CID, constants.MAX_CID)) psc = DefaultNode( colander.Integer(), missing=None, validator=colander.Range(constants.MIN_PSC, constants.MAX_PSC)) def __init__(self, *args, **kw): super(ValidCellKeySchema, self).__init__(*args, **kw) self.radio_node = self.get('radio') def deserialize(self, data): if data: # shallow copy data = dict(data) # deserialize and validate radio field early data['radio'] = self.radio_node.deserialize( data.get('radio', colander.null)) # If the cell id > 65535 then it must be a WCDMA tower if (data['radio'] is Radio['gsm'] and data.get('cid') is not None and data.get('cid', 0) > constants.MAX_CID_GSM): data['radio'] = Radio['wcdma'] if (data['radio'] is Radio['lte'] and data.get('psc') is not None and data.get('psc', 0) > constants.MAX_PSC_LTE): data['psc'] = None return super(ValidCellKeySchema, self).deserialize(data) def validator(self, node, cstruct): super(ValidCellKeySchema, self).validator(node, cstruct) if ((cstruct.get('lac') is None or cstruct.get('cid') is None) and cstruct.get('psc') is None): raise colander.Invalid(node, ('Must have (LAC and CID) or PSC.'))
class CreditCardSchema(colander.MappingSchema): card_number = colander.SchemaNode(colander.String(), validator=colander.luhnok, required=True) expiration_month = colander.SchemaNode(colander.Integer(), validator=colander.Range(1, 12), missing=None) expiration_year = colander.SchemaNode(colander.Integer(), validator=colander.Range(date.today().year, date.today().year + 12), missing=None) expiration_date = colander.SchemaNode(colander.String(), validator=colander.Regex( r'^\d{2}.?(?:\d{4}|\d{2})?$', 'The expiration date is invalid'), missing=None) card_code = colander.SchemaNode(colander.String(), validator=colander.Regex(r'^[0-9]{3,4}$', 'The card code is invalid'), missing=colander.drop) @staticmethod def validator(node, kw): exp_year = kw['expiration_year'] exp_month = kw['expiration_month'] exp_date = kw['expiration_date'] # We only need exp_date or exp_year and exp_month if exp_date is None and (exp_year is None and exp_month is None): raise colander.Invalid(node, 'You must provide a card expiration date') if exp_date is not None: exp_month = exp_date[:2] exp_year = '20' + exp_date[-2:] elif exp_month is None: raise colander.Invalid(node, 'You must provide a card expiration month') elif exp_year is None: raise colander.Invalid(node, 'You must provide a card expiration year') if exp_year == date.today().year and exp_month < date.today().month: raise colander.Invalid(node, 'The credit card has expired') kw['expiration_year'] = str(exp_year) kw['expiration_month'] = str(exp_month).zfill(2)
class ValidCellKeySchema(ValidCellAreaKeySchema): cid = DefaultNode( colander.Integer(), missing=None, validator=colander.Range(constants.MIN_CID, constants.MAX_CID), ) psc = DefaultNode( colander.Integer(), missing=None, validator=colander.Range(constants.MIN_PSC, constants.MAX_PSC), ) def __init__(self, *args, **kw): super(ValidCellKeySchema, self).__init__(*args, **kw) self.radio_node = self.get("radio") def deserialize(self, data): if data: # shallow copy data = dict(data) # deserialize and validate radio field early data["radio"] = self.radio_node.deserialize( data.get("radio", colander.null)) # If the cell id > 65535 then it must be a WCDMA tower if (data["radio"] is Radio["gsm"] and data.get("cid") is not None and data.get("cid", 0) > constants.MAX_CID_GSM): data["radio"] = Radio["wcdma"] if (data["radio"] is Radio["lte"] and data.get("psc") is not None and data.get("psc", 0) > constants.MAX_PSC_LTE): data["psc"] = None return super(ValidCellKeySchema, self).deserialize(data) def validator(self, node, cstruct): super(ValidCellKeySchema, self).validator(node, cstruct) if (cstruct.get("lac") is None or cstruct.get("cid") is None) and cstruct.get("psc") is None: raise colander.Invalid(node, ("Must have (LAC and CID) or PSC."))
class PaginatedSchema(colander.MappingSchema): chrome = colander.SchemaNode( colander.Boolean(true_choices=('true', '1')), location="querystring", missing=True, ) page = colander.SchemaNode( colander.Integer(), validator=colander.Range(min=1), location="querystring", missing=1, ) rows_per_page = colander.SchemaNode( colander.Integer(), validator=colander.Range(min=1, max=1000), location="querystring", missing=20, )
class _InvoiceSumSchema(ResourceSchema): order_id = colander.SchemaNode( colander.Integer(), ) date = colander.SchemaNode( Date(), ) account_id = colander.SchemaNode( colander.String(), validator=account_validator, )
def dataclass_field_to_colander_schemanode( prop: dataclasses.Field, oid_prefix='deformField') -> colander.SchemaNode: t = dataclass_get_type(prop) if t['type'] == date: return colander.SchemaNode(typ=colander.Date(), name=prop.name, oid='%s-%s' % (oid_prefix, prop.name), missing=colander.required if t['required'] else colander.drop) if t['type'] == datetime: return colander.SchemaNode(typ=colander.DateTime(), name=prop.name, oid='%s-%s' % (oid_prefix, prop.name), missing=colander.required if t['required'] else colander.drop) if t['type'] == str: return colander.SchemaNode(typ=colander.String(), name=prop.name, oid='%s-%s' % (oid_prefix, prop.name), missing=colander.required if t['required'] else colander.drop) if t['type'] == int: return colander.SchemaNode(typ=colander.Integer(), name=prop.name, oid='%s-%s' % (oid_prefix, prop.name), missing=colander.required if t['required'] else colander.drop) if t['type'] == float: return colander.SchemaNode(typ=colander.Float(), name=prop.name, oid='%s-%s' % (oid_prefix, prop.name), missing=colander.required if t['required'] else colander.drop) if t['type'] == bool: return colander.SchemaNode(typ=colander.Boolean(), name=prop.name, oid='%s-%s' % (oid_prefix, prop.name), missing=colander.required if t['required'] else colander.drop) if dataclass_check_type(prop, ISchema): subtype = dataclass_to_colander( t['type'], colander_schema_type=colander.MappingSchema) return subtype() if t['type'] == dict: return colander.SchemaNode(typ=colander.Mapping(), name=prop.name, oid='%s-%s' % (oid_prefix, prop.name), missing=colander.required if t['required'] else colander.drop) if t['type'] == list: return colander.SchemaNode( typ=colander.List(), name=prop.name, oid='%s-%s' % (oid_prefix, prop.name), missing=colander.required if t['required'] else colander.drop) raise KeyError(prop)
def test_range_max(self): import colander from .. import convert node = colander.SchemaNode(colander.Integer(), validator=colander.Range(max=444)) ret = convert(node) self.assertDictEqual(ret, { '$schema': 'http://json-schema.org/draft-04/schema#', 'type': 'integer', 'maximum': 444, })
def test_enum(self): import colander from .. import convert node = colander.SchemaNode(colander.Integer(), validator=colander.OneOf([1, 2, 3, 4])) ret = convert(node) self.assertDictEqual(ret, { '$schema': 'http://json-schema.org/draft-04/schema#', 'type': 'integer', 'enum': [1, 2, 3, 4], })
def test_default_null(self): import colander from .. import convert node = colander.SchemaNode(colander.Integer(), missing=None, default=None) ret = convert(node) self.assertDictEqual(ret, { '$schema': 'http://json-schema.org/draft-04/schema#', 'type': ['integer', 'null'], 'default': None, })
class AddSchema(colander.Schema): group_widget = widget.AutocompleteInputWidget( size=60, values='/group/headofnama/act', min_length=1) user_widget = widget.AutocompleteInputWidget(size=60, values='/user/headofnama/act', min_length=1) user_name = colander.SchemaNode(colander.String(), widget=user_widget, oid="user_nm") group_name = colander.SchemaNode(colander.String(), widget=group_widget, oid="group_nm") group_id = colander.SchemaNode(colander.Integer(), widget=widget.HiddenWidget(), oid="group_id") user_id = colander.SchemaNode(colander.Integer(), widget=widget.HiddenWidget(), oid="user_id")
class DuplicateSchema(NewTaskSchema): """ schema used to duplicate a task """ customer_id = colander.SchemaNode( colander.Integer(), title=u"Choix du client", widget=deferred_company_customer_widget, validator=deferred_company_customer_validator, default=deferred_default_customer, )
class ValidCellLookupSchema(ValidCellKeySchema): """A schema which validates the fields in a cell lookup.""" asu = DefaultNode(colander.Integer(), missing=-1, validator=colander.Range(0, 97)) signal = DefaultNode(colander.Integer(), missing=0, validator=colander.Range(-150, -1)) ta = DefaultNode(colander.Integer(), missing=0, validator=colander.Range(0, 63)) def deserialize(self, data): if data: # Sometimes the asu and signal fields are swapped if data.get('asu', 0) < -1 and data.get('signal', None) == 0: data['signal'] = data['asu'] data['asu'] = self.fields['asu'].missing return super(ValidCellLookupSchema, self).deserialize(data)
class ValidCellAreaKeySchema(colander.MappingSchema, ValidatorNode): radio = DefaultNode(RadioType()) mcc = colander.SchemaNode(colander.Integer()) mnc = colander.SchemaNode(colander.Integer()) lac = DefaultNode( colander.Integer(), missing=None, validator=colander.Range(constants.MIN_LAC, constants.MAX_LAC), ) def validator(self, node, cstruct): super(ValidCellAreaKeySchema, self).validator(node, cstruct) if cstruct["mcc"] not in constants.ALL_VALID_MCCS: raise colander.Invalid( node, ("Check against the list of all known valid mccs")) if not (constants.MIN_MNC <= cstruct["mnc"] <= constants.MAX_MNC): raise colander.Invalid(node, ("MNC out of valid range."))
class StackTraceFrameSchema(colander.MappingSchema): filename = colander.SchemaNode(colander.String()) line_number = colander.SchemaNode(colander.Integer(), validator=colander.Range(min=0)) function = colander.SchemaNode(colander.String()) pre_context = StackTraceFrameContextLinesSchema() context = colander.SchemaNode(colander.String()) post_context = StackTraceFrameContextLinesSchema() variables = colander.SchemaNode(colander.Mapping(unknown='preserve'), validator=_valid_variables_mapping)
class UserSchema(CSRFSchema): username = colander.SchemaNode(colander.String(), description="Extension of the user") name = colander.SchemaNode(colander.String(), description='Full name') email = colander.SchemaNode(colander.String(), validator=colander.Email(), description="Email", missing=None), age = colander.SchemaNode(colander.Integer(), description='Age')
class _CompanyAddSchema(ResourceSchema): email = colander.SchemaNode(colander.String(), validator=colander.All( colander.Email(), colander.Length(max=32))) name = colander.SchemaNode(colander.String(), ) timezone = colander.SchemaNode(colander.String(), ) locale = colander.SchemaNode(colander.String(), ) currency_id = colander.SchemaNode( colander.Integer(), missing=None, )
class ValidCellAreaKeySchema(colander.MappingSchema, ValidatorNode): radioType = DefaultNode(RadioType()) mobileCountryCode = colander.SchemaNode(colander.Integer()) mobileNetworkCode = colander.SchemaNode(colander.Integer()) locationAreaCode = DefaultNode( colander.Integer(), missing=None, validator=colander.Range(constants.MIN_LAC, constants.MAX_LAC)) def validator(self, node, cstruct): super(ValidCellAreaKeySchema, self).validator(node, cstruct) if cstruct['mobileCountryCode'] not in constants.ALL_VALID_MCCS: raise colander.Invalid(node, ( 'Check against the list of all known valid mccs')) if (not (constants.MIN_MNC <= cstruct['mobileNetworkCode'] <= constants.MAX_MNC)): raise colander.Invalid(node, ('MNC out of valid range.'))
def user_node(roles=None, multiple=False, **kw): """ Return a schema node for user selection roles: allow to restrict the selection to the given roles (to select between admin, contractor and manager) """ widget_options = kw.pop('widget_options', {}) return colander.SchemaNode( colander.Set() if multiple else colander.Integer(), widget=get_deferred_user_choice(roles, widget_options), **kw)
class _SubaccountSchema(ResourceSchema): account_id = colander.SchemaNode(colander.String(), validator=account_validator) subaccount_type = colander.SchemaNode(colander.String(), validator=subaccount_type_validator) source_id = colander.SchemaNode(colander.Integer(), validator=source_id_validator) name = colander.SchemaNode(colander.String(), validator=name_validator) descr = colander.SchemaNode(colander.String(), missing=None, validator=colander.Length(max=255))
class EstimationPayments(colander.MappingSchema): """ Gestion des acomptes """ deposit = colander.SchemaNode(colander.Integer(), title=u"Acompte à la commande", default=0, widget=deform.widget.SelectWidget( values=get_percents(), css_class='col-md-2')) payment_times = colander.SchemaNode(colander.Integer(), title=u"Paiement en ", default=1, widget=deform.widget.SelectWidget( values=get_payment_times(), css_class='col-md-2')) paymentDisplay = colander.SchemaNode( colander.String(), validator=colander.OneOf([x[0] for x in PAYMENTDISPLAYCHOICES]), widget=deform.widget.RadioChoiceWidget(values=PAYMENTDISPLAYCHOICES), title=u"Affichage des paiements", default="SUMMARY") payment_lines = EstimationPaymentLines( widget=deform.widget.SequenceWidget( template=TEMPLATES_URL + 'paymentlines_sequence.pt', item_template=TEMPLATES_URL + 'paymentlines_sequence_item.pt', min_len=1), title=u'', description=u"Définissez les échéances de paiement") payment_conditions_select = colander.SchemaNode( colander.String(), widget=forms.get_deferred_select(PaymentConditions), title=u"Conditions de paiement prédéfinies", missing=colander.drop, ) payment_conditions = forms.textarea_node( title=u"Conditions de paiement", default=deferred_default_payment_condition, )
class ValidWifiLookupSchema(ValidWifiKeySchema): """A schema which validates the fields in a wifi lookup.""" channel = colander.SchemaNode(colander.Integer(), missing=0, validator=colander.Range( constants.MIN_WIFI_CHANNEL, constants.MAX_WIFI_CHANNEL)) signal = DefaultNode(colander.Integer(), missing=0, validator=colander.Range(constants.MIN_WIFI_SIGNAL, constants.MAX_WIFI_SIGNAL)) snr = DefaultNode(colander.Integer(), missing=0, validator=colander.Range(0, 100)) def deserialize(self, data): if data: channel = int(data.get('channel', 0)) if not (constants.MIN_WIFI_CHANNEL < channel < constants.MAX_WIFI_CHANNEL): # if no explicit channel was given, calculate freq = data.get('frequency', 0) if 2411 < freq < 2473: # 2.4 GHz band data['channel'] = (freq - 2407) // 5 elif 5169 < freq < 5826: # 5 GHz band data['channel'] = (freq - 5000) // 5 else: data['channel'] = self.fields['channel'].missing # map external name to internal if data.get('snr', None) is None: data['snr'] = data.get('signalToNoiseRatio', 0) return super(ValidWifiLookupSchema, self).deserialize(data)
class WebhookSchema(colander.Schema): hook_url = colander.SchemaNode(colander.String(), widget=widget.TextInputWidget()) hook_type = colander.SchemaNode( colander.String(), widget=widget.SelectWidget(values=hooktypes), validator=colander.OneOf(('discord', 'generic'))) enabled = colander.SchemaNode( colander.Boolean(), widget=widget.CheckboxWidget(template="bootstrap"), required=False) jumpEvents = colander.SchemaNode( colander.Boolean(), widget=widget.CheckboxWidget(template="bootstrap"), required=False) marketEvents = colander.SchemaNode( colander.Boolean(), widget=widget.CheckboxWidget(template="bootstrap"), required=False) calendarEvents = colander.SchemaNode( colander.Boolean(), widget=widget.CheckboxWidget(template="bootstrap"), required=False) description = colander.SchemaNode(colander.String(), widget=widget.TextInputWidget(), required=False) id = colander.SchemaNode(colander.Integer(), widget=widget.HiddenWidget(), required=False, default=None, missing=colander.drop) owner_id = colander.SchemaNode(colander.Integer(), widget=widget.HiddenWidget(), required=False, default=None, missing=colander.drop) carrier_id = colander.SchemaNode(colander.Integer(), widget=widget.HiddenWidget(), required=False, default=None, missing=colander.drop)
class _IncomeSchema(ResourceSchema): invoice_id = colander.SchemaNode( colander.Integer(), validator=invoice_validator ) account_item_id = colander.SchemaNode( colander.Integer(), validator=account_item_validator ) date = colander.SchemaNode( Date(), ) sum = colander.SchemaNode( colander.Money(), validator=colander.Range(min=0) ) descr = colander.SchemaNode( colander.String(), validator=colander.Length(max=255), missing=None )
class _TaskSchema(ResourceSchema): task_resource_id = colander.SchemaNode( colander.Integer(), missing=None, ) title = colander.SchemaNode(colander.String(), validator=colander.Length(min=2, max=128)) deadline = colander.SchemaNode(DateTime()) reminder = colander.SchemaNode(colander.Integer(), ) descr = colander.SchemaNode(colander.String(), ) status = colander.SchemaNode(colander.String(), ) upload_id = colander.SchemaNode(colander.Set(), missing=[]) def deserialize(self, cstruct): if ('upload_id' in cstruct and not isinstance(cstruct.get('upload_id'), list)): val = cstruct['upload_id'] cstruct['upload_id'] = list() cstruct['upload_id'].append(val) return super(_TaskSchema, self).deserialize(cstruct)
class ValidateCreditCardSchema(colander.MappingSchema): address_id = colander.SchemaNode(colander.String(), validator=colander.Length(max=60), missing=colander.drop) card_code = colander.SchemaNode(colander.Integer(), validator=colander.Range(100, 9999), missing=colander.drop) # A test mode is required for this transaction type. By default, we will # use 'testMode' validation_mode = colander.SchemaNode(colander.String(), validator=colander.OneOf(['liveMode', 'testMode']), missing='testMode')
class TvaPayment(colander.MappingSchema): amount = colander.SchemaNode( AmountType(5), title=u"Montant de l'encaissement", ) tva_id = colander.SchemaNode( colander.Integer(), title=u"Tva liée à cet encaissement", widget=forms.get_deferred_select(Tva, mandatory=True, keys=('id', 'name')), )
class AccountEntryEditSchema(colander.Schema): # Validate these fields only lightly. The code will do its own # parsing and validation. id = colander.SchemaNode(colander.Integer(), missing=None) statement_id = colander.SchemaNode(colander.Integer()) delta = colander.SchemaNode(colander.String(), validator=colander.All( colander.Length(max=50), colander.Regex( amount_re, msg="The amount is not valid"), )) entry_date = colander.SchemaNode(colander.String(), validator=colander.Length(max=50)) sheet = colander.SchemaNode(colander.String(), missing='', validator=colander.Length(max=50)) row = colander.SchemaNode(colander.Integer(), missing=None) description = colander.SchemaNode(colander.String(), missing='', validator=colander.Length(max=1000))
class DevicesItem(colander.MappingSchema): def schema_type(self, **kw): return colander.Mapping(unknown='raise') type_ = colander.SchemaNode( colander.String(), name='type', ) count = colander.SchemaNode( colander.Integer(), missing=1, )
class SequenceItem(OptionalMappingSchema): radioType = OptionalNode(colander.String()) mobileCountryCode = OptionalNode(colander.Integer()) mobileNetworkCode = OptionalNode(colander.Integer()) locationAreaCode = OptionalNode(colander.Integer()) cellId = OptionalNode(colander.Integer()) age = OptionalNode(colander.Integer()) signalStrength = OptionalNode(colander.Integer()) timingAdvance = OptionalNode(colander.Integer())