Example #1
0
    def test_save_with_postponement_sets_inconsistents(self):
        # create postponed egy's
        self._create_postponed_egys()

        # update with inconsistant EducationGroupOrganization (organization present in the future not in present)
        self.education_group_year.refresh_from_db()
        unconsistent_egy = EducationGroupYear.objects.get(
            education_group=self.education_group_year.education_group,
            academic_year=self.list_acs[4])
        EducationGroupOrganizationFactory(
            organization=OrganizationFactory(),
            education_group_year=unconsistent_egy)
        EducationGroupOrganizationFactory(
            organization=OrganizationFactory(),
            education_group_year=self.education_group_year)

        form = TrainingForm(self.data,
                            instance=self.education_group_year,
                            user=self.user)
        self.assertTrue(form.is_valid(), form.errors)
        form.save()

        self.assertGreater(len(form.warnings), 0)
        self.assertEqual(form.warnings, [
            _("Consistency error in %(academic_year)s : %(error)s") % {
                'academic_year': unconsistent_egy.academic_year,
                'error': EducationGroupOrganization._meta.verbose_name.title()
            }
        ])
Example #2
0
    def test_init(self):
        # In case of creation
        form = TrainingForm({},
                            user=self.user,
                            education_group_type=self.education_group_type)
        self.assertFalse(form.dict_initial_egy)
        self.assertEqual(form.initial_dicts,
                         {'educationgrouporganization_set': {}})

        # In case of update
        coorg = EducationGroupOrganizationFactory(
            organization=OrganizationFactory(),
            education_group_year=self.education_group_year)
        form = TrainingForm({},
                            user=self.user,
                            instance=self.education_group_year)
        dict_initial_egy = model_to_dict_fk(self.education_group_year,
                                            exclude=form.field_to_exclude)

        self.assertEqual(str(form.dict_initial_egy), str(dict_initial_egy))
        initial_dict_coorg = model_to_dict_fk(
            self.education_group_year.coorganizations.first(),
            exclude=FIELD_TO_EXCLUDE_IN_SET)
        self.assertEqual(
            form.initial_dicts, {
                'educationgrouporganization_set': {
                    coorg.organization.id: initial_dict_coorg
                }
            })
Example #3
0
    def test_save_with_postponement(self):
        # Create postponed egy
        form = TrainingForm(self.data,
                            instance=self.education_group_year,
                            user=self.user)
        self.assertTrue(form.is_valid(), form.errors)
        form.save()

        self.assertEqual(len(form.education_group_year_postponed), 6)

        self.assertEqual(
            EducationGroupYear.objects.filter(
                education_group=self.education_group_year.education_group).
            count(), 7)
        self.assertEqual(len(form.warnings), 0)

        # Update egys
        self.education_group_year.refresh_from_db()

        self.data["title"] = "Defence Against the Dark Arts"
        form = TrainingForm(self.data,
                            instance=self.education_group_year,
                            user=self.user)
        self.assertTrue(form.is_valid(), form.errors)
        form.save()

        self.assertEqual(
            EducationGroupYear.objects.filter(
                education_group=self.education_group_year.education_group).
            count(), 7)
        self.assertEqual(len(form.warnings), 0, form.warnings)
Example #4
0
    def test_save_with_postponement_m2m(self):
        domains = [
            DomainFactory(name="Alchemy"),
            DomainFactory(name="Muggle Studies")
        ]
        self.data["secondary_domains"] = '|'.join(
            [str(domain.pk) for domain in domains])

        certificate_aims = [
            CertificateAimFactory(code=100, section=1),
            CertificateAimFactory(code=101, section=2)
        ]
        self.data["certificate_aims"] = [
            str(aim.pk) for aim in certificate_aims
        ]

        self._create_postponed_egys()

        last = EducationGroupYear.objects.filter(
            education_group=self.education_group_year.education_group
        ).order_by('academic_year').last()

        self.education_group_year.refresh_from_db()
        self.assertEqual(self.education_group_year.secondary_domains.count(),
                         2)
        self.assertEqual(last.secondary_domains.count(), 2)
        self.assertEqual(last.certificate_aims.count(), len(certificate_aims))

        # update with a conflict
        dom3 = DomainFactory(name="Divination")
        EducationGroupYearDomainFactory(domain=dom3, education_group_year=last)

        domains = [
            DomainFactory(name="Care of Magical Creatures"),
            DomainFactory(name="Muggle Studies")
        ]

        self.data["secondary_domains"] = '|'.join(
            [str(domain.pk) for domain in domains])

        form = TrainingForm(self.data,
                            instance=self.education_group_year,
                            user=self.user)
        self.assertTrue(form.is_valid(), form.errors)
        form.save()

        self.assertEqual(len(form.education_group_year_postponed), 5)

        self.assertEqual(
            EducationGroupYear.objects.filter(
                education_group=self.education_group_year.education_group).
            count(), 7)
        last.refresh_from_db()
        self.education_group_year.refresh_from_db()

        self.assertEqual(self.education_group_year.secondary_domains.count(),
                         2)
        self.assertEqual(last.secondary_domains.count(), 3)
        self.assertEqual(len(form.warnings), 1)
Example #5
0
def _update_training(request, education_group_year, root,
                     groupelementyear_formset):
    # TODO :: IMPORTANT :: Fix urls patterns to get the GroupElementYear_id and the root_id in the url path !
    # TODO :: IMPORTANT :: Need to update form to filter on list of parents, not only on the first direct parent
    form_education_group_year = TrainingForm(request.POST or None,
                                             user=request.user,
                                             instance=education_group_year)
    coorganization_formset = None
    forms_valid = all([
        form_education_group_year.is_valid(),
        groupelementyear_formset.is_valid()
    ])
    if has_coorganization(education_group_year):
        coorganization_formset = OrganizationFormset(
            data=request.POST or None,
            form_kwargs={
                'education_group_year': education_group_year,
                'user': request.user
            },
            queryset=education_group_year.coorganizations)
        forms_valid = forms_valid and coorganization_formset.is_valid()
    if request.method == 'POST':
        if forms_valid:
            if has_coorganization(education_group_year):
                coorganization_formset.save()
            return _common_success_redirect(request, form_education_group_year,
                                            root, groupelementyear_formset)
        else:
            show_error_message_for_form_invalid(request)

    return render(
        request, "education_group/update_trainings.html", {
            "education_group_year":
            education_group_year,
            "form_education_group_year":
            form_education_group_year.forms[forms.ModelForm],
            "form_education_group":
            form_education_group_year.forms[EducationGroupModelForm],
            "form_coorganization":
            coorganization_formset,
            "form_hops":
            form_education_group_year.hops_form,
            "show_coorganization":
            has_coorganization(education_group_year),
            "show_diploma_tab":
            form_education_group_year.show_diploma_tab(),
            'can_change_coorganization':
            perms.is_eligible_to_change_coorganization(
                person=request.user.person,
                education_group=education_group_year,
            ),
            'group_element_years':
            groupelementyear_formset,
            "is_finality_types":
            education_group_year.is_finality
        })
Example #6
0
 def _create_postponed_egys(self):
     form = TrainingForm(self.data,
                         instance=self.education_group_year,
                         user=self.user)
     self.assertTrue(form.is_valid(), form.errors)
     form.save()
     self.assertEqual(len(form.education_group_year_postponed), 6)
     self.assertEqual(len(form.warnings), 0)
     self.assertEqual(
         EducationGroupYear.objects.filter(
             education_group=self.education_group_year.education_group).
         count(), 7)
Example #7
0
 def _postpone_coorganization_and_check(self):
     form = TrainingForm(self.data,
                         instance=self.education_group_year,
                         user=self.user)
     self.assertTrue(form.is_valid(), form.errors)
     form.save()
     self.assertEqual(len(form.warnings), 0, form.warnings)
     all_egys = EducationGroupYear.objects.filter(
         education_group=self.education_group_year.education_group)
     self.assertEqual(all_egys.count(), 7)
     for egy in all_egys:
         self.assertEqual(egy.educationgrouporganization_set.all().count(),
                          1)
Example #8
0
    def test_init(self):
        # In case of creation
        form = TrainingForm({},
                            user=UserFactory(),
                            education_group_type=self.education_group_type)
        self.assertFalse(hasattr(form, "dict_initial_egy"))

        # In case of update
        form = TrainingForm({},
                            user=UserFactory(),
                            instance=self.education_group_year)
        dict_initial_egy = _model_to_dict(self.education_group_year,
                                          exclude=form.field_to_exclude)

        self.assertEqual(str(form.dict_initial_egy), str(dict_initial_egy))
Example #9
0
    def test_init(self):
        # In case of creation
        form = TrainingForm({},
                            user=self.user,
                            education_group_type=self.education_group_type)
        self.assertFalse(form.dict_initial_egy)

        # In case of update
        form = TrainingForm({},
                            user=self.user,
                            instance=self.education_group_year)
        dict_initial_egy = model_to_dict_fk(self.education_group_year,
                                            exclude=form.field_to_exclude)

        self.assertEqual(str(form.dict_initial_egy), str(dict_initial_egy))
Example #10
0
    def test_ensure_show_diploma_tab_is_hidden(self):
        """
        This test ensure that the show diploma property is False if all fields contains in tab are disabled
        """
        form = TrainingForm(
            {},
            user=self.user_without_perm,
            education_group_type=self.education_group_type,
            context=TRAINING_DAILY_MANAGEMENT,
        )
        for field_name_in_diploma in form.diploma_tab_fields:
            form.forms[
                forms.ModelForm].fields[field_name_in_diploma].disabled = True

        self.assertFalse(form.show_diploma_tab())
Example #11
0
def _update_training(request, education_group_year, root):
    # TODO :: IMPORTANT :: Fix urls patterns to get the GroupElementYear_id and the root_id in the url path !
    # TODO :: IMPORTANT :: Need to update form to filter on list of parents, not only on the first direct parent
    form_education_group_year = TrainingForm(request.POST or None,
                                             user=request.user,
                                             instance=education_group_year)
    coorganization_formset = None

    if show_coorganization(education_group_year):
        coorganization_formset = OrganizationFormset(
            data=request.POST or None,
            form_kwargs={
                'education_group_year': education_group_year,
                'user': request.user
            },
            queryset=education_group_year.coorganizations)
        if form_education_group_year.is_valid(
        ) and coorganization_formset.is_valid():
            coorganization_formset.save()
            return _common_success_redirect(request, form_education_group_year,
                                            root)
    else:
        if form_education_group_year.is_valid():
            return _common_success_redirect(request, form_education_group_year,
                                            root)

    return render(
        request, "education_group/update_trainings.html", {
            "education_group_year":
            education_group_year,
            "form_education_group_year":
            form_education_group_year.forms[forms.ModelForm],
            "form_education_group":
            form_education_group_year.forms[EducationGroupModelForm],
            "form_coorganization":
            coorganization_formset,
            "form_hops":
            form_education_group_year.hops_form,
            "show_coorganization":
            show_coorganization(education_group_year),
            'can_change_coorganization':
            perms.is_eligible_to_change_coorganization(
                person=request.user.person,
                education_group=education_group_year,
            )
        })
Example #12
0
    def test_save_with_postponement_coorganization_inconsistant(self):
        # create postponed egy's
        self._create_postponed_egys()

        # update with a coorganization to postpone
        self.education_group_year.refresh_from_db()

        good_organization = EducationGroupOrganizationFactory(
            organization=OrganizationFactory(),
            education_group_year=self.education_group_year)
        self._postpone_coorganization_and_check()

        # update with unconsistant EducationGroupOrganization (field different from a year to another one)
        self.education_group_year.refresh_from_db()
        unconsistent_egy = EducationGroupYear.objects.get(
            education_group=self.education_group_year.education_group,
            academic_year=self.list_acs[4])
        unconsistent_orga = EducationGroupOrganization.objects.get(
            education_group_year=unconsistent_egy)
        unconsistent_orga.all_students = not good_organization.all_students
        unconsistent_orga.save()
        # have to invalidate cache
        del self.education_group_year.coorganizations
        form = TrainingForm(self.data,
                            instance=self.education_group_year,
                            user=self.user)

        self.assertTrue(form.is_valid(), form.errors)
        form.save()
        self.assertEqual(len(form.warnings), 1)
        error_msg = _("%(col_name)s has been already modified.") % {
            "col_name":
            _(
                EducationGroupOrganization._meta.get_field(
                    'all_students').verbose_name).title(),
        }
        self.assertEqual(form.warnings, [
            _("Consistency error in %(academic_year)s with %(model)s: %(error)s"
              ) %
            {
                'academic_year': unconsistent_egy.academic_year,
                'model': EducationGroupOrganization._meta.verbose_name.title(),
                'error': error_msg
            }
        ])
Example #13
0
def _update_training(request, education_group_year, root):
    # TODO :: IMPORTANT :: Fix urls patterns to get the GroupElementYear_id and the root_id in the url path !
    # TODO :: IMPORTANT :: Need to update form to filter on list of parents, not only on the first direct parent
    form_education_group_year = TrainingForm(request.POST or None,
                                             instance=education_group_year)
    if form_education_group_year.is_valid():
        return _common_success_redirect(request,
                                        form_education_group_year.save(), root)

    return layout.render(
        request, "education_group/update_trainings.html", {
            "education_group_year":
            education_group_year,
            "form_education_group_year":
            form_education_group_year.forms[forms.ModelForm],
            "form_education_group":
            form_education_group_year.forms[EducationGroupModelForm]
        })
Example #14
0
    def test_save_with_postponement_error(self):
        EducationGroupYearFactory(
            academic_year=self.list_acs[4],
            education_group=self.education_group_year.education_group)

        form = TrainingForm(self.data,
                            instance=self.education_group_year,
                            user=UserFactory())
        self.assertTrue(form.is_valid(), form.errors)
        form.save()

        self.assertEqual(len(form.education_group_year_postponed), 5)

        self.assertEqual(
            EducationGroupYear.objects.filter(
                education_group=self.education_group_year.education_group).
            count(), 7)
        self.assertEqual(len(form.warnings), 15)
Example #15
0
 def test_ensure_diploma_tab_fields_property(self):
     form = TrainingForm(
         {},
         user=self.user_with_perm,
         education_group_type=self.education_group_type,
         context=TRAINING_DAILY_MANAGEMENT,
     )
     expected_fields = [
         'joint_diploma', 'diploma_printing_title', 'professional_title',
         'section', 'certificate_aims'
     ]
     self.assertEqual(form.diploma_tab_fields, expected_fields)
Example #16
0
    def test_save_with_postponement_certificate_aims_inconsistant(self):
        """
        This test ensure that the we haven't an error if the certificate aims is inconsistant in future because
        certificate aims is managed by program_manager (This form is only accessible on Central/Faculty manager)
        """
        # Save the training instance will create N+6 data...
        form = TrainingForm(self.form_data,
                            instance=self.training,
                            user=self.central_manager.user)
        self.assertTrue(form.is_valid(), form.errors)
        form.save()

        # Add certificate aims in future...
        training_future = EducationGroupYear.objects.filter(
            education_group=self.training.education_group,
            academic_year__year=self.training.academic_year.year + 2).get()
        certificate_aims_in_future = EducationGroupCertificateAimFactory(
            education_group_year=training_future)

        # Re-save and ensure that there are not consitency errors and the modification is correctly postponed
        form = TrainingForm(
            {
                **self.form_data, "title": "Modification du titre"
            },
            instance=self.training,
            user=self.central_manager.user,
        )
        self.assertTrue(form.is_valid(), form.errors)
        form.save()
        self.assertFalse(form.warnings, form.warnings)

        training_future.refresh_from_db()
        self.assertEqual(training_future.title, "Modification du titre")

        # Ensure that certificate aims has not be modified during postponement
        self.assertTrue(
            EducationGroupCertificateAim.objects.filter(
                pk=certificate_aims_in_future.pk).exists())
Example #17
0
 def test_init_case_user_without_perms(self):
     """
     In this test, we ensure that field present in FieldReference and user don't have permission is disabled
      ==> [main_teaching_campus]
     For field which are not present in FieldReference (same context), the field is not disabled by default
      ==> [partial_acronym]
     """
     form = TrainingForm(
         {},
         user=self.user_without_perm,
         education_group_type=self.education_group_type,
         context=TRAINING_DAILY_MANAGEMENT,
     )
     self.assertTrue(form.forms[forms.ModelForm].fields["main_teaching_campus"].disabled)
     self.assertFalse(form.forms[forms.ModelForm].fields["partial_acronym"].disabled)
Example #18
0
def create_education_group(request, category=None, parent_id=None):
    parent = get_object_or_404(EducationGroupYear,
                               id=parent_id) if parent_id is not None else None

    forms_by_category = {
        education_group_categories.GROUP:
        GroupForm(request.POST or None, parent=parent),
        education_group_categories.TRAINING:
        TrainingForm(request.POST or None, parent=parent),
        education_group_categories.MINI_TRAINING:
        MiniTrainingForm(request.POST or None, parent=parent),
    }

    form_education_group_year = forms_by_category.get(category)

    if form_education_group_year.is_valid():
        education_group_year = form_education_group_year.save()

        parent_id = parent.pk if parent else education_group_year.pk

        success_msg = create_success_message_for_creation_education_group_year(
            parent_id, education_group_year)
        display_success_messages(request, success_msg, extra_tags='safe')

        url = reverse("education_group_read",
                      args=[parent_id, education_group_year.pk])

        return redirect(url)

    templates_by_category = {
        education_group_categories.GROUP:
        "education_group/create_groups.html",
        education_group_categories.TRAINING:
        "education_group/create_trainings.html",
        education_group_categories.MINI_TRAINING:
        "education_group/create_mini_trainings.html",
    }

    return layout.render(
        request, templates_by_category.get(category), {
            "form_education_group_year":
            form_education_group_year.forms[forms.ModelForm],
            "form_education_group":
            form_education_group_year.forms[EducationGroupModelForm],
            "parent":
            parent
        })
Example #19
0
    def setUpTestData(cls):
        super().setUpTestData()

        cls.current_academic_year = AcademicYearFactory(current=True)
        cls.generated_ac_years = AcademicYearFactory.produce(
            base_year=cls.current_academic_year.year,
            number_past=0,
            number_future=7)
        cls.entity_version = MainEntityVersionFactory(
            entity_type=entity_type.SECTOR)
        cls.central_manager = CentralManagerFactory()
        PersonEntityFactory(person=cls.central_manager,
                            entity=cls.entity_version.entity)
        cls.training = TrainingFactory(
            management_entity=cls.entity_version.entity,
            administration_entity=cls.entity_version.entity,
            academic_year=cls.current_academic_year)
        # Save the training instance will create N+6 data...
        form_data = model_to_dict_fk(cls.training,
                                     exclude=('secondary_domains', ))
        form_data.update({
            'primary_language': form_data['primary_language_id'],
            'administration_entity': cls.entity_version.pk,
            'management_entity': cls.entity_version.pk
        })
        training_form = TrainingForm(form_data,
                                     instance=cls.training,
                                     user=cls.central_manager.user)
        training_form.is_valid()
        training_form.save()

        cls.certificate_aim_type_2 = CertificateAimFactory(section=2, code=200)
        cls.certificate_aim_type_4 = CertificateAimFactory(section=4, code=400)
        cls.form_data = {
            'certificate_aims':
            [cls.certificate_aim_type_2.pk, cls.certificate_aim_type_4.pk]
        }