diff --git a/entries/views.py b/entries/views.py index 686d92503c6e64aac482b5ecef552af57026d622..9ad899e8371cc06bea44a236a04381f9a50cf68b 100644 --- a/entries/views.py +++ b/entries/views.py @@ -107,10 +107,12 @@ def hierarchy(request): }, ) + FORM_TYPES = { 'entry' : EntryForm, } + FORM_FACTORY_TYPES = { 'schema' : SchemaFormFactory, 'position' : PositionFormFactory, @@ -128,14 +130,12 @@ FORM_FACTORY_TYPES = { def make_form(form_type, data=None, unique_number=None): - #print('======== MAKE FORM', form_type) if form_type in FORM_FACTORY_TYPES: return FORM_FACTORY_TYPES[form_type].get_form(data=data, unique_number=unique_number) if form_type in FORM_TYPES: return FORM_TYPES[form_type](data=data) elif form_type.startswith('phrase_'): phrase_type = form_type[7:] - #print('================ MAKE PHRASE FORM', phrase_type, unique_number) return PhraseAttributesFormFactory.get_form(phrase_type, data=data, unique_number=unique_number) return None diff --git a/financial_settlement/forms.py b/financial_settlement/forms.py index 5d3cc2e5d822f3c66e13d44f5767af14864c8040..62de4b10ad7a75704585a9f0c5f87b6e0ab2b900 100644 --- a/financial_settlement/forms.py +++ b/financial_settlement/forms.py @@ -14,13 +14,10 @@ from users.models import Note class FinStatementForm(forms.ModelForm): start_date = forms.DateTimeField(input_formats=['%d-%m-%Y'], - widget = forms.DateTimeInput( - format ='%d-%m-%Y', - attrs= {'class':'form-control'})) + widget=forms.DateTimeInput(format='%d-%m-%Y', attrs={'class': 'form-control'})) end_date = forms.DateTimeField(input_formats=['%d-%m-%Y'], - widget = forms.DateTimeInput( - format ='%d-%m-%Y', - attrs= {'class':'form-control'})) + widget=forms.DateTimeInput( + format='%d-%m-%Y', attrs={'class': 'form-control'})) user = forms.ModelChoiceField(queryset=User.objects.all(), label=_('Użytkownik')) @@ -44,10 +41,12 @@ class FinStatementForm(forms.ModelForm): super().__init__(*args, instance=instance, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( - Fieldset('', 'statement_id', 'title', 'start_date', 'end_date', 'payment', 'price_per_unified_frame', 'last_statement_payment', 'user', 'is_active'), + Fieldset('', 'statement_id', 'title', 'start_date', 'end_date', + 'payment', 'price_per_unified_frame', 'last_statement_payment', 'user', 'is_active'), ButtonHolder( Submit('submit', _('Zapisz'), css_class='btn btn-sm btn-success'), - HTML(format_lazy('<a class="btn btn-sm btn-light" href="{}">{}</a>', reverse_lazy('financial_settlement:statement_list'), _('Wróć'))), + HTML(format_lazy('<a class="btn btn-sm btn-light" href="{}">{}</a>', + reverse_lazy('financial_settlement:statement_list'), _('Wróć'))), ), ) for field in ['statement_id', 'title', 'start_date', 'end_date', 'payment', 'price_per_unified_frame', 'user']: @@ -62,70 +61,3 @@ class FinStatementForm(forms.ModelForm): def save(self, commit=True): instance = super().save(commit=commit) return instance - - -# class UserProfileForm(forms.ModelForm): -# class Meta: -# model = User -# fields = [ -# 'first_name', -# 'last_name', -# 'email', -# ] -# -# def __init__(self, *args, instance, **kwargs): -# super().__init__(*args, instance=instance, **kwargs) -# self.helper = FormHelper() -# self.helper.layout = Layout( -# Fieldset('', 'first_name', 'last_name', 'email'), -# ButtonHolder( -# Submit('submit', _('Zapisz'), css_class='btn btn-sm btn-success'), -# HTML(format_lazy('<a class="btn btn-sm btn-light" href="{}">{}</a>', reverse_lazy('users:password_change'), _('Zmień swoje hasło'))), -# HTML(format_lazy('<a class="btn btn-sm btn-light" href="{}">{}</a>', reverse_lazy('dash'), _('Wróć'))), -# ), -# ) -# for field in ['first_name', 'last_name', 'email']: -# self.fields[field].required = True -# -# -# login_form_helper = FormHelper() -# login_form_helper.layout = Layout( -# Fieldset('', 'username', 'password'), -# ButtonHolder( -# Submit('submit', _('Zaloguj się'), css_class='btn btn-sm btn-success'), -# HTML(format_lazy('<a class="btn btn-sm btn-light" href="{}">{}</a>', reverse_lazy('users:password_reset'), _('Nie pamiętam hasła'))), -# ), -# ) -# -# password_reset_form_helper = FormHelper() -# password_reset_form_helper.layout = Layout( -# Fieldset('', 'email'), -# ButtonHolder( -# Submit('submit', _('Zresetuj hasło'), css_class='btn btn-sm btn-success'), -# HTML(format_lazy('<a class="btn btn-sm btn-light" href="{}">{}</a>', reverse_lazy('users:login'), _('Wróć'))), -# ) -# ) -# -# password_change_form_helper = FormHelper() -# password_change_form_helper.layout = Layout( -# Fieldset('', 'old_password', 'new_password1', 'new_password2'), -# ButtonHolder( -# Submit('submit', _('Zmień hasło'), css_class='btn btn-sm btn-success'), -# HTML(format_lazy('<a class="btn btn-sm btn-light" href="{}">{}</a>', reverse_lazy('users:user_profile'), _("Wróć"))), -# ) -# ) -# -# password_reset_set_password_form_helper = FormHelper() -# password_reset_set_password_form_helper.layout = Layout( -# Fieldset('', 'new_password1', 'new_password2'), -# ButtonHolder( -# Submit('submit', _('Ustaw hasło'), css_class='btn btn-sm btn-success'), -# HTML(format_lazy('<a class="btn btn-sm btn-light" href="{}">{}</a>', reverse_lazy('dash'), _("Wróć"))), -# ) -# ) -# -# -# class NoteForm(forms.ModelForm): -# class Meta: -# model = Note -# fields = ["title", "note"] diff --git a/financial_settlement/models.py b/financial_settlement/models.py index d6bbd83fe938b37ebe6a074ac6a08e64fca04b1e..4f2a6220ece4a645e87cafc90b8b44219d169796 100644 --- a/financial_settlement/models.py +++ b/financial_settlement/models.py @@ -1,15 +1,16 @@ from django.contrib.auth.models import User from django.db import models -class FinStatement(models.Model): +class FinStatement(models.Model): + """" Class represents finance statement assigned to the user. """ statement_id = models.PositiveIntegerField(null=False) title = models.CharField(max_length=200, default=None, blank=True, null=True) start_date = models.DateField(null=False) end_date = models.DateField(null=False) - payment = models.DecimalField(null=False, default=0, max_digits = 10,decimal_places=3) - price_per_unified_frame = models.DecimalField(null=False, default=0, max_digits = 10,decimal_places=3) - last_statement_payment = models.DecimalField(null=False, default=0, max_digits = 10,decimal_places=3) + payment = models.DecimalField(null=False, default=0, max_digits=10, decimal_places=3) + price_per_unified_frame = models.DecimalField(null=False, default=0, max_digits=10, decimal_places=3) + last_statement_payment = models.DecimalField(null=False, default=0, max_digits=10, decimal_places=3) user = models.ForeignKey(User, on_delete=models.PROTECT, default=None, blank=True, null=True) is_active = models.BooleanField(default=False) diff --git a/financial_settlement/views.py b/financial_settlement/views.py index ed1c9316fdcb026621458017d90f5b9697b0a3e6..06df81cf6fd120bec51b8922452916c1f1d0cb6f 100644 --- a/financial_settlement/views.py +++ b/financial_settlement/views.py @@ -14,19 +14,35 @@ from unifier.choices import UnifiedFrameStatus from unifier.models import UnifiedFrame from users.forms import UserForm, UserProfileForm, NoteForm -def statement_list(request): +def statement_list(request): + """ + Redirecting to the statement list view for the 'statement_id' given in the request. + :param request: Http request + :return: fin_statements_list view + """ current_user = request.user cat_edit_statement = current_user.has_perm(FinStatement, 'edit_statement') - statements = FinStatement.objects.order_by('statement_id') if cat_edit_statement else FinStatement.objects.filter(user=current_user).order_by('statement_id') + statements = None + if cat_edit_statement: + statements = FinStatement.objects.order_by('statement_id') + else: + FinStatement.objects.filter(user=current_user).order_by('statement_id') + for statement in statements: statement.unified_frame_count = statement.unified_frame.count() statement.current_cost = statement.unified_frame.count() * statement.price_per_unified_frame return render(request, 'fin_statements_list.html', {'statements': statements}) + @permission_required('finstatement.add_statement') def statement_add(request): + """ + Redirecting to the statement add form. + :param request: Http request + :return: fin_statement_form view + """ if request.method == 'POST': form = FinStatementForm(instance=FinStatement(), data=request.POST) if form.is_valid(): @@ -36,8 +52,16 @@ def statement_add(request): form = FinStatementForm(instance=FinStatement()) return render(request, 'fin_statement_form.html', {'form': form, 'title': _('Dodaj umowę')}) + @permission_required('finstatement.change_statement') def statement_edit(request, pk): + """ + Redirecting to the statement edit form. + If the request method is POST, then save the form; otherwise, edit the given statement. + :param request: Http request + :param pk: Id of the statement to edit. + :return: Redirecting to fin_statement_form or fin_statement_form regardless of the method type. + """ statement = get_object_or_404(FinStatement, pk=pk) if request.method == 'POST': form = FinStatementForm(instance=statement, data=request.POST) @@ -48,9 +72,16 @@ def statement_edit(request, pk): form = FinStatementForm(instance=statement) return render(request, 'fin_statement_form.html', {'form': form, 'title': _('Edytuj umowę')}) + def statement_detail(request, pk): + """ + Redirecting to the statement details form. + :param request: Http request + :param pk: 'pk' as statement id + :return: Redirecting to fin_statement_details + """ statement = get_object_or_404(FinStatement, pk=pk) - unified_frames = statement.unified_frame; + unified_frames = statement.unified_frame return render(request, 'fin_statement_details.html', {'statement': statement, diff --git a/unifier/models.py b/unifier/models.py index 35973cf6ed4c0c5233bc1279c6668b16678609ea..ecabcb38741e31b6e99d8ea41669241901efe3f2 100644 --- a/unifier/models.py +++ b/unifier/models.py @@ -34,7 +34,8 @@ class UnifiedFrame(models.Model): objects = models.Manager.from_queryset(UnifiedFrameQueryset)() - fin_statement = models.ForeignKey(FinStatement, on_delete=models.PROTECT, blank=True, default=None, null=True, related_name='unified_frame') + fin_statement = models.ForeignKey(FinStatement, on_delete=models.PROTECT, blank=True, default=None, null=True, + related_name='unified_frame') hasHierarchyElems = models.BooleanField(default=False) @@ -67,7 +68,8 @@ class UnifiedFrame(models.Model): new_unified_frame_arguments = UnifiedFrameArgument.objects.filter(unified_frame=new_frame).all() unified_frame_arguments = UnifiedFrameArgument.objects.filter(unified_frame=self).all() if len(new_unified_frame_arguments) < len(unified_frame_arguments): - raise Exception('Target frame has to little arguments, required: ' + str(len(unified_frame_arguments))+', but found: '+str(len(new_unified_frame_arguments))) + raise Exception('Target frame has to little arguments, required: ' + str(len(unified_frame_arguments)) + + ', but found: '+str(len(new_unified_frame_arguments))) for slowal_frame in slowal_frames: mapping = UnifiedFrame2SlowalFrameMapping.objects.get(unified_frame=self, slowal_frame=slowal_frame) @@ -132,7 +134,8 @@ class UnifiedFrameArgument(models.Model): relations = models.ManyToManyField('UnifiedRelationalSelectionalPreference') # odwołanie do ramy - unified_frame = models.ForeignKey(UnifiedFrame, related_name='unified_arguments', default=None, blank=True, null=True, on_delete=models.PROTECT) + unified_frame = models.ForeignKey(UnifiedFrame, related_name='unified_arguments', + default=None, blank=True, null=True, on_delete=models.PROTECT) # do wyszukiwania preferences_count = models.PositiveIntegerField(null=False, default=0) @@ -143,7 +146,7 @@ class UnifiedFrameArgument(models.Model): class UnifiedRelationalSelectionalPreference(models.Model): relation = models.ForeignKey(SelectionalPreferenceRelation, on_delete=models.PROTECT) - to = models.ForeignKey(UnifiedFrameArgument,on_delete=models.PROTECT) + to = models.ForeignKey(UnifiedFrameArgument, on_delete=models.PROTECT) def __str__(self): return '%s -> %s' % (self.relation, self.to) @@ -151,16 +154,20 @@ class UnifiedRelationalSelectionalPreference(models.Model): class UnifiedFrame2SlowalFrameMapping(models.Model): removed = models.BooleanField(default=False) - unified_frame = models.ForeignKey(UnifiedFrame, related_name='unified_frame_2_slowal_frame', on_delete=models.PROTECT) + unified_frame = models.ForeignKey(UnifiedFrame, related_name='unified_frame_2_slowal_frame', + on_delete=models.PROTECT) slowal_frame = models.OneToOneField(Frame, related_name='slowal_frame_2_unified_frame', on_delete=models.PROTECT) class UnifiedFrameArgumentSlowalFrameMapping(models.Model): - unified_agrument = models.ForeignKey(UnifiedFrameArgument, related_name='unified_agrument_mapping', on_delete=models.PROTECT) + unified_agrument = models.ForeignKey(UnifiedFrameArgument, related_name='unified_agrument_mapping', + on_delete=models.PROTECT) slowal_agrument = models.ForeignKey(Argument, related_name='slowal_agrument_mapping', on_delete=models.PROTECT) - unified_frame_mapping = models.ForeignKey(UnifiedFrame2SlowalFrameMapping, related_name='unified_frame_argument_mapping', on_delete=models.PROTECT) + unified_frame_mapping = models.ForeignKey(UnifiedFrame2SlowalFrameMapping, + related_name='unified_frame_argument_mapping', on_delete=models.PROTECT) class HierarchyModel(models.Model): + """Represents hierarchy relationship between two unified frames.""" hyponym = models.ForeignKey(UnifiedFrame, related_name='hyponym_mapping', on_delete=models.PROTECT) hyperonym = models.ForeignKey(UnifiedFrame, related_name='hyperonym_mapping', on_delete=models.PROTECT) diff --git a/unifier/views.py b/unifier/views.py index 67f713574cbd75f6ff31946d5d86d3884060c98d..bd98f98bc01b926a5edb591215d9d6afda8072a8 100644 --- a/unifier/views.py +++ b/unifier/views.py @@ -9,8 +9,8 @@ from django.views.decorators.csrf import csrf_exempt from common.decorators import ajax_required, ajax from entries.polish_strings import EXAMPLE_SOURCE, EXAMPLE_OPINION -from entries.views import get_scroller_params, get_alternations, get_prefs_list, schema2dict, frame2dict, collect_forms, \ - get_filtered_objects, get_local_schema_filter_form, get_local_frame_filter_form +from entries.views import get_scroller_params, get_alternations, get_prefs_list, schema2dict, \ + frame2dict, collect_forms, get_filtered_objects, get_local_schema_filter_form, get_local_frame_filter_form from financial_settlement.models import FinStatement from importer.unification.UnificationPreprocessXML import UnificationPreprocessHandler from meanings.models import LexicalUnit @@ -94,12 +94,12 @@ def get_unified_frames(request): if 'unified_frame_form' in request.session: forms = collect_forms(request.session['unified_frame_form'], errors_dict) - unifiedFrames = get_filtered_objects(forms).filter() + unified_frames = get_filtered_objects(forms).filter() else: - unifiedFrames = UnifiedFrame.objects.all() + unified_frames = UnifiedFrame.objects.all() if scroller_params['filter']: - unifiedFrames = unifiedFrames.filter(title__startswith=scroller_params['filter']) + unified_frames = unified_frames.filter(title__startswith=scroller_params['filter']) # TODO: zapytać, czy mamy zaciągać powiązane ramy zunifikowane poprzez Enrty (slowal_frame -> lexical_units -> entries -> related_entries) # linked_ids = set() @@ -114,7 +114,7 @@ def get_unified_frames(request): res = {} - for unifiedFrame in unifiedFrames: + for unifiedFrame in unified_frames: res[unifiedFrame.id] = { 'id': str(unifiedFrame.id), 'title': unifiedFrame.title, @@ -153,7 +153,8 @@ def unifiedFrame2dict(frame): 'id': a.id, 'role': { 'str': '{}{}'.format(a.role.role.role.lower(), - ' ' + a.role.attribute.attribute.lower() if a.role.attribute else '') if a.role is not None else None, + ' ' + a.role.attribute.attribute.lower() if a.role.attribute else + '') if a.role is not None else None, 'id': str(a.role.id) } if a.role is not None else None, 'role_type': a.role_type.type.lower() if a.role_type is not None else '', @@ -187,7 +188,8 @@ def get_examples(frames): for argument in frame.arguments.all(): for connection in argument.example_connections.all(): example = connection.example - frame_ids, argument_ids, lu_ids, schema_ids, phrases, phrases_syntax, positions = set(), set(), set(), set(), set(), set(), set() + frame_ids, argument_ids, lu_ids, schema_ids, phrases, phrases_syntax + positions = set(), set(), set(), set(), set(), set(), set() for connection in example.example_connections.all(): for argument in connection.arguments.all(): frame_ids.add(argument.frame.id) @@ -195,7 +197,7 @@ def get_examples(frames): if connection.lexical_unit: lu_ids.add(connection.lexical_unit.id) for hook in connection.schema_connections.all(): - schema_ids.add(hook.schema.id); + schema_ids.add(hook.schema.id) phrases.add('{}-{}-{}-{}'.format(hook.schema.id, hook.position.id, hook.phrase_type.id, hook.alternation - 1)) phrases_syntax.add('{}-{}-{}'.format(hook.schema.id, hook.position.id, hook.phrase_type.id)) @@ -219,7 +221,7 @@ def get_examples(frames): return sorted(examples, key=lambda x: x['sentence']) -def get_unified_frame_json(unifiedFrame, request): +def get_unified_frame_json(unified_frame, request): local_schema_filter_form = None local_frame_filter_form = None if 'no_filters' in request.POST: @@ -228,7 +230,7 @@ def get_unified_frame_json(unifiedFrame, request): local_frame_filter_form = get_local_frame_filter_form(apply_filters, request) slowal_frames_db = Frame.objects.filter( - id__in=unifiedFrame.unified_frame_2_slowal_frame.values("slowal_frame_id")).distinct() + id__in=unified_frame.unified_frame_2_slowal_frame.values("slowal_frame_id")).distinct() if local_frame_filter_form: slowal_frames_db = get_filtered_objects(local_frame_filter_form, slowal_frames_db) @@ -257,9 +259,9 @@ def get_unified_frame_json(unifiedFrame, request): 'schemata': all_schema_objects_dict }] - unifiedFrame_dict = unifiedFrame2dict(unifiedFrame) + unifiedFrame_dict = unifiedFrame2dict(unified_frame) - return {'unified_frame_id': unifiedFrame.id, 'unified_frame': unifiedFrame_dict, 'subentries': subentries, + return {'unified_frame_id': unified_frame.id, 'unified_frame': unifiedFrame_dict, 'subentries': subentries, 'frames': slowal_frames_dict, 'alternations': alternations, 'realisation_phrases': realisation_phrases, 'realisation_descriptions': realisation_descriptions, 'examples': examples, 'last_visited': request.session['last_visited']} @@ -276,8 +278,8 @@ def get_unified_frame(request): if unified_frame_id.isdigit(): # and form.is_valid(): unified_frame_id = int(unified_frame_id) request.session.modified = True - unifiedFrame = UnifiedFrame.objects.get(id=unified_frame_id) - return JsonResponse(get_unified_frame_json(unifiedFrame, request)) + unified_frame = UnifiedFrame.objects.get(id=unified_frame_id) + return JsonResponse(get_unified_frame_json(unified_frame, request)) return JsonResponse({}) @@ -322,7 +324,9 @@ def remove_selectional_preference(request): def updateArgumentPreferencesCount(unified_frame_argument): - unified_frame_argument.preferences_count = unified_frame_argument.predefined.count() + unified_frame_argument.synsets.count() + unified_frame_argument.relations.count(); + unified_frame_argument.preferences_count = unified_frame_argument.predefined.count() + \ + unified_frame_argument.synsets.count() + \ + unified_frame_argument.relations.count() unified_frame_argument.save() @@ -642,6 +646,13 @@ def delete_unified_frame(request, unified_frame_id): @ajax_required @transaction.atomic def hierarchy_assign(request): + """ + Assign hierarchy relationship. + The request has to contain 'hyponym_id' and 'hypernym_id' that represent + unified frames taking part in the relationship. + :param request: http request + :return: Json response containg single field 'succ': (true|false) or 'exists': 'true' + """ if request.method == 'POST': hyponym_id = request.POST['hyponym_id'] @@ -674,6 +685,12 @@ def setHierarchyExistsInfo(unified_fram_id): @ajax_required @transaction.atomic def hierarchy_unassign(request): + """ + Unassign hierarchy relationship. + The request has to contain 'rel1_id' and 'rel2_id' that represent unified frame IDs hierarchy pair. + :param request: http request + :return: Json response containg single field 'succ' = (true|false) + """ if request.method == 'POST': rel1_id = request.POST['rel1_id'] @@ -700,7 +717,12 @@ def hierarchy_unassign(request): def setNoHierarchyExistsInfo(unified_frame_id): - rel_1_hierarchy_count = HierarchyModel.objects.filter(Q(hyponym_id=unified_frame_id) | Q(hyperonym_id=unified_frame_id)).count() + """ + Set unified frame field 'hasHierarchyElems' as false if needed. + :param unified_frame_id: Unified frame id + """ + rel_1_hierarchy_count = HierarchyModel.objects.filter(Q(hyponym_id=unified_frame_id) | + Q(hyperonym_id=unified_frame_id)).count() if rel_1_hierarchy_count == 0: # set info of no hierarchy elems in unified frame -> used to color unified frame list component unified_frame = UnifiedFrame.objects.get(pk=unified_frame_id) @@ -711,6 +733,12 @@ def setNoHierarchyExistsInfo(unified_frame_id): @ajax_required @transaction.atomic def get_hierarchy_hyponyms(request, unified_frame_id): + """ + Returning hierarchy hyponyms for a given unified_frame_id + :param request: http request + :param unified_frame_id: Unifird fram id for witch hyponyms will be returned + :return: Json response containing list of unified frames as hyponyms + """ hyponyms = HierarchyModel.objects.filter(hyperonym_id=unified_frame_id) res = [] @@ -726,6 +754,12 @@ def get_hierarchy_hyponyms(request, unified_frame_id): @ajax_required @transaction.atomic def get_hierarchy_hyperonyms(request, unified_frame_id): + """ + Returning hierarchy hypernyms for a given unified_frame_id. + :param request: http request + :param unified_frame_id: Unifird fram id for witch hyperonyms will be returned + :return: Json response containing list of unified frames as hyperonyms + """ hyperonyms = HierarchyModel.objects.filter(hyponym_id=unified_frame_id) res = []