-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathserializers.py
More file actions
1717 lines (1477 loc) · 71.4 KB
/
Copy pathserializers.py
File metadata and controls
1717 lines (1477 loc) · 71.4 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from decimal import Decimal
from typing import Any, Dict, List, Optional
import random
import string
from rest_framework import serializers
from django.db import connection, transaction
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from BaseBillet.models import Event, PostalAddress, Tag, OptionGenerale, LigneArticle, Price, PriceSold, Product, ProductFormField, Reservation, Membership
from crowds.models import Initiative, BudgetItem, Participation
from fedow_connect.utils import dround
from Administration.utils import clean_html
# Image validation utilities
from PIL import Image, UnidentifiedImageError
def _url_absolue_du_media(chemin_du_media):
"""
Transforme un chemin de media en URL ABSOLUE sur le domaine du tenant courant.
/ Turn a media path into an ABSOLUTE URL on the current tenant's domain.
LOCALISATION : api_v2/serializers.py
"/media/images/concert.jpg" -> "https://mon-lieu.tibillet.coop/media/images/concert.jpg"
POURQUOI : `FieldFile.url` renvoie un chemin RELATIF. Pour un client d'API externe —
un site tiers, une newsletter, une appli mobile — c'est inexploitable : il ne peut pas
deviner sur quel domaine le resoudre. On prefixe donc par le domaine primaire du tenant.
/ WHY: FieldFile.url returns a RELATIVE path, unusable by an external API client.
On passe par connection.tenant (et non par la requete HTTP) pour que ca marche aussi
hors contexte web : tache Celery, management command, generation de newsletter.
/ We use connection.tenant, not the HTTP request, so it also works outside a web
context: Celery task, management command, newsletter generation.
:param chemin_du_media: le chemin renvoye par FieldFile.url, ex "/media/images/x.jpg"
:return: l'URL absolue, ou le chemin d'origine si le tenant n'a pas de domaine
"""
if not chemin_du_media:
return None
# Deja absolue (stockage S3, CDN...) : on n'y touche pas.
# / Already absolute (S3, CDN...): leave it alone.
if chemin_du_media.startswith("http://") or chemin_du_media.startswith("https://"):
return chemin_du_media
domaine_primaire = connection.tenant.get_primary_domain()
if not domaine_primaire:
# Tenant sans domaine primaire : on degrade proprement plutot que de planter.
# / Tenant with no primary domain: degrade gracefully instead of crashing.
return chemin_du_media
return f"https://{domaine_primaire.domain}{chemin_du_media}"
def _validate_uploaded_image(file_obj):
"""Strictly validate that the uploaded object is an image and <= 10 MiB.
- checks declared content_type when available
- checks file size (<= 10 * 1024 * 1024 bytes)
- attempts to open via Pillow
- resets file pointer afterwards
"""
MAX_BYTES = 10 * 1024 * 1024 # 10 MiB
# Some storages/adapters set content_type, some don't (e.g., tests)
content_type = getattr(file_obj, 'content_type', None)
if content_type and not str(content_type).lower().startswith('image/'):
raise serializers.ValidationError('Only image files are allowed (image/*).')
# Check size from UploadedFile when available
size = getattr(file_obj, 'size', None)
if size is None:
# try to derive size from stream if possible without consuming
try:
if hasattr(file_obj, 'seek') and hasattr(file_obj, 'tell'):
pos = file_obj.tell()
file_obj.seek(0, 2) # seek to end
end = file_obj.tell()
file_obj.seek(pos)
size = end
except Exception:
size = None
if size is not None and int(size) > MAX_BYTES:
raise serializers.ValidationError('Image exceeds maximum size of 10 MiB.')
# Verify with Pillow
pos = None
try:
if hasattr(file_obj, 'tell'):
pos = file_obj.tell()
Image.open(file_obj).verify() # type: ignore
except (UnidentifiedImageError, OSError):
raise serializers.ValidationError('Invalid image file.')
finally:
try:
if hasattr(file_obj, 'seek') and pos is not None:
file_obj.seek(pos)
except Exception:
pass
class PostalAddressAsSchemaSerializer(serializers.ModelSerializer):
class Meta:
model = PostalAddress
fields = (
"name",
"street_address",
"address_locality",
"address_region",
"postal_code",
"address_country",
"latitude",
"longitude",
)
def _image_urls(self, instance: PostalAddress) -> List[str]:
"""
Les images du lieu, en URL ABSOLUE.
/ The venue's images, as ABSOLUTE URLs.
Meme correction que pour Event : `FieldFile.url` renvoie un chemin RELATIF,
inexploitable par un client d'API externe. Voir _url_absolue_du_media.
/ Same fix as for Event: FieldFile.url returns a RELATIVE path.
"""
urls: List[str] = []
try:
if instance.img:
urls.append(_url_absolue_du_media(instance.img.url))
except Exception:
pass
try:
if instance.sticker_img:
urls.append(_url_absolue_du_media(instance.sticker_img.url))
except Exception:
pass
return [url for url in urls if url]
def to_representation(self, instance: PostalAddress) -> Dict[str, Any]:
data = super().to_representation(instance)
# Map to schema.org/PostalAddress
result: Dict[str, Any] = {
"@type": "PostalAddress",
"name": data.get("name"),
"streetAddress": data.get("street_address"),
"addressLocality": data.get("address_locality"),
"addressRegion": data.get("address_region"),
"postalCode": data.get("postal_code"),
"addressCountry": data.get("address_country"),
}
# Add geo if present
lat = data.get("latitude")
lon = data.get("longitude")
if lat is not None and lon is not None:
result["geo"] = {
"@type": "GeoCoordinates",
"latitude": float(lat),
"longitude": float(lon),
}
# Add image URLs if available
images = self._image_urls(instance)
if images:
result["image"] = images
return result
# Mapping between internal category codes and schema.org Event subtypes
CATEGORY_TO_SCHEMA_TYPE = {
Event.CONCERT: "MusicEvent",
Event.FESTIVAL: "Festival",
Event.REUNION: "SocialEvent",
Event.CONFERENCE: "EducationEvent",
Event.RESTAURATION: "FoodEvent",
Event.CHANTIER: "Event", # no precise subtype, keep generic
Event.ACTION: "Event", # action slot; modeled as Event + superEvent
}
SCHEMA_TYPE_TO_CATEGORY = {
"musicevent": Event.CONCERT,
"festival": Event.FESTIVAL,
"socialevent": Event.REUNION,
"educationevent": Event.CONFERENCE,
"foodevent": Event.RESTAURATION,
"event": Event.CHANTIER, # default mapping to generic
}
# Build a normalized mapping from translated display label -> internal code
# so that clients may pass additionalType with the human-readable label.
def _display_norm(s):
return str(s).strip().lower() if s is not None else ""
DISPLAY_TO_CATEGORY = { _display_norm(lbl): code for code, lbl in Event.TYPE_CHOICES }
class EventSchemaSerializer(serializers.ModelSerializer):
postal_address = PostalAddressAsSchemaSerializer(read_only=True)
class Meta:
model = Event
fields = (
"uuid",
"name",
"short_description",
"long_description",
"datetime",
"end_datetime",
"full_url",
"postal_address",
)
def _image_urls(self, instance: Event) -> List[str]:
"""
Les images de l'evenement, en URL ABSOLUE, avec le fallback du moteur.
/ The event's images, as ABSOLUTE URLs, with the engine's fallback.
LOCALISATION : api_v2/serializers.py
DEUX CORRECTIONS PAR RAPPORT A L'ANCIEN COMPORTEMENT :
1. On passe par `instance.get_img()`, et non `instance.img` brut. C'est la methode
qu'utilise le moteur d'evenements du site : elle retombe sur l'image du LIEU,
puis sur celle de la CONFIGURATION du tenant. Un evenement sans image propre a
donc une image sur le site — il en a maintenant une dans l'API aussi.
2. Les URLs sont ABSOLUES. `instance.img.url` renvoie "/media/images/x.jpg" : un
client d'API externe ne peut pas savoir sur quel domaine le resoudre. On prefixe
par le domaine primaire du tenant.
/ 1. Use get_img() (venue then tenant-config fallback), like the site's event engine.
/ 2. Return ABSOLUTE URLs: a relative "/media/..." is unusable for an API client.
"""
urls: List[str] = []
# L'image principale, avec le fallback lieu -> configuration.
# / The main image, with the venue -> config fallback.
try:
image_principale = instance.get_img()
if image_principale:
urls.append(_url_absolue_du_media(image_principale.url))
except Exception:
pass
# La vignette d'agenda : pas de fallback, elle est facultative par nature.
# / The agenda thumbnail: no fallback, it is optional by design.
try:
if instance.sticker_img:
urls.append(_url_absolue_du_media(instance.sticker_img.url))
except Exception:
pass
return [url for url in urls if url]
def _additional_properties(self, instance: Event) -> List[Dict[str, Any]]:
props: List[Dict[str, Any]] = []
# optionsRadio
radio_values = list(instance.options_radio.values_list("name", flat=True)) if hasattr(instance, "options_radio") else []
if radio_values:
props.append({
"@type": "PropertyValue",
"name": "optionsRadio",
"value": radio_values,
})
# optionsCheckbox
checkbox_values = list(instance.options_checkbox.values_list("name", flat=True)) if hasattr(instance, "options_checkbox") else []
if checkbox_values:
props.append({
"@type": "PropertyValue",
"name": "optionsCheckbox",
"value": checkbox_values,
})
# custom confirmation message
if getattr(instance, "custom_confirmation_message", None):
props.append({
"@type": "PropertyValue",
"name": "customConfirmationMessage",
"value": instance.custom_confirmation_message,
})
return props
def to_representation(self, instance: Event) -> Dict[str, Any]:
data = super().to_representation(instance)
# Choose the best description
description = data.get("long_description") or data.get("short_description")
# Build schema.org JSON-LD for Event
# Determine schema.org subtype from internal category
schema_type = CATEGORY_TO_SCHEMA_TYPE.get(getattr(instance, "categorie", None), "Event")
payload: Dict[str, Any] = {
"@context": "https://schema.org",
"@type": schema_type,
# expose semantic additionalType with the human-readable category label
"additionalType": getattr(instance, "get_categorie_display")() if hasattr(instance, "get_categorie_display") else None,
"identifier": str(data.get("uuid")) if data.get("uuid") else None,
"name": data.get("name"),
"description": description,
"disambiguatingDescription": data.get("short_description") or None,
"startDate": data.get("datetime"),
"endDate": data.get("end_datetime"),
# location may be a Place with address
"location": None,
"url": data.get("full_url"),
# parent event (schema.org: superEvent)
"superEvent": ({
"@type": "Event",
"identifier": str(getattr(instance.parent, "uuid", "")),
"name": getattr(instance.parent, "name", None),
} if getattr(instance, "parent", None) else None),
# extra mapped fields
"maximumAttendeeCapacity": getattr(instance, "jauge_max", None),
"image": self._image_urls(instance) or None,
"sameAs": data.get("full_url") if getattr(instance, "is_external", False) else None,
"eventStatus": "https://schema.org/EventScheduled" if getattr(instance, "published", True) else "https://schema.org/EventCancelled",
"audience": {"@type": "Audience", "audienceType": "private"} if getattr(instance, "private", False) else None,
"keywords": list(instance.tag.values_list("name", flat=True)) if hasattr(instance, "tag") else None,
"offers": {
"@type": "Offer",
"eligibleQuantity": {
"@type": "QuantitativeValue",
"maxValue": getattr(instance, "max_per_user", None),
},
"returnPolicy": {
"@type": "MerchantReturnPolicy",
"merchantReturnDays": getattr(instance, "refund_deadline", None),
},
},
"additionalProperty": self._additional_properties(instance) or None,
}
# Map location if available
address = data.get("postal_address")
if address:
payload["location"] = {
"@type": "Place",
"address": address,
}
# Remove nulls for cleanliness (and clean nested offers if empty)
clean_payload = {k: v for k, v in payload.items() if v not in (None, "", [])}
# Clean offers substructure if all values are None
offers = clean_payload.get("offers")
if isinstance(offers, dict):
# prune None in eligibleQuantity
if isinstance(offers.get("eligibleQuantity"), dict):
if offers["eligibleQuantity"].get("maxValue") in (None, ""):
offers.pop("eligibleQuantity", None)
# prune returnPolicy if days None
if isinstance(offers.get("returnPolicy"), dict):
if offers["returnPolicy"].get("merchantReturnDays") in (None, ""):
offers.pop("returnPolicy", None)
if not offers:
clean_payload.pop("offers", None)
return clean_payload
class EventCreateSerializer(serializers.Serializer):
"""
schema.org/Event input serializer for creation (semantic fields only) + semantic @type mapping and optional 'superEvent'.
Accepted (schema.org) fields:
- name: Text (required)
- startDate: DateTime (required)
- endDate: DateTime (optional)
- url: URL (optional)
- sameAs: URL (optional; canonical external URL)
- maximumAttendeeCapacity: Integer (maps to jauge_max)
- disambiguatingDescription: Text (maps to short_description)
- description: Text (maps to long_description)
- eventStatus: URL or Text (e.g. https://schema.org/EventScheduled)
- audience: { "@type": "Audience", "audienceType": "private"|"public" }
- keywords: [Text, ...] (tags)
- image: [URL or ImageObject] (ignored on create for now)
- offers: {
"eligibleQuantity": {"maxValue": int},
"returnPolicy": {"merchantReturnDays": int}
}
- additionalProperty: [
{"name":"optionsRadio","value":["OptionName", ...]},
{"name":"optionsCheckbox","value":["OptionName", ...]},
{"name":"customConfirmationMessage","value":"..."}
]
"""
# Core fields
name = serializers.CharField(max_length=200)
startDate = serializers.DateTimeField()
endDate = serializers.DateTimeField(required=False, allow_null=True)
# Optional parent (schema.org superEvent) — UUID string; required if mapped category is ACTION
superEvent = serializers.CharField(required=False, allow_blank=True, allow_null=True)
# Simple mappings
url = serializers.URLField(required=False, allow_blank=True, allow_null=True)
sameAs = serializers.URLField(required=False, allow_blank=True, allow_null=True)
maximumAttendeeCapacity = serializers.IntegerField(required=False, allow_null=True)
disambiguatingDescription = serializers.CharField(required=False, allow_blank=True, allow_null=True)
description = serializers.CharField(required=False, allow_blank=True, allow_null=True)
eventStatus = serializers.CharField(required=False, allow_blank=True, allow_null=True)
audience = serializers.DictField(required=False)
keywords = serializers.ListField(child=serializers.CharField(), required=False)
# Nested structures
image = serializers.ListField(child=serializers.CharField(), required=False)
offers = serializers.DictField(required=False)
additionalProperty = serializers.ListField(child=serializers.DictField(), required=False)
# Semantic category display label (schema.org/Thing.additionalType)
additionalType = serializers.CharField(required=False, allow_blank=True, allow_null=True)
def validate(self, attrs: Dict[str, Any]) -> Dict[str, Any]:
# Strictly validate uploaded images if present in request.FILES
req = self.context.get("request") if hasattr(self, 'context') else None
if req is not None and hasattr(req, 'FILES'):
for fname in ("img", "sticker_img"):
f = req.FILES.get(fname)
if f:
_validate_uploaded_image(f)
return attrs
def create(self, validated_data: Dict[str, Any]) -> Event:
# Extract top-level fields
name: str = validated_data["name"]
start = validated_data["startDate"]
end = validated_data.get("endDate")
url = validated_data.get("url")
same_as = validated_data.get("sameAs")
max_cap = validated_data.get("maximumAttendeeCapacity")
short_desc = validated_data.get("disambiguatingDescription")
long_desc = validated_data.get("description")
# Determine internal category code from semantic @type
requested_type = (self.initial_data.get("@type") or "Event").strip()
cat_code = SCHEMA_TYPE_TO_CATEGORY.get(requested_type.lower(), Event.CHANTIER)
# Allow clients to explicitly set a human-readable category via additionalType (display label)
addl_type_label = validated_data.get("additionalType")
if addl_type_label:
mapped = DISPLAY_TO_CATEGORY.get(str(addl_type_label).strip().lower())
if mapped:
cat_code = mapped
super_event_uuid = validated_data.get("superEvent")
event_status = (validated_data.get("eventStatus") or "").lower() if validated_data.get("eventStatus") else None
audience = validated_data.get("audience") or {}
keywords: List[str] = validated_data.get("keywords") or []
offers = validated_data.get("offers") or {}
add_props: List[Dict[str, Any]] = validated_data.get("additionalProperty") or []
# eventStatus → published
published = True
if event_status:
if "eventscheduled" in event_status:
published = True
elif "eventcancelled" in event_status:
published = False
else:
# default to True if unrecognized
published = True
# audience → private
private = False
try:
aud_type = (audience.get("audienceType") or "").lower()
private = aud_type == "private"
except Exception:
private = False
# offers mapping
max_per_user: Optional[int] = None
refund_days: Optional[int] = None
try:
elig = offers.get("eligibleQuantity") or {}
max_per_user = elig.get("maxValue")
except Exception:
pass
try:
ret = offers.get("returnPolicy") or {}
refund_days = ret.get("merchantReturnDays")
except Exception:
pass
# full_url / external
full_url = same_as or url
is_external = bool(same_as)
# Validate category & parent (semantic rule: ACTION requires superEvent)
parent_obj = None
# If superEvent provided with generic Event, we treat it as ACTION
if super_event_uuid and cat_code == Event.CHANTIER and requested_type.lower() in ("event", "socialevent"):
cat_code = Event.ACTION
if cat_code == Event.ACTION and not super_event_uuid:
raise serializers.ValidationError({"superEvent": "Ce champ est requis quand la catégorie est ACTION."})
if super_event_uuid:
try:
parent_obj = Event.objects.get(uuid=super_event_uuid)
except Event.DoesNotExist:
raise serializers.ValidationError({"superEvent": "Evènement parent introuvable."})
# Generate a unique slug from name to avoid unique constraint violations on repeated tests
base_slug = slugify(name) or "event"
slug_value = base_slug
# If collision, append a short random suffix
while Event.objects.filter(slug=slug_value).exists():
suffix = "-" + "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
slug_value = f"{base_slug}{suffix}"
# Create Event
create_kwargs = {
"name": name,
"slug": slug_value,
"datetime": start,
"end_datetime": end,
"full_url": full_url,
"is_external": is_external,
"short_description": short_desc,
"long_description": long_desc,
"published": published,
"archived": False,
"private": private,
"categorie": cat_code,
"parent": parent_obj,
}
if max_cap is not None:
create_kwargs["jauge_max"] = max_cap
if max_per_user is not None:
create_kwargs["max_per_user"] = max_per_user
if refund_days is not None:
create_kwargs["refund_deadline"] = refund_days
event = Event.objects.create(**create_kwargs)
# keywords → tags
if keywords:
for tag_name in keywords:
if not tag_name:
continue
tag_obj, _ = Tag.objects.get_or_create(name=str(tag_name).strip())
event.tag.add(tag_obj)
# additionalProperty → options & custom message
def _extract_values(prop_name: str) -> List[str]:
for p in add_props:
if str(p.get("name")).lower() == prop_name.lower():
v = p.get("value")
if isinstance(v, list):
return [str(x) for x in v]
if isinstance(v, str):
return [v]
return []
radio_names = _extract_values("optionsRadio")
if radio_names:
for opt_name in radio_names:
try:
opt = OptionGenerale.objects.get(name=opt_name)
except OptionGenerale.DoesNotExist:
# Create missing options to keep API v2 setup simple
# Cree l'option si elle n'existe pas (FALC)
opt = OptionGenerale.objects.create(name=opt_name)
event.options_radio.add(opt)
checkbox_names = _extract_values("optionsCheckbox")
if checkbox_names:
for opt_name in checkbox_names:
try:
opt = OptionGenerale.objects.get(name=opt_name)
except OptionGenerale.DoesNotExist:
# Create missing options to keep API v2 setup simple
# Cree l'option si elle n'existe pas (FALC)
opt = OptionGenerale.objects.create(name=opt_name)
event.options_checkbox.add(opt)
# customConfirmationMessage
for p in add_props:
if str(p.get("name")).lower() == "customconfirmationmessage":
val = p.get("value")
if isinstance(val, str) and val.strip():
event.custom_confirmation_message = val.strip()
event.save(update_fields=["custom_confirmation_message"])
break
return event
class PostalAddressCreateSerializer(serializers.Serializer):
"""
schema.org/PostalAddress input serializer for creation.
Accepted fields (schema.org names):
- name (optional, Text) → internal name helper
- streetAddress (required, Text)
- addressLocality (required, Text)
- addressRegion (optional, Text)
- postalCode (required, Text)
- addressCountry (required, Text)
- geo (optional) { "latitude": number, "longitude": number }
"""
# Optional label for quick finding later (maps to model.name)
name = serializers.CharField(required=False, allow_blank=True, allow_null=True, max_length=400)
# Required address lines
streetAddress = serializers.CharField()
addressLocality = serializers.CharField()
addressRegion = serializers.CharField(required=False, allow_blank=True, allow_null=True)
postalCode = serializers.CharField()
addressCountry = serializers.CharField()
geo = serializers.DictField(required=False)
def validate(self, attrs: Dict[str, Any]) -> Dict[str, Any]:
# Validate uploaded images if provided via multipart request
req = self.context.get("request") if hasattr(self, 'context') else None
if req is not None and hasattr(req, 'FILES'):
for fname in ("img", "sticker_img"):
f = req.FILES.get(fname)
if f:
_validate_uploaded_image(f)
return attrs
def create(self, validated_data: Dict[str, Any]) -> PostalAddress:
geo = validated_data.pop("geo", {}) or {}
lat = geo.get("latitude")
lon = geo.get("longitude")
return PostalAddress.objects.create(
name=validated_data.get("name") or None,
street_address=validated_data["streetAddress"],
address_locality=validated_data["addressLocality"],
address_region=validated_data.get("addressRegion"),
postal_code=validated_data["postalCode"],
address_country=validated_data["addressCountry"],
latitude=lat,
longitude=lon,
)
class SemanticProductFromSaleLineSerializer(serializers.Serializer):
"""
Sérializer sémantique (schema.org) pour une ligne de vente.
Objectif:
- Prendre les mêmes données métier qu'un `LigneArticleSerializer` (même instance source),
mais produire une représentation sémantique lisible par humains et machines.
- Sortie au format schema.org avec `@type: Product`.
Remarques FALC (Facile À Lire et à Comprendre):
- On décrit le produit de la ligne (Product) avec ses infos principales.
- On ajoute une offre (Offer) avec le prix unitaire et la devise.
- On inclut des infos utiles en plus (TVA, quantité, UUID de la ligne) dans `additionalProperty`.
- Cette classe n'altère pas la donnée en base; elle ne fait que formater la réponse.
"""
# Ce Serializer est « read-only » et reconstruit un dict sémantique depuis l'instance
def _absolute_url(self, relative_url: str) -> str:
request = self.context.get('request')
if request and relative_url:
try:
return request.build_absolute_uri(relative_url)
except Exception:
return relative_url
return relative_url
def to_representation(self, instance: LigneArticle) -> Dict[str, Any]:
# Sécurise les accès aux relations
productsold: PriceSold | None = getattr(instance, 'pricesold', None)
product: Product | None = None
if productsold and getattr(productsold, 'productsold', None):
product = productsold.productsold.product
# Nom et descriptions
name = product.name if (product and product.name) else _('Product')
short_desc = getattr(product, 'short_description', None) if product else None
long_desc = getattr(product, 'long_description', None) if product else None
description = long_desc or short_desc
# Image (si présente)
image_url = None
if product and getattr(product, 'img', None):
try:
# Tente d'utiliser une variante raisonnable si dispo
if hasattr(product.img, 'med') and hasattr(product.img.med, 'url'):
image_url = self._absolute_url(product.img.med.url)
elif hasattr(product.img, 'url'):
image_url = self._absolute_url(product.img.url)
except Exception:
image_url = None
# Prix unitaire TTC (à partir de LigneArticle.amount en centimes)
price_unit_eur = None
if instance.amount is not None:
try:
price_unit_eur = str(Decimal(instance.amount) / Decimal('100'))
except Exception:
price_unit_eur = None
# Catégorie (affichage lisible si disponible)
category = None
if product and hasattr(product, 'get_categorie_article_display'):
try:
category = product.get_categorie_article_display()
except Exception:
category = None
# Identifiants
sku = str(product.uuid) if product else None
product_id = str(product.uuid) if product else None
# Offre schema.org (simplifiée)
offers = None
if price_unit_eur is not None:
offers = {
"@type": "Offer",
# Prix TTC unitaire au moment de la vente
"price": price_unit_eur,
"priceCurrency": "EUR",
}
# Propriétés additionnelles utiles (claires et FALC)
additional_property = [
{
"@type": "PropertyValue",
"name": "sale_line_uuid",
"value": str(instance.uuid),
"description": "Identifiant unique de la ligne de vente",
},
{
"@type": "PropertyValue",
"name": "quantity",
"value": str(instance.qty),
"description": "Quantité vendue",
},
{
"@type": "PropertyValue",
"name": "vat",
"value": str(instance.vat),
"description": "TVA appliquée en pourcentage",
},
]
if getattr(instance, 'payment_method', None):
additional_property.append({
"@type": "PropertyValue",
"name": "payment_method",
"value": instance.payment_method,
"description": "Méthode de paiement",
})
if getattr(instance, 'status', None):
additional_property.append({
"@type": "PropertyValue",
"name": "status",
"value": instance.status,
"description": "Statut de la ligne",
})
# Construction finale schema.org/Product
data: Dict[str, Any] = {
"@context": "https://schema.org",
"@type": "Product",
"name": name,
"sku": sku,
"category": category,
"description": description,
"productID": product_id,
"datePublished": instance.datetime.isoformat() if instance.datetime else None,
"offers": offers,
# Informations complémentaires simples et utiles
"additionalProperty": additional_property,
}
if image_url:
data["image"] = image_url
return data
class ProductSchemaSerializer(serializers.Serializer):
"""
schema.org/Product output serializer for API v2 product resources.
Sortie schema.org/Product pour les produits API v2.
"""
def to_representation(self, instance: Product) -> Dict[str, Any]:
description = instance.long_description or instance.short_description
category = instance.get_categorie_article_display() if hasattr(instance, "get_categorie_article_display") else None
offers: List[Dict[str, Any]] = []
for price in instance.prices.all().order_by("order"):
offer: Dict[str, Any] = {
"@type": "Offer",
"identifier": str(price.uuid),
"name": price.name,
"price": str(price.prix),
"priceCurrency": "EUR",
"freePrice": bool(price.free_price),
}
# Optional semantic helpers
if price.stock is not None:
offer["inventoryLevel"] = {
"@type": "QuantitativeValue",
"value": price.stock,
}
if price.max_per_user is not None:
offer["eligibleQuantity"] = {
"@type": "QuantitativeValue",
"maxValue": price.max_per_user,
}
additional_property = []
if price.recurring_payment:
additional_property.append({
"@type": "PropertyValue",
"name": "recurringPayment",
"value": True,
})
additional_property.append({
"@type": "PropertyValue",
"name": "subscriptionType",
"value": price.subscription_type,
})
adhesion_ids = list(price.adhesions_obligatoires.values_list('pk', flat=True))
if adhesion_ids:
additional_property.append({
"@type": "PropertyValue",
"name": "membershipRequiredProducts",
"value": [str(pk) for pk in adhesion_ids],
})
if price.manual_validation:
additional_property.append({
"@type": "PropertyValue",
"name": "manualValidation",
"value": True,
})
if additional_property:
offer["additionalProperty"] = additional_property
offers.append(offer)
data: Dict[str, Any] = {
"@context": "https://schema.org",
"@type": "Product",
"identifier": str(instance.uuid),
"sku": str(instance.uuid),
"name": instance.name,
"description": description,
"category": category,
"offers": offers,
}
return {k: v for k, v in data.items() if v not in (None, "", [])}
class ProductCreateSerializer(serializers.Serializer):
"""
schema.org/Product input serializer for product creation with prices and form fields.
Serializer simple pour creer un produit, ses tarifs, et son formulaire dynamique.
"""
name = serializers.CharField(max_length=500)
description = serializers.CharField(required=False, allow_blank=True, allow_null=True)
category = serializers.CharField(required=False, allow_blank=True, allow_null=True)
offers = serializers.ListField(child=serializers.DictField(), required=True)
additionalProperty = serializers.ListField(child=serializers.DictField(), required=False)
isRelatedTo = serializers.JSONField(required=False)
def _normalize_category(self, raw: Optional[str]) -> str:
if not raw:
return Product.BILLET
normalized = str(raw).strip().lower()
display_to_code = {
str(label).strip().lower(): code
for code, label in Product.CATEGORIE_ARTICLE_CHOICES
}
synonyms = {
"ticket": Product.BILLET,
"ticket booking": Product.BILLET,
"billet": Product.BILLET,
"free booking": Product.FREERES,
"reservation gratuite": Product.FREERES,
"subscription or membership": Product.ADHESION,
"membership": Product.ADHESION,
"adhesion": Product.ADHESION,
Product.BILLET.lower(): Product.BILLET,
Product.FREERES.lower(): Product.FREERES,
Product.ADHESION.lower(): Product.ADHESION,
}
if normalized in display_to_code:
return display_to_code[normalized]
if normalized in synonyms:
return synonyms[normalized]
raise serializers.ValidationError({"category": "Unknown category. Use a known label or code."})
def _extract_additional_property(self, add_props: List[Dict[str, Any]], key: str) -> Any:
for prop in add_props:
name = str(prop.get("name", "")).strip().lower()
if name == key.lower():
return prop.get("value")
return None
def _extract_one_event_uuid(self, element: Any) -> Optional[str]:
"""
Extrait l'UUID d'un seul element isRelatedTo (string ou objet schema.org).
/ Extract the UUID from a single isRelatedTo element (string or object).
"""
if isinstance(element, str):
valeur = element.strip()
return valeur or None
if isinstance(element, dict):
identifier = element.get("identifier") or element.get("id") or element.get("uuid")
if identifier:
valeur = str(identifier).strip()
return valeur or None
return None
def _extract_event_uuids(self, related: Any, add_props: List[Dict[str, Any]]) -> List[str]:
"""
Retourne la liste des UUID d'evenements a relier au produit.
/ Return the list of event UUIDs to link to the product.
isRelatedTo accepte trois formes :
- une string (un seul event) -> ["uuid"]
- un objet schema.org {identifier: ...} -> ["uuid"]
- une liste de strings et/ou d'objets -> ["uuidA", "uuidB", ...]
En dernier recours, on lit additionalProperty["eventUuid"].
/ isRelatedTo accepts a string, a schema.org object, or a list of both.
Falls back to additionalProperty["eventUuid"].
"""
uuids: List[str] = []
# Cas liste : on parcourt chaque element / List case: iterate each element
if isinstance(related, list):
for element in related:
uuid_trouve = self._extract_one_event_uuid(element)
if uuid_trouve:
uuids.append(uuid_trouve)
# Cas simple : string ou objet unique / Single case: string or object
else:
uuid_trouve = self._extract_one_event_uuid(related)
if uuid_trouve:
uuids.append(uuid_trouve)
# Repli : additionalProperty["eventUuid"] (string unique)
# / Fallback: additionalProperty["eventUuid"] (single string)
if not uuids:
fallback = self._extract_additional_property(add_props, "eventUuid")
if isinstance(fallback, str) and fallback.strip():
uuids.append(fallback.strip())
# Dedoublonnage en gardant l'ordre d'apparition
# / De-duplicate while keeping the order of appearance
uuids_uniques = list(dict.fromkeys(uuids))
return uuids_uniques
def _parse_form_fields(self, add_props: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
raw_fields = self._extract_additional_property(add_props, "formFields")
if raw_fields is None:
return []
if isinstance(raw_fields, dict):
return [raw_fields]
if isinstance(raw_fields, list):
return raw_fields
return []
def _extract_offer_property(self, offer: Dict[str, Any], key: str) -> Any:
# Read from offer.additionalProperty (schema.org PropertyValue list)
add_props = offer.get("additionalProperty") or []
if isinstance(add_props, dict):
add_props = [add_props]
if isinstance(add_props, list):
for prop in add_props:
name = str(prop.get("name", "")).strip().lower()
if name == key.lower():
return prop.get("value")
return None
def create(self, validated_data: Dict[str, Any]) -> Product:
name = validated_data["name"]
description = validated_data.get("description")
category_raw = validated_data.get("category")
offers = validated_data.get("offers") or []
add_props = validated_data.get("additionalProperty") or []
related = validated_data.get("isRelatedTo")
if not offers:
raise serializers.ValidationError({"offers": "At least one offer is required."})
category_code = self._normalize_category(category_raw)
form_fields = self._parse_form_fields(add_props)
field_type_map = {
"shorttext": ProductFormField.FieldType.SHORT_TEXT,
"longtext": ProductFormField.FieldType.LONG_TEXT,
"singleselect": ProductFormField.FieldType.SINGLE_SELECT,