-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
755 lines (632 loc) · 29.5 KB
/
utils.py
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
# ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2024 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
# ##############################################################################
import itertools
import os
import uuid
from collections import defaultdict
from contextlib import suppress
from typing import Dict, Union, Iterable, List
import weasyprint
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import User
from django.core.cache import cache
from django.db import models
from django.db.models import QuerySet, F
from django.shortcuts import resolve_url
from django.utils import timezone
from django.utils.translation import pgettext, override, get_language, gettext
from django_htmx.http import trigger_client_event
from rest_framework.generics import get_object_or_404
from admission.auth.roles.central_manager import CentralManager
from admission.auth.roles.program_manager import ProgramManager as AdmissionProgramManager
from admission.auth.roles.sic_management import SicManagement
from admission.constants import CONTEXT_CONTINUING, CONTEXT_GENERAL, CONTEXT_DOCTORATE
from admission.models import (
ContinuingEducationAdmission,
DoctorateAdmission,
GeneralEducationAdmission,
Scholarship,
)
from admission.ddd.admission.doctorat.preparation.domain.validator.exceptions import (
AnneesCurriculumNonSpecifieesException,
)
from admission.ddd.admission.doctorat.preparation.dtos.curriculum import CurriculumAdmissionDTO
from admission.ddd.admission.doctorat.validation.domain.model.enums import ChoixGenre
from admission.ddd.admission.domain.model.enums.condition_acces import TypeTitreAccesSelectionnable
from admission.ddd.admission.dtos.etudes_secondaires import EtudesSecondairesAdmissionDTO
from admission.ddd.admission.dtos.titre_acces_selectionnable import TitreAccesSelectionnableDTO
from admission.ddd.admission.formation_generale.commands import VerifierCurriculumApresSoumissionQuery
from admission.infrastructure.admission.domain.service.annee_inscription_formation import (
ADMISSION_CONTEXT_BY_OSIS_EDUCATION_TYPE,
)
from backoffice.settings.rest_framework.exception_handler import get_error_data
from base.auth.roles.program_manager import ProgramManager
from base.ddd.utils.business_validator import MultipleBusinessExceptions
from base.forms.utils import EMPTY_CHOICE
from base.models.academic_calendar import AcademicCalendar
from base.models.entity_version import EntityVersion
from base.models.enums.academic_calendar_type import AcademicCalendarTypes
from base.models.enums.education_group_types import TrainingType
from base.models.enums.establishment_type import EstablishmentTypeEnum
from base.models.person import Person
from base.utils.utils import format_academic_year
from ddd.logic.formation_catalogue.commands import GetSigleFormationParenteQuery
from ddd.logic.shared_kernel.profil.dtos.etudes_secondaires import (
DiplomeBelgeEtudesSecondairesDTO,
DiplomeEtrangerEtudesSecondairesDTO,
AlternativeSecondairesDTO,
)
from ddd.logic.shared_kernel.profil.dtos.parcours_externe import (
ExperienceAcademiqueDTO,
ExperienceNonAcademiqueDTO,
)
from ddd.logic.shared_kernel.profil.dtos.parcours_interne import ExperienceParcoursInterneDTO
from osis_common.ddd.interface import BusinessException, QueryRequest
from program_management.ddd.domain.exception import ProgramTreeNotFoundException
from reference.models.country import Country
from reference.models.language import Language
def get_cached_admission_perm_obj(admission_uuid):
qs = DoctorateAdmission.objects.select_related(
'supervision_group',
'candidate',
'training__academic_year',
)
return cache.get_or_set(
'admission_permission_{}'.format(admission_uuid),
lambda: get_object_or_404(qs, uuid=admission_uuid),
)
def get_cached_general_education_admission_perm_obj(admission_uuid):
qs = GeneralEducationAdmission.objects.select_related('candidate', 'training__academic_year')
return cache.get_or_set(
'admission_permission_{}'.format(admission_uuid),
lambda: get_object_or_404(qs, uuid=admission_uuid),
)
def get_cached_continuing_education_admission_perm_obj(admission_uuid):
qs = ContinuingEducationAdmission.objects.select_related('candidate', 'training__academic_year')
return cache.get_or_set(
'admission_permission_{}'.format(admission_uuid),
lambda: get_object_or_404(qs, uuid=admission_uuid),
)
def sort_business_exceptions(exception: BusinessException):
if isinstance(exception, AnneesCurriculumNonSpecifieesException):
return exception.status_code, exception.periode
return getattr(exception, 'status_code', ''), None
def gather_business_exceptions(command: QueryRequest) -> Dict[str, list]:
from infrastructure.messages_bus import message_bus_instance
data = defaultdict(list)
try:
# Trigger the verification command
message_bus_instance.invoke(command)
except MultipleBusinessExceptions as exc:
# Gather all errors for output
sorted_exceptions = sorted(exc.exceptions, key=sort_business_exceptions)
for exception in sorted_exceptions:
data = get_error_data(data, exception, {})
return data
def get_missing_curriculum_periods(proposition_uuid: str):
from infrastructure.messages_bus import message_bus_instance
try:
message_bus_instance.invoke(VerifierCurriculumApresSoumissionQuery(uuid_proposition=proposition_uuid))
return []
except MultipleBusinessExceptions as exc:
return [e.message for e in sorted(exc.exceptions, key=lambda exception: exception.periode[0], reverse=True)]
def takewhile_return_attribute_values(predicate, iterable, attribute):
"""
Make an iterator that returns the values of a specific attribute of elements from the iterable as long as the
predicate is true.
"""
for x in iterable:
if predicate(x):
yield x[attribute]
else:
break
def get_uuid_value(value: str) -> Union[uuid.UUID, str]:
"""Return the uuid value from a string."""
try:
return uuid.UUID(hex=value)
except ValueError:
return value
def force_title(string: str):
"""
Return a string in which all words are lowercase, except for the first letter of each one, which can written in
upper or lower case"""
title_string = list(string.title())
for index, char in enumerate(title_string):
if char.isupper() and string[index].islower():
title_string[index] = string[index]
return ''.join(title_string)
def get_admission_cdd_managers(education_group_id) -> models.QuerySet[Person]:
return Person.objects.filter(
models.Q(
id__in=AdmissionProgramManager.objects.filter(education_group_id=education_group_id).values('person_id')
)
| models.Q(id__in=ProgramManager.objects.filter(education_group_id=education_group_id).values('person_id'))
)
def get_doctoral_cdd_managers(education_group_id) -> QuerySet[Person]:
return Person.objects.filter(
id__in=ProgramManager.objects.filter(education_group_id=education_group_id).values('person_id')
)
def add_messages_into_htmx_response(request, response):
msgs = list(messages.get_messages(request))
if msgs:
trigger_client_event(response, 'messages', [{'message': str(msg.message), 'tags': msg.tags} for msg in msgs])
def add_close_modal_into_htmx_response(response):
trigger_client_event(response, 'closeModal')
def get_portal_admission_list_url() -> str:
"""Return the url of the list of the admissions in the portal."""
return f'{settings.OSIS_PORTAL_URL}admission/'
def get_portal_admission_url(context, admission_uuid) -> str:
"""Return the url of the admission in the portal."""
return settings.ADMISSION_FRONTEND_LINK.format(
context=context,
uuid=admission_uuid,
)
def get_backoffice_admission_url(context, admission_uuid, sub_namespace='', url_suffix='') -> str:
"""Return the url of the admission in the backoffice."""
return '{}{}{}'.format(
settings.ADMISSION_BACKEND_LINK_PREFIX,
resolve_url(f'admission:{context}{sub_namespace}', uuid=admission_uuid),
url_suffix,
)
def person_is_sic(person: Person):
return SicManagement.belong_to(person) or CentralManager.belong_to(person)
def person_is_fac_cdd(person: Person):
return AdmissionProgramManager.belong_to(person)
class WeasyprintStylesheets:
@classmethod
def get_stylesheets(cls):
"""Get the stylesheets needed to generate the pdf"""
# Load the stylesheets once and cache them
if not hasattr(cls, '_stylesheet'):
setattr(
cls,
'_stylesheet',
[
weasyprint.CSS(filename=os.path.join(settings.BASE_DIR, file_path))
for file_path in [
'base/static/css/bootstrap.min.css',
'admission/static/admission/admission.css',
'admission/static/admission/base_pdf.css',
]
],
)
return getattr(cls, '_stylesheet')
@classmethod
def get_stylesheets_bootstrap_5(cls):
"""Get the stylesheets needed to generate the pdf"""
# Load the stylesheets once and cache them
if not hasattr(cls, '_stylesheet_bs5'):
setattr(
cls,
'_stylesheet_bs5',
[
weasyprint.CSS(filename=os.path.join(settings.BASE_DIR, file_path))
for file_path in [
'base/static/css/bootstrap5/bootstrap.min.css',
]
],
)
return getattr(cls, '_stylesheet_bs5')
def get_salutation_prefix(person: Person) -> str:
with override(language=person.language):
return {
ChoixGenre.H.name: pgettext('male gender', 'Dear'),
ChoixGenre.F.name: pgettext('female gender', 'Dear'),
ChoixGenre.X.name: pgettext('other gender', 'Dear'),
}.get(person.gender or ChoixGenre.X.name)
def access_title_country(selectable_access_titles: Iterable[TitreAccesSelectionnableDTO]) -> str:
"""Return the iso code of the country of the latest access title having a specify country."""
country = ''
last_experience_year = 0
for title in selectable_access_titles:
if title.selectionne and title.pays_iso_code and title.annee > last_experience_year:
country = title.pays_iso_code
last_experience_year = title.annee
return country
def get_training_url(training_type, training_acronym, partial_training_acronym, suffix):
# Circular import otherwise
from infrastructure.messages_bus import message_bus_instance
from admission.constants import CONTEXT_CONTINUING
from admission.constants import CONTEXT_GENERAL
from admission.constants import CONTEXT_DOCTORATE
if training_type == TrainingType.FORMATION_PHD.name:
return (
"https://uclouvain.be/en/study/inscriptions/doctorate-and-doctoral-training.html"
if get_language() == settings.LANGUAGE_CODE_EN
else "https://uclouvain.be/fr/etudier/inscriptions/conditions-doctorats.html"
)
else:
admission_context = ADMISSION_CONTEXT_BY_OSIS_EDUCATION_TYPE.get(training_type)
academic_calendar_type = {
CONTEXT_GENERAL: AcademicCalendarTypes.ADMISSION_ACCESS_CONDITIONS_URL,
CONTEXT_CONTINUING: AcademicCalendarTypes.CONTINUING_EDUCATION_ENROLLMENT,
CONTEXT_DOCTORATE: AcademicCalendarTypes.DOCTORATE_EDUCATION_ENROLLMENT,
}.get(admission_context) or AcademicCalendarTypes.ADMISSION_ACCESS_CONDITIONS_URL
# Get the last year being published
today = timezone.now().today()
year = (
AcademicCalendar.objects.filter(
reference=academic_calendar_type.name,
start_date__lte=today,
)
.order_by('-start_date')
.values_list('data_year__year', flat=True)
.first()
)
sigle = training_acronym
with suppress(ProgramTreeNotFoundException): # pragma: no cover
# Try to get the acronym from the parent, if it exists
sigle = message_bus_instance.invoke(
GetSigleFormationParenteQuery(
code_formation=partial_training_acronym,
annee=year,
)
)
return f"https://uclouvain.be/prog-{year}-{sigle}-{suffix}"
def get_practical_information_url(training_type, training_acronym, partial_training_acronym):
return get_training_url(training_type, training_acronym, partial_training_acronym, 'infos_pratiques')
def get_access_conditions_url(training_type, training_acronym, partial_training_acronym):
return get_training_url(training_type, training_acronym, partial_training_acronym, 'cond_adm')
def get_access_titles_names(
access_titles: Dict[str, TitreAccesSelectionnableDTO],
curriculum_dto: CurriculumAdmissionDTO,
etudes_secondaires_dto: EtudesSecondairesAdmissionDTO,
internal_experiences: List[ExperienceParcoursInterneDTO],
) -> List[str]:
"""
Returns the list of access titles formatted names in reverse chronological order.
"""
access_titles_names = []
# Sort the access titles by year and only keep the selected ones
access_titles_list = sorted(
(access_title for access_title in access_titles.values() if access_title.selectionne),
key=lambda title: title.annee,
reverse=True,
)
curriculum_experiences_by_uuid = {
experience.uuid: experience
for experience in itertools.chain(
curriculum_dto.experiences_academiques,
curriculum_dto.experiences_non_academiques,
[etudes_secondaires_dto.experience],
internal_experiences,
)
if experience
}
for access_title in access_titles_list:
experience_name = ''
experience = curriculum_experiences_by_uuid.get(access_title.uuid_experience)
if access_title.type_titre == TypeTitreAccesSelectionnable.EXPERIENCE_PARCOURS_INTERNE.name:
# Internal experience
if isinstance(experience, ExperienceParcoursInterneDTO):
experience_derniere_annee = experience.derniere_annee
experience_name = '{title} ({year}) - UCL'.format(
title=experience_derniere_annee.intitule_formation,
year=format_academic_year(experience_derniere_annee.annee),
)
elif access_title.type_titre == TypeTitreAccesSelectionnable.ETUDES_SECONDAIRES.name:
# Secondary studies
if isinstance(experience, DiplomeBelgeEtudesSecondairesDTO):
experience_name = '{title} ({year}) - {institute}'.format(
title=str(etudes_secondaires_dto.diplome_belge),
year=format_academic_year(access_title.annee),
institute=etudes_secondaires_dto.diplome_belge.nom_institut,
)
elif isinstance(experience, DiplomeEtrangerEtudesSecondairesDTO):
experience_name = '{title} ({year}) - {country}'.format(
title=str(etudes_secondaires_dto.diplome_etranger),
year=format_academic_year(access_title.annee),
country=etudes_secondaires_dto.diplome_etranger.pays_nom,
)
elif isinstance(experience, AlternativeSecondairesDTO):
experience_name = str(etudes_secondaires_dto.alternative_secondaires)
elif etudes_secondaires_dto.annee_diplome_etudes_secondaires:
experience_name = '{title} ({year})'.format(
title=gettext('Secondary school'),
year=format_academic_year(access_title.annee),
)
else:
# Curriculum experiences
if isinstance(experience, ExperienceAcademiqueDTO):
experience_name = '{title} ({year}) - {institute}'.format(
title=f'{experience.nom_formation} ({experience.nom_formation_equivalente_communaute_fr})'
if experience.nom_formation_equivalente_communaute_fr
else experience.nom_formation,
year=format_academic_year(access_title.annee),
institute=experience.nom_institut,
)
elif isinstance(experience, ExperienceNonAcademiqueDTO):
experience_name = '{title} ({year})'.format(
title=str(experience),
year=format_academic_year(access_title.annee),
)
access_titles_names.append(experience_name)
return access_titles_names
def copy_documents(objs):
"""
Create copies of the files of the specified objects and affect them to the specified objects.
:param objs: The list of objects.
"""
from osis_document.api.utils import get_several_remote_metadata, get_remote_tokens, documents_remote_duplicate
from osis_document.contrib import FileField
from osis_document.utils import generate_filename
all_document_uuids = []
all_document_upload_paths = {}
document_fields_by_obj_uuid = {}
# Get all the document fields and the uuids of the documents to duplicate
for obj in objs:
document_fields_by_obj_uuid[obj.uuid] = {}
for field in obj._meta.get_fields():
if isinstance(field, FileField):
document_uuids = getattr(obj, field.name)
if document_uuids:
document_fields_by_obj_uuid[obj.uuid][field.name] = field
all_document_uuids += [document_uuid for document_uuid in document_uuids if document_uuid]
all_tokens = get_remote_tokens(all_document_uuids)
metadata_by_token = get_several_remote_metadata(tokens=list(all_tokens.values()))
# Get the upload paths of the documents to duplicate
for obj in objs:
for field_name, field in document_fields_by_obj_uuid[obj.uuid].items():
document_uuids = getattr(obj, field_name)
for document_uuid in document_uuids:
if not document_uuid:
continue
document_uuid_str = str(document_uuid)
file_name = 'file'
if document_uuid_str in all_tokens and all_tokens[document_uuid_str] in metadata_by_token:
metadata = metadata_by_token[all_tokens[document_uuid_str]]
if metadata.get('name'):
file_name = metadata['name']
all_document_upload_paths[document_uuid_str] = generate_filename(obj, file_name, field.upload_to)
# Make a copy of the documents and return the uuids of the copied documents
duplicates_documents_uuids = documents_remote_duplicate(
uuids=all_document_uuids,
with_modified_upload=True,
upload_path_by_uuid=all_document_upload_paths,
)
# Update the uuids of the documents with the uuids of the copied documents
for obj in objs:
for field_name in document_fields_by_obj_uuid[obj.uuid]:
setattr(
obj,
field_name,
[
uuid.UUID(duplicates_documents_uuids[str(document_uuid)])
for document_uuid in getattr(obj, field_name)
if duplicates_documents_uuids.get(str(document_uuid))
],
)
def get_experience_urls(
user: User,
admission: Union[DoctorateAdmission, GeneralEducationAdmission, ContinuingEducationAdmission],
experience: Union[ExperienceAcademiqueDTO, ExperienceNonAcademiqueDTO, EtudesSecondairesAdmissionDTO],
candidate_noma: str = '',
):
"""
Return the details and edit urls of an experience (cv experience or secondary studies).
:param user: The current user
:param admission: The admission object
:param experience: The experience dto
:param candidate_noma: The candidate noma, if any
:return: A dictionary containing the urls of the experience.
"""
current_context = {
GeneralEducationAdmission: CONTEXT_GENERAL,
DoctorateAdmission: CONTEXT_DOCTORATE,
ContinuingEducationAdmission: CONTEXT_CONTINUING,
}[type(admission)]
base_namespace = f'admission:{current_context}'
res_context = {
'edit_url': '',
'delete_url': '',
'duplicate_url': '',
'details_url': '',
'curex_url': '',
'edit_new_link_tab': False,
}
if not getattr(user, '_computed_permissions', None):
computed_permissions = {
'admission.change_admission_curriculum': user.has_perm(
perm='admission.change_admission_curriculum',
obj=admission,
),
'admission.change_admission_secondary_studies': user.has_perm(
perm='admission.change_admission_secondary_studies',
obj=admission,
),
'admission.delete_admission_curriculum': user.has_perm(
perm='admission.delete_admission_curriculum',
obj=admission,
),
'profil.can_edit_parcours_externe': user.has_perm(perm='profil.can_edit_parcours_externe'),
'profil.can_see_parcours_externe': user.has_perm(perm='profil.can_see_parcours_externe'),
}
setattr(user, '_computed_permissions', computed_permissions)
else:
computed_permissions = getattr(user, '_computed_permissions')
if isinstance(experience, ExperienceAcademiqueDTO):
res_context['details_url'] = resolve_url(
f'{base_namespace}:curriculum:educational',
uuid=admission.uuid,
experience_uuid=experience.uuid,
)
if not computed_permissions['admission.change_admission_curriculum']:
return res_context
if experience.epc_experience:
if candidate_noma:
if computed_permissions['profil.can_see_parcours_externe']:
res_context['curex_url'] = resolve_url(
'parcours-externe-view',
noma=candidate_noma,
)
if computed_permissions['profil.can_edit_parcours_externe']:
res_context['edit_url'] = resolve_url(
'edit-experience-academique-view',
noma=candidate_noma,
experience_uuid=experience.annees[0].uuid,
)
res_context['edit_new_link_tab'] = True
else:
res_context['duplicate_url'] = resolve_url(
f'{base_namespace}:update:curriculum:educational_duplicate',
uuid=admission.uuid,
experience_uuid=experience.uuid,
)
res_context['edit_url'] = resolve_url(
f'{base_namespace}:update:curriculum:educational',
uuid=admission.uuid,
experience_uuid=experience.uuid,
)
if computed_permissions['admission.delete_admission_curriculum']:
res_context['delete_url'] = resolve_url(
f'{base_namespace}:update:curriculum:educational_delete',
uuid=admission.uuid,
experience_uuid=experience.uuid,
)
elif isinstance(experience, ExperienceNonAcademiqueDTO):
res_context['details_url'] = resolve_url(
f'{base_namespace}:curriculum:non_educational',
uuid=admission.uuid,
experience_uuid=experience.uuid,
)
if not computed_permissions['admission.change_admission_curriculum']:
return res_context
res_context['duplicate_url'] = resolve_url(
f'{base_namespace}:update:curriculum:non_educational_duplicate',
uuid=admission.uuid,
experience_uuid=experience.uuid,
)
if experience.epc_experience:
if candidate_noma:
if computed_permissions['profil.can_edit_parcours_externe']:
res_context['edit_url'] = resolve_url(
'edit-experience-non-academique-view',
noma=candidate_noma,
experience_uuid=experience.uuid,
)
res_context['edit_new_link_tab'] = True
else:
res_context['edit_url'] = resolve_url(
f'{base_namespace}:update:curriculum:non_educational',
uuid=admission.uuid,
experience_uuid=experience.uuid,
)
if computed_permissions['admission.delete_admission_curriculum']:
res_context['delete_url'] = resolve_url(
f'{base_namespace}:update:curriculum:non_educational_delete',
uuid=admission.uuid,
experience_uuid=experience.uuid,
)
elif isinstance(experience, EtudesSecondairesAdmissionDTO):
res_context['details_url'] = resolve_url(
f'{base_namespace}:education',
uuid=admission.uuid,
)
if not computed_permissions['admission.change_admission_secondary_studies']:
return res_context
if experience.epc_experience:
if candidate_noma:
if computed_permissions['profil.can_edit_parcours_externe']:
res_context['edit_url'] = resolve_url(
'edit-etudes-secondaires-view',
noma=candidate_noma,
)
res_context['edit_new_link_tab'] = True
else:
res_context['edit_url'] = resolve_url(
f'{base_namespace}:update:education',
uuid=admission.uuid,
)
return res_context
def format_address(street='', street_number='', postal_code='', city='', country=''):
"""Return the concatenation of the specified street, street number, postal code, city and country."""
address_parts = [
f'{street} {street_number}',
f'{postal_code} {city}',
country,
]
return ', '.join(filter(lambda part: part and len(part) > 1, address_parts))
def format_school_title(school):
"""Return the concatenation of the school name and city."""
return '{} <span class="school-address">{}</span>'.format(
school.name,
format_address(
street=school.street,
street_number=school.street_number,
postal_code=school.zipcode,
city=school.city,
),
)
def get_superior_institute_queryset():
return EntityVersion.objects.filter(
entity__organization__establishment_type__in=[
EstablishmentTypeEnum.UNIVERSITY.name,
EstablishmentTypeEnum.NON_UNIVERSITY_HIGHER.name,
],
parent__isnull=True,
).annotate(
organization_id=F('entity__organization_id'),
organization_uuid=F('entity__organization__uuid'),
organization_acronym=F('entity__organization__acronym'),
organization_community=F('entity__organization__community'),
organization_establishment_type=F('entity__organization__establishment_type'),
name=F('entity__organization__name'),
city=F('entityversionaddress__city'),
street=F('entityversionaddress__street'),
street_number=F('entityversionaddress__street_number'),
zipcode=F('entityversionaddress__postal_code'),
)
def get_thesis_location_initial_choices(value):
return EMPTY_CHOICE if not value else EMPTY_CHOICE + ((value, value),)
def get_scholarship_initial_choices(uuid):
if not uuid:
return EMPTY_CHOICE
try:
scholarship = Scholarship.objects.get(uuid=uuid)
except Scholarship.DoesNotExist:
return EMPTY_CHOICE
return EMPTY_CHOICE + ((uuid, scholarship.long_name or scholarship.short_name),)
def get_language_initial_choices(code):
if not code:
return EMPTY_CHOICE
try:
language = Language.objects.get(code=code)
except Language.DoesNotExist:
return EMPTY_CHOICE
return EMPTY_CHOICE + (
(language.code, language.name if get_language() == settings.LANGUAGE_CODE_FR else language.name_en),
)
def get_country_initial_choices(iso_code):
if not iso_code:
return EMPTY_CHOICE
try:
country = Country.objects.get(iso_code=iso_code)
except Country.DoesNotExist:
return EMPTY_CHOICE
return EMPTY_CHOICE + (
(country.iso_code, country.name if get_language() == settings.LANGUAGE_CODE_FR else country.name_en),
)