-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidators.py
More file actions
98 lines (87 loc) · 3.43 KB
/
validators.py
File metadata and controls
98 lines (87 loc) · 3.43 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
import rest_framework.exceptions
import business.constants
class PromoValidator:
def __init__(self, data, instance=None):
self.data = data
self.instance = instance
self.full_data = self._get_full_data()
def _get_full_data(self):
full_data = {}
if self.instance is not None:
full_data.update(
{
'mode': self.instance.mode,
'promo_common': self.instance.promo_common,
'promo_unique': None,
'max_count': self.instance.max_count,
'active_from': self.instance.active_from,
'active_until': self.instance.active_until,
'used_count': self.instance.used_count,
'target': self.instance.target
if self.instance.target
else {},
},
)
full_data.update(self.data)
return full_data
def validate(self):
mode = self.full_data.get('mode')
promo_common = self.full_data.get('promo_common')
promo_unique = self.full_data.get('promo_unique')
max_count = self.full_data.get('max_count')
used_count = self.full_data.get('used_count')
if mode not in [
business.constants.PROMO_MODE_COMMON,
business.constants.PROMO_MODE_UNIQUE,
]:
raise rest_framework.exceptions.ValidationError(
{'mode': 'Invalid mode.'},
)
if used_count and used_count > max_count:
raise rest_framework.exceptions.ValidationError(
{'mode': 'Invalid max_count.'},
)
if mode == business.constants.PROMO_MODE_COMMON:
if not promo_common:
raise rest_framework.exceptions.ValidationError(
{
'promo_common': (
'This field is required for COMMON mode.'
),
},
)
if promo_unique is not None:
raise rest_framework.exceptions.ValidationError(
{
'promo_unique': (
'This field is not allowed for COMMON mode.'
),
},
)
if max_count is None or not (
business.constants.PROMO_COMMON_MIN_COUNT
<= max_count
<= business.constants.PROMO_COMMON_MAX_COUNT
):
raise rest_framework.exceptions.ValidationError(
{
'max_count': (
'Must be between 0 and 100,000,000 '
'for COMMON mode.'
),
},
)
elif mode == business.constants.PROMO_MODE_UNIQUE:
if promo_common is not None:
raise rest_framework.exceptions.ValidationError(
{
'promo_common': (
'This field is not allowed for UNIQUE mode.'
),
},
)
if max_count != business.constants.PROMO_UNIQUE_MAX_COUNT:
raise rest_framework.exceptions.ValidationError(
{'max_count': 'Must be 1 for UNIQUE mode.'},
)
return self.full_data