-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializers.py
More file actions
399 lines (343 loc) · 12.7 KB
/
serializers.py
File metadata and controls
399 lines (343 loc) · 12.7 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import django.contrib.auth.password_validation
import pycountry
import rest_framework.exceptions
import rest_framework.serializers
import business.constants
import business.models
import user.constants
import user.models
class BaseLimitOffsetPaginationSerializer(
rest_framework.serializers.Serializer,
):
"""
Base serializer for common filtering and sorting parameters.
Pagination parameters (limit, offset) are handled by the pagination class.
"""
limit = rest_framework.serializers.IntegerField(
min_value=0,
required=False,
)
offset = rest_framework.serializers.IntegerField(
min_value=0,
required=False,
)
def validate(self, attrs):
errors = {}
for field in ('limit', 'offset'):
raw = self.initial_data.get(field, None)
if raw == '':
errors[field] = ['This field cannot be an empty string.']
if errors:
raise rest_framework.exceptions.ValidationError(errors)
return super().validate(attrs)
class CountryField(rest_framework.serializers.CharField):
"""
Custom field for validating country codes according to ISO 3166-1 alpha-2.
"""
def __init__(self, **kwargs):
kwargs['allow_blank'] = False
kwargs['min_length'] = business.constants.TARGET_COUNTRY_CODE_LENGTH
kwargs['max_length'] = business.constants.TARGET_COUNTRY_CODE_LENGTH
super().__init__(**kwargs)
def to_internal_value(self, data):
code = super().to_internal_value(data)
try:
pycountry.countries.lookup(code.upper())
except LookupError:
raise rest_framework.serializers.ValidationError(
'Invalid ISO 3166-1 alpha-2 country code.',
)
return code
class TargetSerializer(rest_framework.serializers.Serializer):
age_from = rest_framework.serializers.IntegerField(
min_value=business.constants.TARGET_AGE_MIN,
max_value=business.constants.TARGET_AGE_MAX,
required=False,
)
age_until = rest_framework.serializers.IntegerField(
min_value=business.constants.TARGET_AGE_MIN,
max_value=business.constants.TARGET_AGE_MAX,
required=False,
)
country = CountryField(required=False)
categories = rest_framework.serializers.ListField(
child=rest_framework.serializers.CharField(
min_length=business.constants.TARGET_CATEGORY_MIN_LENGTH,
max_length=business.constants.TARGET_CATEGORY_MAX_LENGTH,
allow_blank=False,
),
max_length=business.constants.TARGET_CATEGORY_MAX_ITEMS,
required=False,
allow_empty=True,
)
def validate(self, data):
age_from = data.get('age_from')
age_until = data.get('age_until')
if (
age_from is not None
and age_until is not None
and age_from > age_until
):
raise rest_framework.serializers.ValidationError(
{'age_until': 'Must be greater than or equal to age_from.'},
)
return data
class BaseCompanyPromoSerializer(rest_framework.serializers.ModelSerializer):
"""
Base serializer for promo, containing validation and representation logic.
"""
image_url = rest_framework.serializers.URLField(
required=False,
allow_blank=False,
max_length=business.constants.PROMO_IMAGE_URL_MAX_LENGTH,
)
description = rest_framework.serializers.CharField(
min_length=business.constants.PROMO_DESC_MIN_LENGTH,
max_length=business.constants.PROMO_DESC_MAX_LENGTH,
required=True,
)
target = TargetSerializer(
required=True,
allow_null=True,
)
promo_common = rest_framework.serializers.CharField(
min_length=business.constants.PROMO_COMMON_CODE_MIN_LENGTH,
max_length=business.constants.PROMO_COMMON_CODE_MAX_LENGTH,
required=False,
allow_null=True,
allow_blank=False,
)
promo_unique = rest_framework.serializers.ListField(
child=rest_framework.serializers.CharField(
min_length=business.constants.PROMO_UNIQUE_CODE_MIN_LENGTH,
max_length=business.constants.PROMO_UNIQUE_CODE_MAX_LENGTH,
allow_blank=False,
),
min_length=business.constants.PROMO_UNIQUE_LIST_MIN_ITEMS,
max_length=business.constants.PROMO_UNIQUE_LIST_MAX_ITEMS,
required=False,
allow_null=True,
)
class Meta:
model = business.models.Promo
fields = (
'description',
'image_url',
'target',
'max_count',
'active_from',
'active_until',
'mode',
'promo_common',
'promo_unique',
)
def validate(self, data):
"""
Main validation method.
Determines the mode and calls the corresponding validation method.
"""
mode = data.get('mode', getattr(self.instance, 'mode', None))
if mode == business.constants.PROMO_MODE_COMMON:
self._validate_common(data)
else:
self._validate_unique(data)
return data
def _validate_common(self, data):
"""
Validations for COMMON promo mode.
"""
if 'promo_unique' in data and data['promo_unique'] is not None:
raise rest_framework.serializers.ValidationError(
{'promo_unique': 'This field is not allowed for COMMON mode.'},
)
if self.instance is None and not data.get('promo_common'):
raise rest_framework.serializers.ValidationError(
{'promo_common': 'This field is required for COMMON mode.'},
)
new_max_count = data.get('max_count')
if self.instance and new_max_count is not None:
used_count = self.instance.get_used_codes_count
if used_count > new_max_count:
raise rest_framework.serializers.ValidationError(
{
'max_count': (
f'max_count ({new_max_count}) cannot be less than '
f'used_count ({used_count}).'
),
},
)
effective_max_count = (
new_max_count
if new_max_count is not None
else getattr(self.instance, 'max_count', None)
)
min_c = business.constants.PROMO_COMMON_MIN_COUNT
max_c = business.constants.PROMO_COMMON_MAX_COUNT
if effective_max_count is not None and not (
min_c <= effective_max_count <= max_c
):
raise rest_framework.serializers.ValidationError(
{
'max_count': (
f'Must be between {min_c} and {max_c} for COMMON mode.'
),
},
)
def _validate_unique(self, data):
"""
Validations for UNIQUE promo mode.
"""
if 'promo_common' in data and data['promo_common'] is not None:
raise rest_framework.serializers.ValidationError(
{'promo_common': 'This field is not allowed for UNIQUE mode.'},
)
if self.instance is None and not data.get('promo_unique'):
raise rest_framework.serializers.ValidationError(
{'promo_unique': 'This field is required for UNIQUE mode.'},
)
effective_max_count = data.get(
'max_count',
getattr(self.instance, 'max_count', None),
)
if (
effective_max_count is not None
and effective_max_count
!= business.constants.PROMO_UNIQUE_MAX_COUNT
):
raise rest_framework.serializers.ValidationError(
{
'max_count': (
'Must be equal to '
f'{business.constants.PROMO_UNIQUE_MAX_COUNT} '
'for UNIQUE mode.'
),
},
)
def to_representation(self, instance):
"""
Controls the display of fields in the response.
"""
data = super().to_representation(instance)
if not instance.image_url:
data.pop('image_url', None)
if instance.mode == business.constants.PROMO_MODE_UNIQUE:
data.pop('promo_common', None)
if 'promo_unique' in self.fields and isinstance(
self.fields['promo_unique'],
rest_framework.serializers.SerializerMethodField,
):
data['promo_unique'] = self.get_promo_unique(instance)
else:
data['promo_unique'] = [
code.code for code in instance.unique_codes.all()
]
else:
data.pop('promo_unique', None)
return data
class OtherFieldSerializer(rest_framework.serializers.Serializer):
age = rest_framework.serializers.IntegerField(
required=True,
min_value=user.constants.AGE_MIN,
max_value=user.constants.AGE_MAX,
)
country = CountryField(required=True)
class BaseUserSerializer(rest_framework.serializers.ModelSerializer):
password = rest_framework.serializers.CharField(
write_only=True,
required=True,
validators=[django.contrib.auth.password_validation.validate_password],
max_length=user.constants.PASSWORD_MAX_LENGTH,
min_length=user.constants.PASSWORD_MIN_LENGTH,
style={'input_type': 'password'},
)
name = rest_framework.serializers.CharField(
required=True,
min_length=user.constants.NAME_MIN_LENGTH,
max_length=user.constants.NAME_MAX_LENGTH,
)
surname = rest_framework.serializers.CharField(
required=True,
min_length=user.constants.SURNAME_MIN_LENGTH,
max_length=user.constants.SURNAME_MAX_LENGTH,
)
email = rest_framework.serializers.EmailField(
required=True,
min_length=user.constants.EMAIL_MIN_LENGTH,
max_length=user.constants.EMAIL_MAX_LENGTH,
)
avatar_url = rest_framework.serializers.URLField(
required=False,
max_length=user.constants.AVATAR_URL_MAX_LENGTH,
allow_null=True,
)
other = OtherFieldSerializer(required=True)
class Meta:
model = user.models.User
fields = (
'name',
'surname',
'email',
'password',
'avatar_url',
'other',
)
class BaseUserPromoSerializer(rest_framework.serializers.ModelSerializer):
"""
Base serializer for promos, containing common fields and methods.
"""
promo_id = rest_framework.serializers.UUIDField(source='id')
company_id = rest_framework.serializers.UUIDField(source='company.id')
company_name = rest_framework.serializers.CharField(source='company.name')
active = rest_framework.serializers.BooleanField(source='is_active')
like_count = rest_framework.serializers.IntegerField(
source='get_like_count',
)
comment_count = rest_framework.serializers.IntegerField(
source='get_comment_count',
)
is_liked_by_user = rest_framework.serializers.SerializerMethodField()
is_activated_by_user = rest_framework.serializers.SerializerMethodField()
class Meta:
model = business.models.Promo
fields = (
'promo_id',
'company_id',
'company_name',
'description',
'image_url',
'active',
'is_activated_by_user',
'like_count',
'comment_count',
'is_liked_by_user',
)
read_only_fields = fields
def get_is_liked_by_user(self, obj: business.models.Promo) -> bool:
"""
Checks whether the current user has liked this promo.
"""
request = self.context['request']
return user.models.PromoLike.objects.filter(
promo=obj,
user=request.user,
).exists()
def get_is_activated_by_user(self, obj: business.models.Promo) -> bool:
"""
Checks whether the current user has activated this promo code.
"""
request = self.context.get('request')
return user.models.PromoActivationHistory.objects.filter(
promo=obj,
user=request.user,
).exists()
class BaseCommentSerializer(rest_framework.serializers.ModelSerializer):
"""
Base serializer for promo comments.
"""
text = rest_framework.serializers.CharField(
min_length=user.constants.COMMENT_TEXT_MIN_LENGTH,
max_length=user.constants.COMMENT_TEXT_MAX_LENGTH,
)
class Meta:
model = user.models.PromoComment
fields = ('text',)