Repository navigation
Expand file tree
/
Copy pathvalidators.py
More file actions
200 lines (138 loc) · 5.57 KB
/
Copy pathvalidators.py
File metadata and controls
200 lines (138 loc) · 5.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""Custom field validators for InvenTree."""
import re
from decimal import Decimal, InvalidOperation
from django.conf import settings
from django.core import validators
from django.core.exceptions import FieldDoesNotExist, ValidationError
from django.utils.translation import gettext_lazy as _
from jinja2 import Template
from moneyed import CURRENCIES
import common.models
def validate_currency_code(code):
"""Check that a given code is a valid currency code."""
if code not in CURRENCIES:
raise ValidationError(_('Not a valid currency code'))
def allowable_url_schemes():
"""Return the list of allowable URL schemes.
In addition to the default schemes allowed by Django,
the install configuration file (config.yaml) can specify
extra schemas
"""
# Default schemes
schemes = ['http', 'https', 'ftp', 'ftps']
extra = settings.EXTRA_URL_SCHEMES
for e in extra:
if e.lower() not in schemes:
schemes.append(e.lower())
return schemes
class AllowedURLValidator(validators.URLValidator):
"""Custom URL validator to allow for custom schemes."""
def __call__(self, value):
"""Validate the URL."""
self.schemes = allowable_url_schemes()
super().__call__(value)
def validate_part_name(value):
"""Validate the name field for a Part instance
This function is exposed to any Validation plugins, and thus can be customized.
"""
from plugin.registry import registry
for plugin in registry.with_mixin('validation'):
# Run the name through each custom validator
# If the plugin returns 'True' we will skip any subsequent validation
if plugin.validate_part_name(value):
return
def validate_part_ipn(value):
"""Validate the IPN field for a Part instance.
This function is exposed to any Validation plugins, and thus can be customized.
If no validation errors are raised, the IPN is also validated against a configurable regex pattern.
"""
from plugin.registry import registry
plugins = registry.with_mixin('validation')
for plugin in plugins:
# Run the IPN through each custom validator
# If the plugin returns 'True' we will skip any subsequent validation
if plugin.validate_part_ipn(value):
return
# If we get to here, none of the plugins have raised an error
pattern = common.models.InvenTreeSetting.get_setting('PART_IPN_REGEX')
if pattern:
match = re.search(pattern, value)
if match is None:
raise ValidationError(_('IPN must match regex pattern {pat}').format(pat=pattern))
def validate_purchase_order_reference(value):
"""Validate the 'reference' field of a PurchaseOrder."""
from order.models import PurchaseOrder
# If we get to here, run the "default" validation routine
PurchaseOrder.validate_reference_field(value)
def validate_sales_order_reference(value):
"""Validate the 'reference' field of a SalesOrder."""
from order.models import SalesOrder
# If we get to here, run the "default" validation routine
SalesOrder.validate_reference_field(value)
def validate_tree_name(value):
"""Placeholder for legacy function used in migrations."""
...
def validate_overage(value):
"""Validate that a BOM overage string is properly formatted.
An overage string can look like:
- An integer number ('1' / 3 / 4)
- A decimal number ('0.123')
- A percentage ('5%' / '10 %')
"""
value = str(value).lower().strip()
# First look for a simple numerical value
try:
i = Decimal(value)
if i < 0:
raise ValidationError(_("Overage value must not be negative"))
# Looks like a number
return True
except (ValueError, InvalidOperation):
pass
# Now look for a percentage value
if value.endswith('%'):
v = value[:-1].strip()
# Does it look like a number?
try:
f = float(v)
if f < 0:
raise ValidationError(_("Overage value must not be negative"))
elif f > 100:
raise ValidationError(_("Overage must not exceed 100%"))
return True
except ValueError:
pass
raise ValidationError(
_("Invalid value for overage")
)
def validate_part_name_format(value):
"""Validate part name format.
Make sure that each template container has a field of Part Model
"""
# Make sure that the field_name exists in Part model
from part.models import Part
jinja_template_regex = re.compile('{{.*?}}')
field_name_regex = re.compile('(?<=part\\.)[A-z]+')
for jinja_template in jinja_template_regex.findall(str(value)):
# make sure at least one and only one field is present inside the parser
field_names = field_name_regex.findall(jinja_template)
if len(field_names) < 1:
raise ValidationError({
'value': 'At least one field must be present inside a jinja template container i.e {{}}'
})
for field_name in field_names:
try:
Part._meta.get_field(field_name)
except FieldDoesNotExist:
raise ValidationError({
'value': f'{field_name} does not exist in Part Model'
})
# Attempt to render the template with a dummy Part instance
p = Part(name='test part', description='some test part')
try:
Template(value).render({'part': p})
except Exception as exc:
raise ValidationError({
'value': str(exc)
})
return True