Skip to content

Commit

Permalink
Dodawanie/edycja marek z formularza firmy (#3753)
Browse files Browse the repository at this point in the history
* Dodawanie/edycja marek z formularza firmy

* fixup! Dodawanie/edycja marek z formularza firmy
  • Loading branch information
mik-laj authored May 5, 2024
1 parent 39a0bfe commit fe7ab5f
Show file tree
Hide file tree
Showing 4 changed files with 274 additions and 5 deletions.
23 changes: 22 additions & 1 deletion pola/company/forms.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#!/usr/bin/python
from crispy_forms.helper import FormHelper
from dal import autocomplete
from django import forms
from django.forms import inlineformset_factory

from pola.forms import (
CommitDescriptionMixin,
Expand All @@ -13,7 +15,11 @@
from . import models


class CompanyForm(ReadOnlyFieldsMixin, SaveButtonMixin, FormHorizontalMixin, CommitDescriptionMixin, forms.ModelForm):
class CompanyForm(ReadOnlyFieldsMixin, FormHorizontalMixin, CommitDescriptionMixin, forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper.form_tag = False

readonly_fields = ['name']

class Meta:
Expand Down Expand Up @@ -74,3 +80,18 @@ class Meta:
model = models.Brand
fields = ['name', 'common_name', 'company', 'logotype']
widgets = {'company': autocomplete.ModelSelect2(url='company:company-autocomplete')}


BrandFormSet = inlineformset_factory(
models.Company, models.Brand, fields=['name', 'common_name', 'company'], exclude=[], can_delete=True
)


class BrandFormSetHelper(FormHelper):
template = 'bootstrap/table_inline_formset.html'
form_tag = False

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.form_method = 'post'
self.render_required_fields = True
57 changes: 55 additions & 2 deletions pola/company/templates/company/company_form.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,30 @@
{% endblock %}

{% block content %}
{% crispy form %}
<form
id="company-form"
method="POST"
action="{{ form.helper.form_action }}"
{% if form.is_multipart %} enctype="multipart/form-data"{% endif %}>
<div class="form-horizontal">
{% crispy form %}
</div>
<div class="brand-formset clearfix">
{% crispy brand_formset brand_formset_helper %}
<div class="pull-right">
<button class="btn add-row" type="button">Add new row</button>
</div>
</div>
<div class="form-horizontal">
<div class="form-group">
<div class="aab controls col-lg-3"></div>
<div class="controls col-lg-9">
<input type="submit" name="action" value="Save" class="btn btn-primary" id="submit-id-action">
<input type="reset" name="reset" value="Przywróć poprzednie" class="btn btn-inverse" id="reset-id-reset">
</div>
</div>
</div>
</form>
{% endblock content %}

{% block javascript %}
Expand All @@ -35,5 +58,35 @@
$('#div_id_commit_desc textarea').text('Nowy opis firmy na podstawie opisów w poprzednim formacie')
}
</script>
{% endif %}
{% endif %}
<script>
$('.brand-formset').each(function() {
const $formset = $(this);
const $addButton = $formset.find('.add-row');
const $template = $formset.find('.empty-form').clone();
const $rowsContainer = $formset.find('.empty-form').parent()
const $totalForms = $formset.find('input[name$=TOTAL_FORMS]');

console.log({$formset, $addButton, $template, $rowsContainer})
$template.removeClass('hidden empty-form')
$addButton.click(function () {
const $newRow = $template.clone();
// -1 because of the empty form
const formCount = $rowsContainer.children().length - 1;
$newRow.find('input, select, textarea, td').each(function () {
const $el = $(this);
['name', 'id'].forEach(function (attr) {
const value = $el.attr(attr);
if (value) {
$el.attr(attr, value.replace('__prefix__', formCount));
}
});
});
$rowsContainer.append($newRow);
// +1 because of the added form
$totalForms.val(formCount + 1);
});
})

</script>
{% endblock %}
153 changes: 152 additions & 1 deletion pola/company/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,19 +50,170 @@ class TestCompanyCreateView(PermissionMixin, TemplateUsedMixin, TestCase):
url = reverse_lazy('company:create')
template_name = 'company/company_form.html'

def test_form_success(self):
self.login()
post_data = {
"name": "",
"official_name": "Test Company",
"common_name": "Nazwa dla uzytkownika",
"is_friend": "False",
"display_brands_in_description": "False",
"plCapital": "100",
"plWorkers": "100",
"plRnD": "100",
"plRegistered": "100",
"plNotGlobEnt": "100",
"description": "",
"sources": "",
"verified": "False",
"Editor_notes": "",
"nip": "",
"address": "",
"logotype": "",
"official_url": "",
"commit_desc": "Opis zmiany",
"brand_set-TOTAL_FORMS": "3",
"brand_set-INITIAL_FORMS": "0",
"brand_set-MIN_NUM_FORMS": "0",
"brand_set-MAX_NUM_FORMS": "1000",
"brand_set-__prefix__-name": "",
"brand_set-__prefix__-common_name": "",
"brand_set-__prefix__-company": "",
"brand_set-__prefix__-id": "",
"brand_set-__prefix__-DELETE": "on",
"brand_set-0-name": "Test Brand",
"brand_set-0-common_name": "Nazwa dla uzytkownika marki",
"brand_set-0-company": "",
"brand_set-0-id": "",
"brand_set-1-name": "",
"brand_set-1-common_name": "",
"brand_set-1-company": "",
"brand_set-1-id": "",
"brand_set-2-name": "",
"brand_set-2-common_name": "",
"brand_set-2-company": "",
"brand_set-2-id": "",
"action": "Save",
}
response = self.client.post(self.url, post_data)

self.assertEqual(Company.objects.count(), 1)
self.assertEqual(Brand.objects.count(), 1)
company = Company.objects.first()
self.assertEqual(company.official_name, 'Test Company')
self.assertEqual(Brand.objects.first().name, 'Test Brand')
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, company.get_absolute_url())


class TestCompanyCreateFromKRSView(PermissionMixin, TemplateUsedMixin, WebTestMixin, TestCase):
url = reverse_lazy('company:create_from_krs')
template_name = 'company/company_from_krs.html'


class TestCompanyUpdate(CompanyInstanceMixin, PermissionMixin, TemplateUsedMixin, TestCase):
class TestCompanyUpdateView(CompanyInstanceMixin, PermissionMixin, TemplateUsedMixin, TestCase):
template_name = 'company/company_form.html'

def setUp(self):
super().setUp()
self.url = reverse('company:edit', kwargs={'pk': self.instance.pk})

def test_form_success_with_formset(self):
self.brand_instance = BrandFactory(company=self.instance)
self.login()

initial_form_data = {
"name": self.instance.name,
"official_name": self.instance.official_name,
"common_name": self.instance.common_name,
"is_friend": "False",
"display_brands_in_description": "False",
"plCapital": "",
"plWorkers": "",
"plRnD": "",
"plRegistered": "",
"plNotGlobEnt": "",
"description": self.instance.description,
"sources": "",
"verified": "False",
"Editor_notes": "",
"nip": "",
"address": "",
"logotype": "",
"official_url": "",
"commit_desc": "",
"brand_set-TOTAL_FORMS": "4",
"brand_set-INITIAL_FORMS": "1",
"brand_set-MIN_NUM_FORMS": "0",
"brand_set-MAX_NUM_FORMS": "1000",
"brand_set-0-name": self.brand_instance.name,
"brand_set-0-common_name": self.brand_instance.common_name,
"brand_set-0-company": str(self.instance.pk),
"brand_set-0-id": str(self.brand_instance.pk),
"brand_set-1-name": "",
"brand_set-1-common_name": "",
"brand_set-1-company": str(self.instance.pk),
"brand_set-1-id": "",
"brand_set-2-name": "",
"brand_set-2-common_name": "",
"brand_set-2-company": str(self.instance.pk),
"brand_set-2-id": "",
"brand_set-3-name": "",
"brand_set-3-common_name": "",
"brand_set-3-company": str(self.instance.pk),
"brand_set-3-id": "",
"action": "Save",
}

# Update company data
post_data = initial_form_data.copy()
post_data['official_name'] = post_data['official_name'] + "_updated"

# Set change description
post_data['commit_desc'] = 'Commit message'

# Update brand data
post_data['brand_set-0-name'] = post_data['brand_set-0-name'] + "_updated"
post_data['brand_set-0-common_name'] = post_data['brand_set-0-common_name'] + "_updated"

# Add new brand using dynamic formset
post_data.update(
{
"brand_set-4-name": "New brand - name",
"brand_set-4-common_name": "New brand - common-name",
"brand_set-4-company": str(self.instance.pk),
"brand_set-4-id": "",
}
)
post_data["brand_set-TOTAL_FORMS"] = str(int(post_data["brand_set-TOTAL_FORMS"]) + 1)

response = self.client.post(self.url, post_data)
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, self.instance.get_absolute_url())

self.assertEqual(Company.objects.count(), 1)
self.assertEqual(Brand.objects.count(), 2)

company = Company.objects.first()
company.refresh_from_db()

self.assertTrue(
company.official_name.endswith('_updated'), f"{company.official_name!r} does not end with '_updated'"
)

existing_brand = Brand.objects.get(pk=self.brand_instance.pk)
self.assertTrue(
existing_brand.name.endswith('_updated'), f"{existing_brand.name!r} does not end with '_updated'"
)
self.assertTrue(
existing_brand.common_name.endswith('_updated'),
f"{existing_brand.common_name!r} does not end with '_updated'",
)

new_brand = Brand.objects.filter(company=company).exclude(pk=self.brand_instance.pk).first()
self.assertEqual(new_brand.name, "New brand - name")
self.assertEqual(new_brand.common_name, "New brand - common-name")


class TestCompanyUpdateWeb(WebTestMixin, TestCase):
def setUp(self):
Expand Down
46 changes: 45 additions & 1 deletion pola/company/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,13 @@

from ..logic_score import get_pl_score
from .filters import BrandFilter, CompanyFilter
from .forms import BrandForm, CompanyCreateFromKRSForm, CompanyForm
from .forms import (
BrandForm,
BrandFormSet,
BrandFormSetHelper,
CompanyCreateFromKRSForm,
CompanyForm,
)


class CompanyListView(LoginPermissionRequiredMixin, FilterView):
Expand All @@ -48,6 +54,26 @@ class CompanyCreate(GetInitalFormMixin, LoginPermissionRequiredMixin, FormValidM
form_class = CompanyForm
form_valid_message = "Firma utworzona!"

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.request.POST:
context['brand_formset'] = BrandFormSet(self.request.POST)
else:
context['brand_formset'] = BrandFormSet()
context['brand_formset_helper'] = BrandFormSetHelper()
return context

def form_valid(self, form):
context = self.get_context_data(form=form)
formset = context['brand_formset']
if formset.is_valid():
response = super().form_valid(form)
formset.instance = self.object
formset.save()
return response
else:
return super().form_invalid(form)


class CompanyCreateFromKRSView(LoginPermissionRequiredMixin, FormView):
permission_required = 'company.add_company'
Expand All @@ -73,6 +99,24 @@ class CompanyUpdate(LoginPermissionRequiredMixin, FormValidMessageMixin, Concure
concurency_url = reverse_lazy('concurency:lock')
form_valid_message = "Firma zaktualizowana!"

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.request.POST:
context['brand_formset'] = BrandFormSet(self.request.POST, instance=self.object)
else:
context['brand_formset'] = BrandFormSet(instance=self.object)
context['brand_formset_helper'] = BrandFormSetHelper()
return context

def form_valid(self, form):
response = super().form_valid(form)
formset = BrandFormSet(self.request.POST, instance=self.object)
if formset.is_valid():
formset.save()
else:
return super().form_invalid(form)
return response


class CompanyDelete(LoginPermissionRequiredMixin, FormValidMessageMixin, DeleteView):
permission_required = 'company.delete_company'
Expand Down

0 comments on commit fe7ab5f

Please sign in to comment.