def learning_units_external_search(request): search_form = ExternalLearningUnitYearForm(request.GET or None, initial={'academic_year_id': current_academic_year()}) user_person = get_object_or_404(Person, user=request.user) external_learning_units = [] try: if search_form.is_valid(): external_learning_units = search_form.get_learning_units() check_if_display_message(request, external_learning_units) except TooManyResultsException: display_error_messages(request, 'too_many_results') if request.POST: return redirect(reverse("learning_unit_proposal_search") + "?{}".format(request.GET.urlencode())) context = { 'form': search_form, 'academic_years': get_last_academic_years(), 'current_academic_year': current_academic_year(), 'experimental_phase': True, 'search_type': EXTERNAL_SEARCH, 'learning_units': external_learning_units, 'is_faculty_manager': user_person.is_faculty_manager(), 'form_comparison': SelectComparisonYears(academic_year=get_academic_year_of_reference(external_learning_units)), } return layout.render(request, "learning_units.html", context)
def get_queryset(self): form_class = MandatesArchivesForm form = form_class(self.request.GET) current_reviewer = reviewer.find_by_person(self.request.user.person) if len( assistant_mandate.find_for_supervisor_for_academic_year( self.request.user.person, academic_year.current_academic_year())) > 0: self.is_supervisor = True mandates_id = mandate_entity.find_by_entity( current_reviewer.entity).values_list('assistant_mandate_id', flat=True) if form.is_valid(): self.request.session['selected_academic_year'] = form.cleaned_data[ 'academic_year'].id selected_academic_year = academic_year.AcademicYear.objects.get( id=self.request.session.get('selected_academic_year')) elif self.request.session.get('selected_academic_year'): selected_academic_year = academic_year.AcademicYear.objects.get( id=self.request.session.get('selected_academic_year')) else: selected_academic_year = academic_year.current_academic_year() self.request.session[ 'selected_academic_year'] = selected_academic_year.id if self.kwargs.get("filter", None): selected_academic_year = academic_year.current_academic_year() self.request.session[ 'selected_academic_year'] = selected_academic_year.id queryset = assistant_mandate.find_by_academic_year(selected_academic_year).filter(id__in=mandates_id).\ filter(state=current_reviewer.role.replace('_ASSISTANT', '')) else: queryset = assistant_mandate.find_by_academic_year( selected_academic_year).filter(id__in=mandates_id) return queryset
def get_queryset(self): form_class = MandatesArchivesForm form = form_class(self.request.GET) current_reviewer = reviewer.find_by_person(self.request.user.person) if len(assistant_mandate.find_for_supervisor_for_academic_year(self.request.user.person, academic_year.current_academic_year())) > 0: self.is_supervisor = True mandates_id = mandate_entity.find_by_entity(current_reviewer.entity).values_list( 'assistant_mandate_id', flat=True) if form.is_valid(): self.request.session['selected_academic_year'] = form.cleaned_data[ 'academic_year'].id selected_academic_year = academic_year.AcademicYear.objects.get( id=self.request.session.get('selected_academic_year')) elif self.request.session.get('selected_academic_year'): selected_academic_year = academic_year.AcademicYear.objects.get( id=self.request.session.get('selected_academic_year')) else: selected_academic_year = academic_year.current_academic_year() self.request.session[ 'selected_academic_year'] = selected_academic_year.id if self.kwargs.get("filter", None): selected_academic_year = academic_year.current_academic_year() self.request.session[ 'selected_academic_year'] = selected_academic_year.id queryset = assistant_mandate.find_by_academic_year(selected_academic_year).filter(id__in=mandates_id).\ filter(state=current_reviewer.role.replace('_ASSISTANT', '').replace('_DAF', '')) else: queryset = assistant_mandate.find_by_academic_year(selected_academic_year).filter(id__in=mandates_id) return queryset
def get_context_data(self, **kwargs): context = super(AssistantsListView, self).get_context_data(**kwargs) context['year'] = academic_year.current_academic_year().year start_date = academic_year.current_academic_year().start_date context['is_reviewer'] = self.is_reviewer context['current_reviewer'] = self.reviewer if self.reviewer: entity = entity_version.get_last_version(self.reviewer.entity) else: entity = None context['entity'] = entity if self.is_reviewer: can_delegate = reviewer.can_delegate( reviewer.find_by_person(self.request.user.person)) context['can_delegate'] = can_delegate else: context['can_delegate'] = False for mandate in context['object_list']: entities = [] entities_id = mandate.mandateentity_set.all().order_by('id') for entity in entities_id: current_entityversion = entity_version.get_by_entity_and_date( entity.entity, start_date)[0] if current_entityversion is None: current_entityversion = entity_version.get_last_version( entity.entity) entities.append(current_entityversion) mandate.entities = entities return context
def learning_units_external_search(request): search_form = ExternalLearningUnitYearForm(request.GET or None, initial={ 'academic_year_id': current_academic_year(), 'with_entity_subordinated': True }) user_person = get_object_or_404(Person, user=request.user) found_learning_units = LearningUnitYear.objects.none() if search_form.is_valid(): found_learning_units = search_form.get_queryset() check_if_display_message(request, found_learning_units) context = { 'form': search_form, 'academic_years': get_last_academic_years(), 'current_academic_year': current_academic_year(), 'search_type': EXTERNAL_SEARCH, 'learning_units_count': found_learning_units.count(), 'is_faculty_manager': user_person.is_faculty_manager, 'form_comparison': SelectComparisonYears(academic_year=get_academic_year_of_reference( found_learning_units)), 'page_obj': paginate_queryset(found_learning_units, request.GET), } return render(request, "learning_units.html", context)
def test_update_without_parent(self): entity_version = MainEntityVersionFactory() education_group_type = MiniTrainingEducationGroupTypeFactory() initial_educ_group_year = EducationGroupYearFactory( academic_year=current_academic_year(), management_entity=entity_version.entity, education_group__start_year=current_academic_year(), education_group_type=education_group_type) initial_educ_group = initial_educ_group_year.education_group form = self.form_class(data=self.post_data, instance=initial_educ_group_year, parent=None, user=self.user) self.assertTrue(form.is_valid(), form.errors) updated_educ_group_year = form.save() self.assertEqual(updated_educ_group_year.pk, initial_educ_group_year.pk) # Assert keep the same EducationGroup when update self.assertEqual(updated_educ_group_year.education_group, initial_educ_group) self._assert_all_fields_correctly_saved(updated_educ_group_year) self.assertTrue(form.forms[ModelForm].fields["academic_year"].disabled)
def get(self, request, *args, **kwargs): return http.HttpResponse(json.dumps({ 'results': [ {'id': training['uuid'], 'text': training['acronym'] + " - " + str(training['academic_year'])} for training in get_training_list_from_osis( search=self.q, from_year=current_academic_year().year+1, to_year=current_academic_year().year+1 )['results'] ] }), content_type='application/json')
def step_impl(context: Context): calendar = AcademicCalendar.objects.filter( academic_year=current_academic_year(), reference=EDUCATION_GROUP_EDITION).first() if calendar: calendar.end_date = (datetime.now() - timedelta(days=1)).date() calendar.save()
def test_learning_units_summary_list(self, mock_render): request_factory = RequestFactory() now = datetime.datetime.now() EntityVersionFactory(entity=self.an_entity, start_date=now, end_date=datetime.datetime(now.year + 1, 9, 15), entity_type='INSTITUTE') request = request_factory.get( self.url, data={'academic_year_id': current_academic_year().id}) request.user = self.faculty_user lu = self._create_learning_unit_year_for_entity(self.an_entity) person_lu = PersonFactory() tutor_lu_1 = TutorFactory(person=person_lu) self.attribution_lu = AttributionFactory(learning_unit_year=lu, tutor=tutor_lu_1, summary_responsible=True) self._create_entity_calendar(self.an_entity) self.client.force_login(self.faculty_user) learning_units_summary_list(request) self.assertTrue(mock_render.called) request, template, context = mock_render.call_args[0] self.assertEqual(template, 'learning_units.html') self.assertEqual(context['search_type'], SUMMARY_LIST) self.assertEqual(len(context['learning_units_with_errors']), 1) self.assertTrue(context['is_faculty_manager'])
def generate_xls(): workbook = Workbook(encoding='utf-8') worksheet = workbook.active worksheet.title = "mandates" worksheet.append([_(entity_type.SECTOR), _(entity_type.FACULTY), _(entity_type.LOGISTICS_ENTITY), _(entity_type.INSTITUTE), _("matricule"), _("name"), _("firstname"), _("email"), "FGS", _("age"), _("status"), _("renewal_type"), _("assistant_type"), _("fulltime_equivalent"), _("contract_duration_fte"), _("contract_duration"), _("entry_date_contract"), _("end_date"), _("comment"), _("absences"), _("sector_vice_rector_review"), _("justification"), _("comment"), _("confidential"), ]) mandates = assistant_mandate.find_by_academic_year(academic_year.current_academic_year()) for mandate in mandates: line = construct_line(mandate) worksheet.append(line) return save_virtual_workbook(workbook)
def add_reviewer_for_structure(request): current_entity = entity.find_by_id(request.POST.get("entity")) year = academic_year.current_academic_year().year if not reviewer.can_delegate_to_entity(reviewer.find_by_person(request.user.person), current_entity): return redirect('assistants_home') form = ReviewerDelegationForm(data=request.POST) if form.is_valid() and request.POST.get('person_id'): new_reviewer = form.save(commit=False) this_person = person.find_by_id(request.POST.get('person_id')) if reviewer.find_by_person(this_person): msg = _("person_already_reviewer_msg") form.add_error(None, msg) return render(request, "reviewer_add_reviewer.html", { 'form': form, 'year': year, 'entity': current_entity, 'reviewer': reviewer.find_by_person(request.user.person) }) new_reviewer.person = this_person new_reviewer.save() html_template_ref = 'assistant_reviewers_startup_html' txt_template_ref = 'assistant_reviewers_startup_txt' send_message(person=this_person, html_template_ref=html_template_ref, txt_template_ref=txt_template_ref) return redirect('reviewer_delegation') else: this_reviewer = reviewer.find_by_person(person=request.user.person) role = this_reviewer.role + '_ASSISTANT' form = ReviewerDelegationForm(initial={'entity': current_entity, 'year': year, 'role': role}) return render(request, "reviewer_add_reviewer.html", { 'form': form, 'year': year, 'entity': current_entity, 'reviewer': reviewer.find_by_person(request.user.person) })
def send_mail_activation(request, activation_code, applicant, template_reference): logger.info('Sending mail activation to : {} '.format( applicant.user.email)) message_content = { 'html_template_ref': '{0}_html'.format(template_reference), 'txt_template_ref': '{0}_txt'.format(template_reference) } receivers = [] receiver = { 'receiver_email': applicant.user.email, 'receiver_id': applicant.id } receivers.append(receiver) message_content['receivers'] = receivers activation_link = "{0}://{1}/admission/admission/user/{2}/activation".format( request.scheme, request.get_host(), activation_code) data = { 'title': title(applicant.gender), 'academic_year': academic_year.current_academic_year(), 'activation_link': activation_link, 'signature': render_to_string( 'messaging/html_email_signature.html', { 'logo_mail_signature_url': LOGO_EMAIL_SIGNATURE_URL, 'logo_osis_url': LOGO_OSIS_URL }) } message_content['template_base_data'] = data return send_message.send_messages(message_content)
def update_education_group(request, root_id, education_group_year_id): education_group_year = get_object_or_404(EducationGroupYear, pk=education_group_year_id) if request.user.groups.filter(name=FACULTY_MANAGER_GROUP).exists() and\ education_group_year.academic_year.year < current_academic_year().year: return update_certificate_aims(request, root_id, education_group_year) return update_education_group_year(request, root_id, education_group_year)
def learning_units_proposal_search(request): search_form = LearningUnitProposalForm(request.GET or None) proposals = [] try: if search_form.is_valid(): proposals = search_form.get_proposal_learning_units() check_if_display_message(request, proposals) except TooManyResultsException: display_error_messages(request, 'too_many_results') if proposals: proposals = _proposal_management(request, proposals) a_person = find_by_user(request.user) context = { 'form': search_form, 'academic_years': get_last_academic_years(), 'current_academic_year': current_academic_year(), 'experimental_phase': True, 'search_type': PROPOSAL_SEARCH, 'proposals': proposals, 'is_faculty_manager': a_person.is_faculty_manager() } return layout.render(request, "learning_units.html", context)
def send_mail_after_annual_procedure_of_automatic_postponement( end_academic_year, luys_postponed, luys_already_existing, luys_ending_this_year, luys_with_errors): html_template_ref = 'luy_after_auto_postponement_html' txt_template_ref = 'luy_after_auto_postponement_txt' permission = Permission.objects.filter( codename='can_receive_emails_about_automatic_postponement') managers = Person.objects.filter(Q(user__groups__permissions=permission) | Q(user__user_permissions=permission))\ .distinct() receivers = [ message_config.create_receiver(manager.id, manager.email, manager.language) for manager in managers ] template_base_data = { 'academic_year': current_academic_year().year, 'end_academic_year': end_academic_year.year, 'luys_postponed': len(luys_postponed), 'luys_already_existing': luys_already_existing.count(), 'luys_ending_this_year': luys_ending_this_year.count(), 'luys_with_errors': luys_with_errors } message_content = message_config.create_message_content( html_template_ref, txt_template_ref, None, receivers, template_base_data, None, None) return message_service.send_messages(message_content)
def can_update_by_faculty_manager(self): if not self.learning_container_year: return False current_year = current_academic_year().year year = self.academic_year.year return current_year <= year <= current_year + MAX_ACADEMIC_YEAR_FACULTY
def li_with_update_perm(context, url, message, url_id="link_update"): if context['education_group_year'].academic_year.year < current_academic_year().year and \ context['person'].is_faculty_manager: return li_with_permission(context, _is_eligible_certificate_aims, url, message, url_id, True) return li_with_permission(context, is_eligible_to_change_education_group, url, message, url_id)
def _is_faculty_manager_eligible(self): if self.education_group_year.academic_year.year < current_academic_year( ).year: raise PermissionDenied( _("The faculty manager cannot modify general information which are lower than N" )) return True
def learning_units_summary_list(request): a_user_person = find_by_user(request.user) learning_units_found = [] initial_academic_year = current_academic_year() if academic_calendar.is_academic_calendar_has_started(initial_academic_year, SUMMARY_COURSE_SUBMISSION): initial_academic_year = initial_academic_year.next() search_form = LearningUnitYearForm(request.GET or None, initial={'academic_year_id': initial_academic_year}) try: if search_form.is_valid(): learning_units_found_search = search_form.get_learning_units( requirement_entities=a_user_person.find_main_entities_version, luy_status=True ) learning_units_found = get_learning_units_and_summary_status(learning_units_found_search) check_if_display_message(request, learning_units_found_search) except TooManyResultsException: display_error_messages(request, 'too_many_results') responsible_and_learning_unit_yr_list = get_responsible_and_learning_unit_yr_list(learning_units_found) learning_units = sorted(learning_units_found, key=lambda learning_yr: learning_yr.acronym) errors = [can_learning_unit_year_educational_information_be_udpated(learning_unit_year_id=luy.id) for luy in learning_units] context = { 'form': search_form, 'formset': _get_formset(request, responsible_and_learning_unit_yr_list), 'learning_units_with_errors': list(zip(learning_units, errors)), 'experimental_phase': True, 'search_type': SUMMARY_LIST, 'is_faculty_manager': a_user_person.is_faculty_manager() } return layout.render(request, "learning_units.html", context)
def test_current_academic_year(self): current_academic_yr = academic_year.current_academic_year() starting_academic_yr = academic_year.starting_academic_year() if starting_academic_yr != current_academic_yr: self.assertEqual(current_academic_yr.year, now.year - 1) else: self.assertEqual(current_academic_yr.year, now.year)
def test_update_with_parent_when_existing_group_element_year( self, mock_find_authorized_types): parent = EducationGroupYearFactory( academic_year=self.expected_educ_group_year.academic_year, education_group__end_year=None) entity_version = MainEntityVersionFactory() initial_educ_group_year = EducationGroupYearFactory( management_entity=entity_version.entity, academic_year=self.expected_educ_group_year.academic_year, education_group__start_year=current_academic_year().year) GroupElementYearFactory(parent=parent, child_branch=initial_educ_group_year) initial_count = GroupElementYear.objects.all().count() form = self.form_class(data=self.post_data, instance=initial_educ_group_year, parent=parent, user=self.user) self.assertTrue(form.is_valid(), form.errors) updated_education_group_year = form.save() # Assert existing GroupElementYear is reused. self.assertEqual(initial_count, GroupElementYear.objects.all().count()) self._assert_all_fields_correctly_saved(updated_education_group_year) self.assertTrue(form.forms[ModelForm].fields["academic_year"].disabled)
def _learning_units_search(request, search_type): service_course_search = search_type == SERVICE_COURSES_SEARCH form = LearningUnitYearForm(request.GET or None, service_course_search=service_course_search) found_learning_units = [] try: if form.is_valid(): found_learning_units = form.get_activity_learning_units() check_if_display_message(request, found_learning_units) except TooManyResultsException: messages.add_message(request, messages.ERROR, _('too_many_results')) if request.GET.get('xls_status') == "xls": return create_xls(request.user, found_learning_units) context = { 'form': form, 'academic_years': get_last_academic_years(), 'container_types': learning_container_year_types.LEARNING_CONTAINER_YEAR_TYPES, 'types': learning_unit_year_subtypes.LEARNING_UNIT_YEAR_SUBTYPES, 'learning_units': found_learning_units, 'current_academic_year': current_academic_year(), 'experimental_phase': True, 'search_type': search_type } return layout.render(request, "learning_units.html", context)
def test_learning_units_summary_list_by_client(self): self.client.force_login(self.faculty_user) response = self.client.get( self.url, data={'academic_year_id': current_academic_year().id}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "learning_units.html")
def setup_academic_years(self): self.this_year = datetime.datetime.now().year self.start_year = self.this_year - LEARNING_UNIT_CREATION_SPAN_YEARS * 2 self.last_year = self.this_year + LEARNING_UNIT_CREATION_SPAN_YEARS * 2 self.list_of_academic_years = self.create_list_of_academic_years(self.start_year, self.last_year) self.current_academic_year = mdl_academic_year.current_academic_year() index_of_current_academic_year_in_list = self.list_of_academic_years.index(self.current_academic_year) self.oldest_academic_year = self.list_of_academic_years[0] self.latest_academic_year = self.list_of_academic_years[-1] self.old_academic_year = self.list_of_academic_years[index_of_current_academic_year_in_list - LEARNING_UNIT_CREATION_SPAN_YEARS] self.last_academic_year = self.list_of_academic_years[index_of_current_academic_year_in_list + LEARNING_UNIT_CREATION_SPAN_YEARS] self.list_of_academic_years_after_now = [ academic_year for academic_year in self.list_of_academic_years if (self.current_academic_year.year <= academic_year.year <= self.last_academic_year.year) ] self.list_of_odd_academic_years = [academic_year for academic_year in self.list_of_academic_years_after_now if academic_year.year % 2] self.list_of_even_academic_years = [academic_year for academic_year in self.list_of_academic_years_after_now if not academic_year.year % 2]
def get_expiration_date(academic_year, consumed): now = safe_datetime.now() current_academic_year = mdl_academic_year.current_academic_year() current_year = current_academic_year.year if current_academic_year else None timedelta = get_time_delta(academic_year, consumed, current_year) expiration_date = now + timedelta return expiration_date
def generate_xls(): workbook = Workbook(encoding='utf-8') worksheet = workbook.active worksheet.title = "mandates" worksheet.append([ _(entity_type.SECTOR), _(entity_type.FACULTY), _(entity_type.LOGISTICS_ENTITY), _(entity_type.INSTITUTE), _("matricule"), _("name"), _("firstname"), _("email"), _("age"), _("status"), _("renewal_type"), _("assistant_type"), _("fulltime_equivalent"), _("contract_duration_fte"), _("contract_duration"), _("end_date"), _("comment"), _("absences"), _("sector_vice_rector_review"), _("justification"), _("comment"), _("confidential"), ]) mandates = assistant_mandate.find_by_academic_year( academic_year.current_academic_year()) for mandate in mandates: line = construct_line(mandate) worksheet.append(line) return save_virtual_workbook(workbook)
def setUp(self): AcademicYearFactory.produce_in_past() self.current_academic_yr = academic_year.current_academic_year() self.academic_calendar_1 = AcademicCalendarFactory.build( title="Submission of score encoding - 1", start_date=datetime.date(self.current_academic_yr.year, 10, 15), end_date=datetime.date(self.current_academic_yr.year + 1, 1, 1), academic_year=self.current_academic_yr, reference=academic_calendar_type.SCORES_EXAM_SUBMISSION) self.academic_calendar_2 = AcademicCalendarFactory.build( title="Submission of score encoding - 2", start_date=datetime.date(self.current_academic_yr.year + 1, 3, 15), end_date=datetime.date(self.current_academic_yr.year + 1, 6, 28), academic_year=self.current_academic_yr, reference=academic_calendar_type.SCORES_EXAM_SUBMISSION) self.academic_calendar_3 = AcademicCalendarFactory.build( title="Submission of score encoding - 3", start_date=datetime.date(self.current_academic_yr.year + 1, 8, 1), end_date=datetime.date(self.current_academic_yr.year + 1, 9, 29), academic_year=self.current_academic_yr, reference=academic_calendar_type.SCORES_EXAM_SUBMISSION) self.academic_calendar_4 = AcademicCalendarFactory.build( title="Deliberation session 1", start_date=datetime.date(self.current_academic_yr.year + 1, 1, 1), end_date=datetime.date(self.current_academic_yr.year + 1, 1, 2), academic_year=self.current_academic_yr, reference=academic_calendar_type.DELIBERATION) self.academic_calendar_1.save(functions=[]) self.academic_calendar_2.save(functions=[]) self.academic_calendar_3.save(functions=[]) self.academic_calendar_4.save(functions=[])
def learning_units_proposal_search(request): search_form = LearningUnitProposalForm(request.GET or None, initial={'academic_year_id': current_academic_year()}) user_person = get_object_or_404(Person, user=request.user) proposals = [] research_criteria = [] try: if search_form.is_valid(): research_criteria = get_research_criteria(search_form) proposals = search_form.get_proposal_learning_units() check_if_display_message(request, proposals) except TooManyResultsException: display_error_messages(request, 'too_many_results') if request.GET.get('xls_status') == "xls": return create_xls_proposal(request.user, proposals, _get_filter(search_form, PROPOSAL_SEARCH)) if request.POST: selected_proposals_id = request.POST.getlist("selected_action", default=[]) selected_proposals = ProposalLearningUnit.objects.filter(id__in=selected_proposals_id) messages_by_level = apply_action_on_proposals(selected_proposals, user_person, request.POST, research_criteria) display_messages_by_level(request, messages_by_level) return redirect(reverse("learning_unit_proposal_search") + "?{}".format(request.GET.urlencode())) context = { 'form': search_form, 'form_proposal_state': ProposalStateModelForm(), 'academic_years': get_last_academic_years(), 'current_academic_year': current_academic_year(), 'experimental_phase': True, 'search_type': PROPOSAL_SEARCH, 'proposals': proposals, 'is_faculty_manager': user_person.is_faculty_manager(), 'form_comparison': SelectComparisonYears(academic_year=get_academic_year_of_reference(proposals)), } return layout.render(request, "learning_units.html", context)
def save_message_history(request, type): message = Message.objects.create( sender=manager.Manager.objects.get(person=request.user.person), date=timezone.now(), type=type, academic_year=academic_year.current_academic_year()) message.save()
def settings_edit(request): """Use to edit app settings.""" global_settings = settings.get_settings() if global_settings: form = SettingsForm(initial={ 'starting_date': global_settings.starting_date, 'ending_date': global_settings.ending_date, 'assistants_starting_date': global_settings.assistants_starting_date, 'assistants_ending_date': global_settings.assistants_ending_date, 'assistants_contract_end_starting_date': global_settings.assistants_contract_end_starting_date, 'assistants_contract_end_ending_date': global_settings.assistants_contract_end_ending_date }, prefix="set", instance=global_settings) else: form = SettingsForm(prefix="set", instance=global_settings) year = academic_year.current_academic_year().year return layout.render(request, 'settings.html', { 'year': year, 'form': form, })
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form.fields[ 'education_group_type'].queryset = EducationGroupType.objects.all( ).order_by_translated_name() self.form.fields['academic_year'].initial = current_academic_year() self.form.fields[ 'category'].initial = education_group_categories.TRAINING
def test_func(self): if settings.access_to_procedure_is_open(): try: return assistant_mandate.find_for_supervisor_for_academic_year( self.request.user.person, academic_year.current_academic_year()) except ObjectDoesNotExist: return False
def get_entities(mandate): start_date = academic_year.current_academic_year().start_date entities_id = mandate.mandateentity_set.all().order_by('id').values_list('entity', flat=True) entities = find_versions_from_entites(entities_id, start_date) entities_data = "" for entity in entities: entities_data += "<strong>{} : </strong>{}<br />".format(_(entity.entity_type), entity.acronym) return entities_data
def get_context_data(self, **kwargs): context = super(StructuresListView, self).get_context_data(**kwargs) context['year'] = academic_year.current_academic_year().year context['current_reviewer'] = reviewer.find_by_person(self.request.user.person) entity = entity_version.get_last_version(context['current_reviewer'].entity) context['entity'] = entity context['is_supervisor'] = is_supervisor(self.request.user.person) return context
def get_initial(self): if self.request.session.get('selected_academic_year'): selected_academic_year = academic_year.find_academic_year_by_id( self.request.session.get('selected_academic_year')) else: selected_academic_year = academic_year.current_academic_year() self.request.session[ 'selected_academic_year'] = selected_academic_year.id return {'academic_year': selected_academic_year}
def search_by_learning_unit_this_year(code, specific_title, academic_year=None): if academic_year is None: academic_year = current_academic_year() queryset = Attribution.objects.filter(learning_unit_year__academic_year=academic_year) if specific_title: queryset = queryset.filter(learning_unit_year__specific_title__icontains=specific_title) if code: queryset = queryset.filter(learning_unit_year__acronym__icontains=code) return queryset
def get_context_data(self, **kwargs): context = super(AssistantMandatesListView, self).get_context_data(**kwargs) context['assistant'] = academic_assistant.find_by_person(person.find_by_user(self.request.user)) context['current_academic_year'] = current_academic_year() context['can_see_file'] = settings.assistants_can_see_file() for mandate in context['object_list']: entities_id = mandate.mandateentity_set.all().order_by('id').values_list('entity', flat=True) mandate.entities = base.models.entity.find_versions_from_entites(entities_id, mandate.academic_year.start_date) return context
def __init__(self, *args, start_year=None, end_year=None, **kwargs): super().__init__(*args, **kwargs) if not start_year: start_year = current_academic_year().year if not end_year: end_year = start_year + LEARNING_UNIT_CREATION_SPAN_YEARS self.choices = [(year, self.academic_year_str(year)) for year in range(start_year, end_year + 1)] self.choices = add_blank(self.choices)
def settings_save(request): global_settings = settings.get_settings() form = SettingsForm(data=request.POST, instance=global_settings, prefix='set') if form.is_valid(): form.save() return settings_edit(request) else: year = academic_year.current_academic_year().year return layout.render(request, 'settings.html', {'year': year, 'form': form})
def can_modify_end_year_by_proposal(learning_unit_year, person, raise_exception=False): result = True max_limit = current_academic_year().year + 6 if person.is_faculty_manager and not person.is_central_manager: n_year = current_academic_year().next().year elif person.is_central_manager: n_year = current_academic_year().year else: return False if learning_unit_year.academic_year.year < n_year or learning_unit_year.academic_year.year >= max_limit: result = False can_raise_exception( raise_exception, result, MSG_NOT_ELIGIBLE_TO_MODIFY_END_YEAR_PROPOSAL_ON_THIS_YEAR ) return result
def get_closest_new_session_exam(date=None): if date is None: date = datetime.date.today() current_academic_year = academic_year.current_academic_year() return SessionExamCalendar.objects.exclude(academic_calendar__start_date__isnull=True) \ .filter(academic_calendar__start_date__gte=date, academic_calendar__academic_year=current_academic_year, academic_calendar__reference=academic_calendar_type.SCORES_EXAM_SUBMISSION) \ .order_by('academic_calendar__start_date') \ .first()
def get_context_data(self, **kwargs): context = super(AssistantsListView, self).get_context_data(**kwargs) context['year'] = academic_year.current_academic_year().year context['current_reviewer'] = self.reviewer if self.reviewer: can_delegate = reviewer.can_delegate(reviewer.find_by_person(self.request.user.person)) context['can_delegate'] = can_delegate else: context['can_delegate'] = False return add_entities_version_to_mandates_list(context)
def find_by_user(user, academic_yr=None): """ :param user: User from which we get the offerYears. :param academic_yr: The academic year (takes the current academic year by default). :return: All OfferYears where the user is a program manager for a given year. """ if not academic_yr: academic_yr = academic_year.current_academic_year() program_manager_queryset = program_manager.find_by_user(user, academic_year=academic_yr) offer_year_ids = program_manager_queryset.values_list('offer_year', flat=True).distinct('offer_year') return OfferYear.objects.filter(pk__in=offer_year_ids).order_by('acronym')
def get_context_data(self, **kwargs): context = super(AssistantLearningUnitsListView, self).get_context_data(**kwargs) mandate = assistant_mandate.find_mandate_by_assistant_for_academic_year( academic_assistant.find_by_person(self.request.user.person), academic_year.current_academic_year()) context['mandate_id'] = mandate.id context['assistant_type'] = mandate.assistant_type files = assistant_document_file.find_by_assistant_mandate_and_description(mandate, document_type.TUTORING_DOCUMENT) context['files'] = files context['document_type'] = document_type.TUTORING_DOCUMENT return context
def user_is_assistant_and_procedure_is_open_and_workflow_is_assistant(user): try: mandate = assistant_mandate.find_mandate_by_assistant_for_academic_year( academic_assistant.find_by_person(user.person), academic_year.current_academic_year()) if mandate.state != assistant_mandate_state.TRTS: return False except assistant_mandate.AssistantMandate.DoesNotExist: return False else: return user.is_authenticated and settings.access_to_procedure_is_open() and \ academic_assistant.find_by_person(user.person)
def get_scores_encoding_list(user, **kwargs): current_academic_year = academic_year.current_academic_year() current_number_session = session_exam_calendar.find_session_exam_number() is_program_manager = program_manager.is_program_manager(user) learning_unit_year_id = kwargs.get('learning_unit_year_id') offer_year_id = kwargs.get('offer_year_id') tutor_id = kwargs.get('tutor_id') enrollments_ids = kwargs.get('enrollments_ids') justification = kwargs.get('justification') only_enrolled = _need_to_filter_students_enrolled_to_exam(justification, kwargs) if is_program_manager: professor = tutor.find_by_id(tutor_id) if tutor_id else None offers_year = [offer_year.find_by_id(offer_year_id)] if offer_year_id else \ list(offer_year.find_by_user(user, academic_yr=current_academic_year)) enrollments = exam_enrollment.find_for_score_encodings( academic_year=current_academic_year, session_exam_number=current_number_session, learning_unit_year_id=learning_unit_year_id, tutor=professor, offers_year=offers_year, registration_id=kwargs.get('registration_id'), student_last_name=kwargs.get('student_last_name'), student_first_name=kwargs.get('student_first_name'), justification=justification, only_enrolled=only_enrolled, ) else: professor = tutor.find_by_user(user) enrollments = exam_enrollment.find_for_score_encodings( academic_year=current_academic_year, session_exam_number=current_number_session, learning_unit_year_id=learning_unit_year_id, tutor=professor, only_enrolled=only_enrolled ) # Want a subset of exam enrollment list if enrollments_ids: enrollments = enrollments.filter(id__in=enrollments_ids) # Append deadline/deadline_tutor for each exam enrollments enrollments = _append_session_exam_deadline(list(enrollments)) enrollments = sort_encodings(enrollments) return ScoresEncodingList(**{ 'academic_year': current_academic_year, 'number_session': current_number_session, 'learning_unit_year': learning_unit_year.get_by_id(learning_unit_year_id) if learning_unit_year_id else None, 'enrollments': enrollments })
def send_message_to_assistants(request): mandates_for_current_academic_year = assistant_mandate.find_by_academic_year( academic_year.current_academic_year()) for mandate in mandates_for_current_academic_year: if mandate.renewal_type == assistant_mandate_renewal.NORMAL or \ mandate.renewal_type == assistant_mandate_renewal.SPECIAL: html_template_ref = 'assistant_assistants_startup_normal_renewal_html' txt_template_ref = 'assistant_assistants_startup_normal_renewal_txt' else: html_template_ref = 'assistant_assistants_startup_except_renewal_html' txt_template_ref = 'assistant_assistants_startup_except_renewal_txt' send_message(mandate.assistant.person, html_template_ref, txt_template_ref) save_message_history(request, message_type.TO_ALL_ASSISTANTS) return redirect('messages_history')
def _restrict_academic_years_choice_for_proposal_creation_suppression(self, proposal_type): if proposal_type in (ProposalType.CREATION.name, ProposalType.SUPPRESSION): if self.person.is_faculty_manager and proposal_type == ProposalType.CREATION.name: starting_academic_year = academic_year.current_academic_year().next() else: starting_academic_year = academic_year.starting_academic_year() end_year_range = MAX_ACADEMIC_YEAR_CENTRAL - 1 if self.person.is_faculty_manager \ else MAX_ACADEMIC_YEAR_CENTRAL self.fields["academic_year"].queryset = academic_year.find_academic_years( start_year=starting_academic_year.year, end_year=starting_academic_year.year + end_year_range )
def export_mandates_to_sap(request): mandates = assistant_mandate.find_by_academic_year_by_excluding_declined(academic_year.current_academic_year()) response = HttpResponse(content_type='application/zip') filename = ('%s_%s_%s.zip' % (_('assistants_mandates'), mandates[0].academic_year, time.strftime("%Y%m%d_%H%M"))) response['Content-Disposition'] = 'filename="%s"' % filename buffer = BytesIO() zip_file = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) for mandate in mandates: file = build_doc(request, mandates=[mandate], type='export_to_sap') zip_file.writestr(('%s_%s_%s.pdf' % (mandate.sap_id, mandate.academic_year, mandate.assistant.person.last_name)), file.content) zip_file.close() buffer.flush() ret_zip = buffer.getvalue() buffer.close() response.write(ret_zip) return response
def settings_edit(request): """Use to edit app settings.""" global_settings = settings.get_settings() if global_settings: form = SettingsForm( initial={'starting_date': global_settings.starting_date, 'ending_date': global_settings.ending_date, 'assistants_starting_date': global_settings.assistants_starting_date, 'assistants_ending_date': global_settings.assistants_ending_date, 'assistants_contract_end_starting_date': global_settings.assistants_contract_end_starting_date, 'assistants_contract_end_ending_date': global_settings.assistants_contract_end_ending_date }, prefix="set", instance=global_settings) else: form = SettingsForm(prefix="set", instance=global_settings) year = academic_year.current_academic_year().year return layout.render(request, 'settings.html', {'year': year, 'form': form, })
def _compute_end_year(education_group): """ This function compute the end year that the postponement must achieve :arg education_group: The education group that we want to postpone """ # Compute max postponement based on config EDUCATION_GROUP_MAX_POSTPONE_YEARS max_postponement_end_year = current_academic_year().year + EDUCATION_GROUP_MAX_POSTPONE_YEARS if education_group.end_year: # Get the min [Prevent education_group.end_year > academic_year.year provided by system] max_postponement_end_year = min(max_postponement_end_year, education_group.end_year) # Lookup on database, get the latest existing education group year [Prevent desync end_date and data] latest_egy = education_group.educationgroupyear_set.select_related('academic_year') \ .order_by('academic_year__year').last() return max(max_postponement_end_year, latest_egy.academic_year.year)
def list_my_attributions_summary_editable(request): tutor = get_object_or_404(Tutor, person__user=request.user) current_ac = academic_year.current_academic_year() learning_unit_years = find_learning_unit_years_by_academic_year_tutor_attributions( academic_year=current_ac.next(), tutor=tutor ) entity_calendars = entity_calendar.build_calendar_by_entities( ac_year=current_ac, reference=academic_calendar_type.SUMMARY_COURSE_SUBMISSION ) errors = (can_user_edit_educational_information(user=tutor.person.user, learning_unit_year_id=luy.id) for luy in learning_unit_years) context = { 'learning_unit_years_with_errors': zip(learning_unit_years, errors), 'entity_calendars': entity_calendars, } return render(request, 'manage_my_courses/list_my_courses_summary_editable.html', context)
def reviewer_action(request): reviewers_formset = formset_factory(ReviewersFormset)(request.POST, request.FILES) if reviewers_formset.is_valid(): for reviewer_form in reviewers_formset: action = reviewer_form.cleaned_data.get('action') if action == 'DELETE': reviewer_delete(request, reviewer_form.cleaned_data.get('id')) elif action == 'REPLACE': year = academic_year.current_academic_year().year reviewer_id = reviewer_form.cleaned_data.get('id') this_reviewer = reviewer.find_by_id(reviewer_id) entity = entity_version.get_last_version(this_reviewer.entity) form = ReviewerReplacementForm(initial={'person': this_reviewer.person, 'id': this_reviewer.id}, prefix="rev", instance=this_reviewer) return render(request, "manager_replace_reviewer.html", {'reviewer': this_reviewer, 'entity': entity, 'year': year, 'form': form}) return HttpResponseRedirect(reverse('reviewers_list'))
def get_queryset(self): form_class = MandatesArchivesForm form = form_class(self.request.GET) if form.is_valid(): self.request.session['selected_academic_year'] = form.cleaned_data[ 'academic_year'].id queryset = assistant_mandate.AssistantMandate.objects.filter( academic_year=form.cleaned_data['academic_year']) elif self.request.session.get('selected_academic_year'): selected_academic_year = academic_year.AcademicYear.objects.get( id=self.request.session.get('selected_academic_year')) queryset = assistant_mandate.AssistantMandate.objects\ .filter(academic_year=selected_academic_year) else: selected_academic_year = academic_year.current_academic_year() self.request.session[ 'selected_academic_year'] = selected_academic_year.id queryset = assistant_mandate.AssistantMandate.objects.filter( academic_year=selected_academic_year) return queryset
def build_doc(request, mandates, type='default'): if mandates: year = mandates[0].academic_year else: year = academic_year.current_academic_year() if type is 'export_to_sap': filename = ('%s_%s_%s.pdf' % (mandates[0].sap_id, year, mandates[0].assistant.person)) else: filename = ('%s_%s_%s.pdf' % (_('assistants_mandates'), year, time.strftime("%Y%m%d_%H%M"))) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="%s"' % filename buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=PAGE_SIZE, rightMargin=MARGIN_SIZE, leftMargin=MARGIN_SIZE, topMargin=70, bottomMargin=25) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Tiny', fontSize=6, font='Helvetica', leading=8, leftIndent=0, rightIndent=0, firstLineIndent=0, alignment=TA_LEFT, spaceBefore=0, spaceAfter=0, splitLongWords=1, )) styles.add(ParagraphStyle(name='StandardWithBorder', font='Helvetica', leading=18, leftIndent=10, rightIndent=10, firstLineIndent=0, alignment=TA_JUSTIFY, spaceBefore=25, spaceAfter=5, splitLongWords=1, borderColor='#000000', borderWidth=1, borderPadding=10, )) content = [] if academic_assistant.find_by_person(find_by_user(request.user)): role = user_role.ASSISTANT elif reviewer.find_by_person(find_by_user(request.user)): role = reviewer.find_by_person(find_by_user(request.user)).role else: role = user_role.ADMINISTRATOR if type is 'default' or type is 'export_to_sap': for mandate in mandates: add_mandate_content(content, mandate, styles, role) else: content.append(create_paragraph("%s (%s)<br />" % (_('declined_mandates'), year), '', styles["BodyText"])) if mandates: write_table(content, add_declined_mandates(mandates, styles['Tiny']), COLS_WIDTH_FOR_DECLINED_MANDATES) content.append(PageBreak()) doc.build(content, add_header_footer) pdf = buffer.getvalue() buffer.close() response.write(pdf) return response
def reviewer_replace(request): year = academic_year.current_academic_year().year form = ReviewerReplacementForm(data=request.POST, prefix='rev') reviewer_to_replace = reviewer.find_by_id(request.POST.get('reviewer_id')) entity = entity_version.get_last_version(reviewer_to_replace.entity) this_person = request.POST.get('person_id') if form.is_valid() and this_person: this_person = person.find_by_id(this_person) if reviewer.find_by_person(this_person): msg = _("person_already_reviewer_msg") form.add_error(None, msg) else: reviewer_to_replace.person = this_person reviewer_to_replace.save() return redirect('reviewers_list') else: msg = _("bad_person_msg") form.add_error(None, msg) return render(request, "manager_replace_reviewer.html", {'reviewer': reviewer_to_replace, 'entity': entity, 'year': year, 'form': form})
def send_mail_activation(request, activation_code, applicant, template_reference): logger.info('Sending mail activation to : {} '.format(applicant.user.email)) message_content = {'html_template_ref': '{0}_html'.format(template_reference), 'txt_template_ref': '{0}_txt'.format(template_reference)} receivers = [] receiver = {'receiver_email': applicant.user.email, 'receiver_id': applicant.id} receivers.append(receiver) message_content['receivers'] = receivers activation_link = "{0}://{1}/admission/admission/user/{2}/activation".format(request.scheme, request.get_host(), activation_code) data = {'title': title(applicant.gender), 'academic_year': academic_year.current_academic_year(), 'activation_link': activation_link, 'signature': render_to_string('messaging/html_email_signature.html', {'logo_mail_signature_url': LOGO_EMAIL_SIGNATURE_URL, 'logo_osis_url': LOGO_OSIS_URL})} message_content['template_base_data'] = data return send_message.send_messages(message_content)
def reviewer_add(request): year = academic_year.current_academic_year().year if request.POST: form = ReviewerForm(data=request.POST) this_person = request.POST.get('person_id') if form.is_valid() and this_person: this_person = person.find_by_id(this_person) new_reviewer = form.save(commit=False) if reviewer.find_by_person(this_person): msg = _("person_already_reviewer_msg") form.add_error(None, msg) if reviewer.find_by_entity_and_role(new_reviewer.entity, new_reviewer.role): msg = _("reviewer_with_same_role_already_exists_msg") form.add_error(None, msg) if not form.has_error(field=NON_FIELD_ERRORS): new_reviewer.person = this_person new_reviewer.save() return redirect('reviewers_list') else: msg = _("bad_person_msg") form.add_error(None, msg) else: form = ReviewerForm(initial={'year': year}) return render(request, "manager_add_reviewer.html", {'form': form, 'year': year})
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form.fields['education_group_type'].queryset = EducationGroupType.objects.all().order_by_translated_name() self.form.fields['academic_year'].initial = current_academic_year() self.form.fields['category'].initial = education_group_categories.TRAINING