From 05662cf62b78a16e1dc38b11846187bff5a47809 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Tue, 2 Feb 2021 12:40:35 +0100 Subject: [PATCH 01/25] uniform check for empty strings --- openebs/form.py | 2 +- openebs/models.py | 4 ++-- openebs/views_change.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/openebs/form.py b/openebs/form.py index 247d532..4c08f0b 100644 --- a/openebs/form.py +++ b/openebs/form.py @@ -67,7 +67,7 @@ def clean(self): def clean_messagecontent(self): # Improve: Strip spaces from message if ('messagecontent' not in self.cleaned_data or self.cleaned_data['messagecontent'] is None or len( - self.cleaned_data['messagecontent']) < 1) \ + self.cleaned_data['messagecontent'].strip()) == 0) \ and self.cleaned_data['messagetype'] != 'OVERRULE': raise ValidationError(_("Bericht mag niet leeg zijn")) return self.cleaned_data['messagecontent'] diff --git a/openebs/models.py b/openebs/models.py index 2a38b6a..bf68dda 100644 --- a/openebs/models.py +++ b/openebs/models.py @@ -148,7 +148,7 @@ class Meta(object): def __str__(self): message = self.messagecontent - if message == "": + if not message or len(message.strip()) == 0: message = _("") return "%s|%s#%s : %s" % (self.dataownercode, self.messagecodedate, self.messagecodenumber, message) @@ -370,7 +370,7 @@ class Kv15ScenarioMessage(models.Model): def __str__(self): message = self.messagecontent - if message == "": + if not message or len(message.strip()) == 0: message = _("") return "%s : %s" % (self.scenario.name, message) diff --git a/openebs/views_change.py b/openebs/views_change.py index 258c5c2..10e68ad 100644 --- a/openebs/views_change.py +++ b/openebs/views_change.py @@ -79,7 +79,7 @@ def add_journeys_from_request(self, data): journey_errors = 0 journeys = [] for journey in self.request.GET['journey'].split(','): - if journey == "": + if len(journey.strip()) == 0: continue log.info("Finding journey %s for '%s'" % (journey, self.request.user)) j = Kv1Journey.find_from_realtime(self.request.user.userprofile.company, journey) From 192629093dd11d881d24568e65f10188fd82be8f Mon Sep 17 00:00:00 2001 From: baasje85 Date: Tue, 2 Feb 2021 12:55:21 +0100 Subject: [PATCH 02/25] typfout gecorrigeerd in choices model FerryKv6Messages --- ferry/migrations/0017_auto_20210202_1254.py | 18 ++++++++++++++++++ ferry/models.py | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 ferry/migrations/0017_auto_20210202_1254.py diff --git a/ferry/migrations/0017_auto_20210202_1254.py b/ferry/migrations/0017_auto_20210202_1254.py new file mode 100644 index 0000000..ff6aa06 --- /dev/null +++ b/ferry/migrations/0017_auto_20210202_1254.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.17 on 2021-02-02 11:54 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('ferry', '0016_auto_20160424_1526'), + ] + + operations = [ + migrations.AlterField( + model_name='ferrykv6messages', + name='status', + field=models.PositiveSmallIntegerField(choices=[(1, 'Gereed voor vertrek'), (5, 'Vertrokken'), (10, 'Aankomst')], default=0, verbose_name='Status'), + ), + ] diff --git a/ferry/models.py b/ferry/models.py index e1c3d1e..461d055 100644 --- a/ferry/models.py +++ b/ferry/models.py @@ -42,7 +42,7 @@ class Status(object): ARRIVED = 10 STATUS = ( - (Status.READY, _("Gereerd voor vertrek")), + (Status.READY, _("Gereed voor vertrek")), (Status.DEPARTED, _("Vertrokken")), (Status.ARRIVED, _("Aankomst")), ) From 156ac2d25e89bc9acc242792011157f39064015c Mon Sep 17 00:00:00 2001 From: baasje85 Date: Tue, 2 Feb 2021 12:56:19 +0100 Subject: [PATCH 03/25] validity check user-entered times --- openebs/form.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/openebs/form.py b/openebs/form.py index 4c08f0b..95321f9 100644 --- a/openebs/form.py +++ b/openebs/form.py @@ -274,8 +274,27 @@ def clean(self): if 'messageendtime' not in data: raise ValidationError(_("Voer een geldige eindtijd in")) + datetimevalidation = [] + try: + datetime.strptime(self.data['messagestarttime'], "%d-%m-%Y %H:%M:%S") + except: + datetimevalidation.append(_("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)")) + pass + + try: + datetime.strptime(self.data['messageendtime'], "%d-%m-%Y %H:%M:%S") + except: + datetimevalidation.append(_("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)")) + pass + + if len(datetimevalidation) == 2: + raise ValidationError(_("Voer een geldige begin- en eindtijd in (dd-mm-jjjj uu:mm:ss)")) + elif len(datetimevalidation) == 1: + raise ValidationError(datetimevalidation[0]) + if data['messageendtime'] <= data['messagestarttime']: raise ValidationError(_("Einde bericht moet na begin zijn")) + return data def __init__(self, *args, **kwargs): From 643e592c85085b5d8c52ccb987d55acf499941ec Mon Sep 17 00:00:00 2001 From: baasje85 Date: Tue, 2 Feb 2021 13:03:43 +0100 Subject: [PATCH 04/25] added date to future activeMessages --- .../templates/openebs/snippet_message-duration_small.html | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/openebs/templates/openebs/snippet_message-duration_small.html b/openebs/templates/openebs/snippet_message-duration_small.html index 2a513cc..b78059f 100644 --- a/openebs/templates/openebs/snippet_message-duration_small.html +++ b/openebs/templates/openebs/snippet_message-duration_small.html @@ -1,5 +1,9 @@ {% load i18n %} -{{ msg.messagestarttime|date:"H:i" }} - +{% if msg.is_future %} + {{ msg.messagestarttime|date:"d-m-Y H:i" }} - +{% else %} + {{ msg.messagestarttime|date:"H:i" }} - +{% endif %} {% if msg.get_message_duration == 0 %} {{ msg.messageendtime|date:"H:i" }} {% elif msg.get_message_duration == 1 %} From 848dc558f0782706158b103cfd0ee9a8c078c175 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Tue, 2 Feb 2021 15:55:32 +0100 Subject: [PATCH 05/25] validate 'ritaanpassing' within .js --- openebs/form_kv17.py | 2 +- .../templates/openebs/kv17change_form.html | 4 +- openebs2/static/js/add_msg_journey.js | 81 ++++++++++++++++++- 3 files changed, 84 insertions(+), 3 deletions(-) diff --git a/openebs/form_kv17.py b/openebs/form_kv17.py index a9386f2..f7df1db 100644 --- a/openebs/form_kv17.py +++ b/openebs/form_kv17.py @@ -33,7 +33,7 @@ class Kv17ChangeForm(forms.ModelForm): advicecontent = forms.CharField(max_length=255, label=_("Uitleg advies"), required=False, widget=forms.Textarea(attrs={'cols': 40, 'rows': 4, 'class': 'col-lg-6'})) - def clean(self): + def clean(self): # should be redundant after jquery filter in html-form, but just in case cleaned_data = super(Kv17ChangeForm, self).clean() operatingday = parse_date(self.data['operatingday']) if operatingday is None: diff --git a/openebs/templates/openebs/kv17change_form.html b/openebs/templates/openebs/kv17change_form.html index 8418237..1744194 100644 --- a/openebs/templates/openebs/kv17change_form.html +++ b/openebs/templates/openebs/kv17change_form.html @@ -90,13 +90,15 @@

{% trans "Ritaanpassing" %}

{% endif %}


+ +

{% crispy form form.helper %}

- +
diff --git a/openebs2/static/js/add_msg_journey.js b/openebs2/static/js/add_msg_journey.js index 215ce2e..5b609a4 100644 --- a/openebs2/static/js/add_msg_journey.js +++ b/openebs2/static/js/add_msg_journey.js @@ -361,7 +361,7 @@ function emptyLineList() { $("#lijn-list").empty(); $("#lines").val(''); selectedLines = []; - cancelledLines = []; + //cancelledLines = []; currentLineMeasures = []; $('#lijn-list span').remove(); $('.lijn-overzicht').css("display","none"); @@ -527,6 +527,79 @@ function changeOfRange() { colorSelectedRange(); } +function formValidation() { + // check if operatingday is filled + validationerrors = [] + operatingday = $('#id_operatingday').val(); + if (operatingday === null) { + validationerrors.push("Er staan geen ritten in de database.") + } + // check if journeys are filled + if ($('#lines').val().length == 0 && $('#journeys').val().length == 0) { + validationerrors.push("Er zijn geen ritten geselecteerd om op te heffen.") + } else if ($('#lines').val().length !== 0) { + var begintime = null; + var endtime = null; + if ($('#id_begintime_part').val().length !== 0) { + begintime = stringToTime($('#id_begintime_part').val()); + } + if ($('#id_endtime_part').val().length !== 0) { + endtime = stringToTime($('#id_endtime_part').val()); + } + + if (begintime !== null && endtime !== null) { + if (endtime >= 25200 && endtime < begintime) { + validationerrors.push("Eindtijd valt op volgende operationele dag.") + } + } + var is_active = 0; + $.each(selectedLines, function(i, line_id) { + if (line_id == 'Hele vervoerder') { + line_id = null; + } + check_results = check_for_active_lines(line_id, begintime, endtime); + if (check_results !== 0) { + is_active += 1; + } + }); + if (is_active > 0) { + validationerrors.push("De ingangstijd valt al binnen een geplande operatie."); + } + } + + if (validationerrors.length == 0) { + $(".form").submit(); + } else { + if (!$("#error_list").hasClass('hidden')) { + $("#error_list").empty(); + } + $.each(validationerrors, function(i, error) { + $("#error_list").append('

'+error+'

'); + }); + if ($("#error_list").hasClass('hidden')) { + $("#error_list").removeClass('hidden'); + } + } +} + +function check_for_active_lines(line_id, begintime, endtime) { + count = 0; + cancelledLines.filter(measure => { + if (measure.id === line_id || measure.id === null) { + if (measure.begintime === null && measure.endtime === null) { + count += 1; + } else if (measure.begintime === null && measure.endtime > begintime) { + count += 1; + } else if (measure.begintime <= begintime && measure.endtime === null) { + count += 1; + } else if (measure.begintime <= begintime && measure.endtime >= begintime) { + count += 1; + } + } + }); + return count; +} + /* TIME FUNCTIONS */ function convertSecondsToTime(seconds) { var hours = Math.floor(seconds / 3600); @@ -549,3 +622,9 @@ function padTime(i) { return '00'; } } + +function stringToTime(timestring) { + timestring = timestring.split(/:/); + var time = timestring[0] * 3600 + timestring[1] * 60; + return time; +} From 88a1c787d14c6edfe240a4134c949bf8e39e5610 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Tue, 2 Feb 2021 17:18:32 +0100 Subject: [PATCH 06/25] bugfix automatic adjusted endtime --- openebs2/static/js/add_msg.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openebs2/static/js/add_msg.js b/openebs2/static/js/add_msg.js index e89296c..1e824fb 100644 --- a/openebs2/static/js/add_msg.js +++ b/openebs2/static/js/add_msg.js @@ -263,7 +263,7 @@ function checkMessageTime(event, ui) { if (starttime >= endtime) { if ($(this).attr('id') == "id_messagestarttime") { - endtime.setDate(endtime.getDate()+1); + endtime.setDate(starttime.getDate()+1); $("#id_messageendtime").val(formatDate(endtime)); } else { starttime.setDate(endtime.getDate()-1); From caff64f0bf8bb95fa697bdfc707d3c490c094c8a Mon Sep 17 00:00:00 2001 From: baasje85 Date: Tue, 2 Feb 2021 17:19:31 +0100 Subject: [PATCH 07/25] bugfix only check messagetimes on change, not blur --- openebs/templates/openebs/snippet_halte-picker-js.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openebs/templates/openebs/snippet_halte-picker-js.html b/openebs/templates/openebs/snippet_halte-picker-js.html index 9ac50f6..f5d146c 100644 --- a/openebs/templates/openebs/snippet_halte-picker-js.html +++ b/openebs/templates/openebs/snippet_halte-picker-js.html @@ -19,8 +19,8 @@ $('body').on('click', '#id_messagestarttime,#id_messageendtime', function() { $(this).select(); }); -$('body').on('blur', '#id_messagestarttime,#id_messageendtime', calculateTime); -$('body').on('blur', '#id_messagestarttime,#id_messageendtime', checkMessageTime); +$('body').on('change', '#id_messagestarttime,#id_messageendtime', calculateTime); +$('body').on('change', '#id_messagestarttime,#id_messageendtime', checkMessageTime); $('body').on('change', '#id_messagedurationtype_1', function() { hideEndTime(); }); From c831b213153fd41890a41e5582d87416fe764d1e Mon Sep 17 00:00:00 2001 From: baasje85 Date: Tue, 2 Feb 2021 17:31:05 +0100 Subject: [PATCH 08/25] validate add message within .js --- openebs/form.py | 1 - .../openebs/kv15stopmessage_form.html | 6 ++- openebs2/static/js/add_msg.js | 43 +++++++++++++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/openebs/form.py b/openebs/form.py index 95321f9..adc894c 100644 --- a/openebs/form.py +++ b/openebs/form.py @@ -65,7 +65,6 @@ def clean(self): return self.cleaned_data def clean_messagecontent(self): - # Improve: Strip spaces from message if ('messagecontent' not in self.cleaned_data or self.cleaned_data['messagecontent'] is None or len( self.cleaned_data['messagecontent'].strip()) == 0) \ and self.cleaned_data['messagetype'] != 'OVERRULE': diff --git a/openebs/templates/openebs/kv15stopmessage_form.html b/openebs/templates/openebs/kv15stopmessage_form.html index dbc9a27..ea45759 100644 --- a/openebs/templates/openebs/kv15stopmessage_form.html +++ b/openebs/templates/openebs/kv15stopmessage_form.html @@ -29,11 +29,13 @@

{% trans "Bericht" %}

value="{% for halte in object.kv15messagestop_set.all %}{{ halte.stop.dataownercode }}_{{ halte.stop.userstopcode }},{% endfor %}" /> {% endif %} + +
{% crispy form form.helper %}
-
- +
+
diff --git a/openebs2/static/js/add_msg.js b/openebs2/static/js/add_msg.js index 1e824fb..e602c8b 100644 --- a/openebs2/static/js/add_msg.js +++ b/openebs2/static/js/add_msg.js @@ -256,6 +256,49 @@ function writeHaltesWithMessages(data, status) { }); } +function formValidation() { + validationerrors = [] + + // check for empty messagecontent + if ($('#id_messagecontent').val().trim().length == 0) { + validationerrors.push("Bericht mag niet leeg zijn."); + } + + // check if begin- and endtime is filled correctly + var dates = [$('#id_messagestarttime').val().trim(), $('#id_messageendtime').val().trim()] + $.each(dates, function(i, date) { + var dateparts = date.split(' ')[0].split('-'); + if (dateparts.length !== 3 || + dateparts[0].length == 0 || dateparts[0].length > 2 || + dateparts[1].length == 0 || dateparts[1].length > 2 || dateparts[2].length !== 4) { + if (i == 0) { + validationerrors.push("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)") + } else { + validationerrors.push("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)") + } + } + }); + + // check if stops are filled + if ($('#haltes').val().length == 0) { + validationerrors.push("Selecteer minimaal een halte.") + } + + if (validationerrors.length == 0) { + $(".form").submit(); + } else { + if (!$("#error_list").hasClass('hidden')) { + $("#error_list").empty(); + } + $.each(validationerrors, function(i, error) { + $("#error_list").append('

'+error+'

'); + }); + if ($("#error_list").hasClass('hidden')) { + $("#error_list").removeClass('hidden'); + } + } +} + /* TIME FUNCTIONS */ function checkMessageTime(event, ui) { var starttime = parseDate($("#id_messagestarttime").val()); From e4d72a0228d9f6ffdfe911370161af5fd3769215 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Tue, 2 Feb 2021 17:39:25 +0100 Subject: [PATCH 09/25] validate add scenariomessage within .js --- .../openebs/kv15scenariomessage_form.html | 6 ++- openebs2/static/js/add_msg.js | 45 +++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/openebs/templates/openebs/kv15scenariomessage_form.html b/openebs/templates/openebs/kv15scenariomessage_form.html index 539e186..32a0eab 100644 --- a/openebs/templates/openebs/kv15scenariomessage_form.html +++ b/openebs/templates/openebs/kv15scenariomessage_form.html @@ -24,11 +24,13 @@

{% trans "Bericht" %}

+ +
{% crispy form form.helper %}
-
- +
+
diff --git a/openebs2/static/js/add_msg.js b/openebs2/static/js/add_msg.js index e602c8b..5cf2a07 100644 --- a/openebs2/static/js/add_msg.js +++ b/openebs2/static/js/add_msg.js @@ -299,6 +299,51 @@ function formValidation() { } } +function formValidation() { + validationerrors = [] + + // check for empty messagecontent + if ($('#id_messagecontent').val().trim().length == 0) { + validationerrors.push("Bericht mag niet leeg zijn."); + } + var pathname = window.location.pathname; + if (pathname.indexOf('scenario') == -1) { + // check if begin- and endtime is filled correctly + var dates = [$('#id_messagestarttime').val().trim(), $('#id_messageendtime').val().trim()] + $.each(dates, function(i, date) { + var dateparts = date.split(' ')[0].split('-'); + if (dateparts.length !== 3 || + dateparts[0].length == 0 || dateparts[0].length > 2 || + dateparts[1].length == 0 || dateparts[1].length > 2 || dateparts[2].length !== 4) { + if (i == 0) { + validationerrors.push("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)") + } else { + validationerrors.push("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)") + } + } + }); + } + // check if stops are filled + if ($('#haltes').val().length == 0) { + validationerrors.push("Selecteer minimaal een halte.") + } + + if (validationerrors.length == 0) { + $(".form").submit(); + } else { + if (!$("#error_list").hasClass('hidden')) { + $("#error_list").empty(); + } + $.each(validationerrors, function(i, error) { + $("#error_list").append('

'+error+'

'); + }); + if ($("#error_list").hasClass('hidden')) { + $("#error_list").removeClass('hidden'); + } + } +} + + /* TIME FUNCTIONS */ function checkMessageTime(event, ui) { var starttime = parseDate($("#id_messagestarttime").val()); From f8abde4cda5d304292d2fdb81b8df088981571e9 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Tue, 2 Feb 2021 17:43:05 +0100 Subject: [PATCH 10/25] validate update-pages within .js --- openebs/templates/openebs/kv15scenariomessage_update.html | 3 ++- openebs/templates/openebs/kv15stopmessage_update.html | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/openebs/templates/openebs/kv15scenariomessage_update.html b/openebs/templates/openebs/kv15scenariomessage_update.html index e2735d2..1af8dab 100644 --- a/openebs/templates/openebs/kv15scenariomessage_update.html +++ b/openebs/templates/openebs/kv15scenariomessage_update.html @@ -24,12 +24,13 @@

Bericht

+
{% csrf_token %} {% crispy form form.helper %}
- +
diff --git a/openebs/templates/openebs/kv15stopmessage_update.html b/openebs/templates/openebs/kv15stopmessage_update.html index 9aebe22..380bfb3 100644 --- a/openebs/templates/openebs/kv15stopmessage_update.html +++ b/openebs/templates/openebs/kv15stopmessage_update.html @@ -23,6 +23,7 @@

{% trans "Bewerk bericht" %}

+
{% csrf_token %} {% crispy form form.helper %} @@ -33,7 +34,7 @@

{% trans "Bewerk bericht" %}

- +
From d1fb2a215dc9ebfae686efe168e5270e0ab983fa Mon Sep 17 00:00:00 2001 From: baasje85 Date: Wed, 3 Feb 2021 11:43:08 +0100 Subject: [PATCH 11/25] validate add_message with ajax from .js --- openebs/form.py | 55 ----------------------------- openebs/urls.py | 3 +- openebs/views.py | 66 +++++++++++++++++++++++++++++++++-- openebs2/static/js/add_msg.js | 38 +++++++++++++++++--- 4 files changed, 100 insertions(+), 62 deletions(-) diff --git a/openebs/form.py b/openebs/form.py index adc894c..58a79db 100644 --- a/openebs/form.py +++ b/openebs/form.py @@ -15,61 +15,6 @@ class Kv15StopMessageForm(forms.ModelForm): - def clean(self): - # TODO Move _all_ halte parsing here! - - datetimevalidation = [] - try: - datetime.strptime(self.data['messagestarttime'], "%d-%m-%Y %H:%M:%S") - except: - datetimevalidation.append(_("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)")) - pass - - try: - endtime = datetime.strptime(self.data['messageendtime'], "%d-%m-%Y %H:%M:%S") - if not is_aware(endtime): - endtime = make_aware(endtime) - except: - datetimevalidation.append(_("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)")) - pass - - if len(datetimevalidation) == 2: - raise ValidationError(_("Voer een geldige begin- en eindtijd in (dd-mm-jjjj uu:mm:ss)")) - elif len(datetimevalidation) == 1: - raise ValidationError(datetimevalidation[0]) - - current = datetime.now() - if not is_aware(current): - current = make_aware(current) - - valid_ids = [] - nonvalid_ids = [] - for halte in self.data['haltes'].split(','): - halte_split = halte.split('_') - if len(halte_split) == 2: - stop = Kv1Stop.find_stop(halte_split[0], halte_split[1]) - if stop: - valid_ids.append(stop.pk) - else: - nonvalid_ids.append(halte) - - if len(nonvalid_ids) != 0: - log.warning("Ongeldige haltes: %s" % ', '.join(nonvalid_ids)) - if len(valid_ids) == 0 and len(nonvalid_ids) != 0: - raise ValidationError(_("Er werd geen geldige halte geselecteerd.")) - elif len(valid_ids) == 0: - raise ValidationError(_("Selecteer minimaal een halte.")) - elif current > endtime: - raise ValidationError(_("Eindtijd van bericht ligt in het verleden")) - else: - return self.cleaned_data - - def clean_messagecontent(self): - if ('messagecontent' not in self.cleaned_data or self.cleaned_data['messagecontent'] is None or len( - self.cleaned_data['messagecontent'].strip()) == 0) \ - and self.cleaned_data['messagetype'] != 'OVERRULE': - raise ValidationError(_("Bericht mag niet leeg zijn")) - return self.cleaned_data['messagecontent'] class Meta(object): model = Kv15Stopmessage diff --git a/openebs/urls.py b/openebs/urls.py index e1a1b01..980c43d 100644 --- a/openebs/urls.py +++ b/openebs/urls.py @@ -1,7 +1,7 @@ from django.conf.urls import url from django.views.generic import RedirectView from openebs.views import MessageListView, MessageCreateView, MessageDeleteView, MessageUpdateView, ActiveStopsAjaxView, MessageDetailsView, MessageStopsAjaxView, \ - MessageStopsBoundAjaxView, MessageResendView + MessageStopsBoundAjaxView, MessageResendView, MessageValidationAjaxView from openebs.views_change import ChangeListView, ChangeCreateView, ChangeDeleteView, ActiveJourneysAjaxView, \ ChangeUpdateView, ActiveLinesAjaxView from openebs.views_filters import FilterListView, FilterDeleteView, FilterUpdateView, FilterCreateView, \ @@ -28,6 +28,7 @@ url(r'^bericht/(?P\d+)/verwijderen$', MessageDeleteView.as_view(), name="msg_delete"), url(r'^bericht/(?P\d+)/haltes.geojson', MessageStopsAjaxView.as_view(), name="msg_stops_ajax"), # LEGACY: map url(r'^bericht/(?P\d+)/halte_bereik.geojson', MessageStopsBoundAjaxView.as_view(), name="msg_bounds_ajax"), # Map bounds to zoom + url(r'^bericht/validatie.json', MessageValidationAjaxView.as_view(), name="msg_validation"), # This next view is used as URL when adding a message (name is not used) url(r'^bericht/haltes.json', ActiveStopsAjaxView.as_view(), name="active_stops_ajax"), diff --git a/openebs/views.py b/openebs/views.py index ca1f98a..498b165 100644 --- a/openebs/views.py +++ b/openebs/views.py @@ -1,6 +1,6 @@ # Create your views here. import logging -from datetime import timedelta +from datetime import timedelta, datetime from django.contrib.gis.db.models import Extent from django.urls import reverse_lazy @@ -8,7 +8,7 @@ from django.shortcuts import redirect from django.views.generic import ListView, UpdateView, DetailView from django.views.generic.edit import CreateView, DeleteView -from django.utils.timezone import now +from django.utils.timezone import now, is_aware, make_aware from djgeojson.views import GeoJSONLayerView @@ -267,3 +267,65 @@ def get_queryset(self): qry = qry.filter(kv15stopmessage__dataownercode=self.request.user.userprofile.company) return qry + + +class MessageValidationAjaxView(AccessJsonMixin, JSONListResponseMixin, DetailView): + permission_required = 'openebs.add_messages' + model = Kv15Stopmessage + render_object = 'object' + + def get_object(self, **kwargs): + + message_validation = [] + starttime = self.request.GET.get('messagestarttime') + endtime = self.request.GET.get('messageendtime') + messagecontent = self.request.GET.get('messagecontent') + messagetype = self.request.GET.get('messagetype') + haltes = self.request.GET.get('haltes') + + if len(messagecontent.strip()) == 0 and messagetype != 'OVERRULE': + message_validation.append("Bericht mag niet leeg zijn") + + datetimevalidation = [] + try: + datetime.strptime(starttime, "%d-%m-%Y %H:%M:%S") + except: + datetimevalidation.append("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)") + + try: + endtime = datetime.strptime(endtime, "%d-%m-%Y %H:%M:%S") + if not is_aware(endtime): + endtime = make_aware(endtime) + except: + datetimevalidation.append("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)") + + if len(datetimevalidation) == 2: + message_validation.append("Voer een geldige begin- en eindtijd in (dd-mm-jjjj uu:mm:ss)") + elif len(datetimevalidation) == 1: + message_validation.append(datetimevalidation[0]) + + current = datetime.now() + if not is_aware(current): + current = make_aware(current) + + valid_ids = [] + nonvalid_ids = [] + for halte in haltes.split(','): + halte_split = halte.split('_') + if len(halte_split) == 2: + stop = Kv1Stop.find_stop(halte_split[0], halte_split[1]) + if stop: + valid_ids.append(stop.pk) + else: + nonvalid_ids.append(halte) + + if len(nonvalid_ids) != 0: + log.warning("Ongeldige haltes: %s" % ', '.join(nonvalid_ids)) + if len(valid_ids) == 0 and len(nonvalid_ids) != 0: + message_validation.append("Er werd geen geldige halte geselecteerd.") + elif len(valid_ids) == 0: + message_validation.append("Selecteer minimaal een halte.") + elif current > endtime: + message_validation.append("Eindtijd van bericht ligt in het verleden") + + return message_validation diff --git a/openebs2/static/js/add_msg.js b/openebs2/static/js/add_msg.js index 5cf2a07..6dd5ebd 100644 --- a/openebs2/static/js/add_msg.js +++ b/openebs2/static/js/add_msg.js @@ -31,9 +31,11 @@ function writeList(data, status) { $.each(data.object_list, function (i, line) { validIds.push('l'+line.pk) if (!$('#l'+line.pk).length) { - row = ''+line.publiclinenumber+ ''; - row += ''+line.headsign+''; - $(row).hide().appendTo("#rows").fadeIn(200); + if (line.publiclinenumber) { // not all lines with a lineplanningnumber has a publiclinenumber or headsign + row = ''+line.publiclinenumber+ ''; + row += ''+line.headsign+''; + $(row).hide().appendTo("#rows").fadeIn(200); + } } }); @@ -301,7 +303,7 @@ function formValidation() { function formValidation() { validationerrors = [] - + /* // check for empty messagecontent if ($('#id_messagecontent').val().trim().length == 0) { validationerrors.push("Bericht mag niet leeg zijn."); @@ -341,6 +343,34 @@ function formValidation() { $("#error_list").removeClass('hidden'); } } + */ + var pathname = window.location.pathname; + if (pathname.indexOf('scenario') == -1) { + $.ajax({url: '/bericht/validatie.json', + data: {'messagestarttime': $('#id_messagestarttime').val().trim(), + 'messageendtime': $('#id_messageendtime').val().trim(), + 'messagecontent': $('#id_messagecontent').val().trim(), + 'messagetype': $("input[name='messagetype']:checked").val(), + 'haltes': $('#haltes').val(), + }, + success : function(result) { + var validationerrors = result.object; + if (validationerrors.length == 0) { + $(".form").submit(); + } else { + if (!$("#error_list").hasClass('hidden')) { + $("#error_list").empty(); + } + $.each(validationerrors, function(i, error) { + $("#error_list").append('

'+error+'

'); + }); + if ($("#error_list").hasClass('hidden')) { + $("#error_list").removeClass('hidden'); + } + } + } + }); + } // TODO: else validate scenariomessage } From 7016e32d3d996f683ed29a22b65c3f75947bb143 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Wed, 3 Feb 2021 13:55:23 +0100 Subject: [PATCH 12/25] validate add_scenario_message with ajax from .js --- openebs/views.py | 49 +++++++++---------- openebs2/static/js/add_msg.js | 88 +++++++++++------------------------ 2 files changed, 51 insertions(+), 86 deletions(-) diff --git a/openebs/views.py b/openebs/views.py index 498b165..e3f4f1b 100644 --- a/openebs/views.py +++ b/openebs/views.py @@ -277,8 +277,6 @@ class MessageValidationAjaxView(AccessJsonMixin, JSONListResponseMixin, DetailVi def get_object(self, **kwargs): message_validation = [] - starttime = self.request.GET.get('messagestarttime') - endtime = self.request.GET.get('messageendtime') messagecontent = self.request.GET.get('messagecontent') messagetype = self.request.GET.get('messagetype') haltes = self.request.GET.get('haltes') @@ -286,27 +284,32 @@ def get_object(self, **kwargs): if len(messagecontent.strip()) == 0 and messagetype != 'OVERRULE': message_validation.append("Bericht mag niet leeg zijn") - datetimevalidation = [] - try: - datetime.strptime(starttime, "%d-%m-%Y %H:%M:%S") - except: - datetimevalidation.append("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)") - - try: - endtime = datetime.strptime(endtime, "%d-%m-%Y %H:%M:%S") - if not is_aware(endtime): - endtime = make_aware(endtime) - except: - datetimevalidation.append("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)") - - if len(datetimevalidation) == 2: - message_validation.append("Voer een geldige begin- en eindtijd in (dd-mm-jjjj uu:mm:ss)") - elif len(datetimevalidation) == 1: - message_validation.append(datetimevalidation[0]) + if hasattr(self.request.GET, 'messagestarttime'): + starttime = self.request.GET.get('messagestarttime') + endtime = self.request.GET.get('messageendtime') + datetimevalidation = [] + try: + datetime.strptime(starttime, "%d-%m-%Y %H:%M:%S") + except: + datetimevalidation.append("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)") - current = datetime.now() - if not is_aware(current): - current = make_aware(current) + try: + endtime = datetime.strptime(endtime, "%d-%m-%Y %H:%M:%S") + if not is_aware(endtime): + endtime = make_aware(endtime) + except: + datetimevalidation.append("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)") + + if len(datetimevalidation) == 2: + message_validation.append("Voer een geldige begin- en eindtijd in (dd-mm-jjjj uu:mm:ss)") + elif len(datetimevalidation) == 1: + message_validation.append(datetimevalidation[0]) + + current = datetime.now() + if not is_aware(current): + current = make_aware(current) + if current > endtime: + message_validation.append("Eindtijd van bericht ligt in het verleden") valid_ids = [] nonvalid_ids = [] @@ -325,7 +328,5 @@ def get_object(self, **kwargs): message_validation.append("Er werd geen geldige halte geselecteerd.") elif len(valid_ids) == 0: message_validation.append("Selecteer minimaal een halte.") - elif current > endtime: - message_validation.append("Eindtijd van bericht ligt in het verleden") return message_validation diff --git a/openebs2/static/js/add_msg.js b/openebs2/static/js/add_msg.js index 6dd5ebd..11142fc 100644 --- a/openebs2/static/js/add_msg.js +++ b/openebs2/static/js/add_msg.js @@ -303,74 +303,38 @@ function formValidation() { function formValidation() { validationerrors = [] - /* - // check for empty messagecontent - if ($('#id_messagecontent').val().trim().length == 0) { - validationerrors.push("Bericht mag niet leeg zijn."); - } + var pathname = window.location.pathname; if (pathname.indexOf('scenario') == -1) { - // check if begin- and endtime is filled correctly - var dates = [$('#id_messagestarttime').val().trim(), $('#id_messageendtime').val().trim()] - $.each(dates, function(i, date) { - var dateparts = date.split(' ')[0].split('-'); - if (dateparts.length !== 3 || - dateparts[0].length == 0 || dateparts[0].length > 2 || - dateparts[1].length == 0 || dateparts[1].length > 2 || dateparts[2].length !== 4) { - if (i == 0) { - validationerrors.push("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)") - } else { - validationerrors.push("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)") - } - } - }); - } - // check if stops are filled - if ($('#haltes').val().length == 0) { - validationerrors.push("Selecteer minimaal een halte.") - } - - if (validationerrors.length == 0) { - $(".form").submit(); + validationdata = {'messagestarttime': $('#id_messagestarttime').val().trim(), + 'messageendtime': $('#id_messageendtime').val().trim(), + 'messagecontent': $('#id_messagecontent').val().trim(), + 'messagetype': $("input[name='messagetype']:checked").val(), + 'haltes': $('#haltes').val()} } else { - if (!$("#error_list").hasClass('hidden')) { - $("#error_list").empty(); - } - $.each(validationerrors, function(i, error) { - $("#error_list").append('

'+error+'

'); - }); - if ($("#error_list").hasClass('hidden')) { - $("#error_list").removeClass('hidden'); - } + validationdata = {'messagecontent': $('#id_messagecontent').val().trim(), + 'messagetype': $("input[name='messagetype']:checked").val(), + 'haltes': $('#haltes').val()} } - */ - var pathname = window.location.pathname; - if (pathname.indexOf('scenario') == -1) { - $.ajax({url: '/bericht/validatie.json', - data: {'messagestarttime': $('#id_messagestarttime').val().trim(), - 'messageendtime': $('#id_messageendtime').val().trim(), - 'messagecontent': $('#id_messagecontent').val().trim(), - 'messagetype': $("input[name='messagetype']:checked").val(), - 'haltes': $('#haltes').val(), - }, - success : function(result) { - var validationerrors = result.object; - if (validationerrors.length == 0) { - $(".form").submit(); - } else { - if (!$("#error_list").hasClass('hidden')) { - $("#error_list").empty(); - } - $.each(validationerrors, function(i, error) { - $("#error_list").append('

'+error+'

'); - }); - if ($("#error_list").hasClass('hidden')) { - $("#error_list").removeClass('hidden'); - } + $.ajax({url: '/bericht/validatie.json', + data: validationdata, + success : function(result) { + var validationerrors = result.object; + if (validationerrors.length == 0) { + $(".form").submit(); + } else { + if (!$("#error_list").hasClass('hidden')) { + $("#error_list").empty(); + } + $.each(validationerrors, function(i, error) { + $("#error_list").append('

'+error+'

'); + }); + if ($("#error_list").hasClass('hidden')) { + $("#error_list").removeClass('hidden'); } } - }); - } // TODO: else validate scenariomessage + } + }); } From 7ba3d67491e572de901e9a8c07f81276db10d698 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Wed, 3 Feb 2021 15:33:48 +0100 Subject: [PATCH 13/25] small improvements in add_msg_journey.js --- openebs2/static/js/add_msg_journey.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/openebs2/static/js/add_msg_journey.js b/openebs2/static/js/add_msg_journey.js index 5b609a4..24f36a1 100644 --- a/openebs2/static/js/add_msg_journey.js +++ b/openebs2/static/js/add_msg_journey.js @@ -154,7 +154,8 @@ function writeTrips(data, status) { tripSelection = data.object.trips_1.concat(data.object.trips_2); maxLen = Math.max(data.object.trips_1.length, data.object.trips_2.length); if (maxLen > 0) { - $('#trips tbody').fadeOut(100).empty(); + $('#trips tbody').fadeOut(100); + $('#trips tr').not('.help').remove(); tripRows = null; for (i = 0; i <= maxLen; i = i + 1) { a = null; @@ -168,6 +169,7 @@ function writeTrips(data, status) { $('#trips tbody').hide().append(tripRows); $('#trips thead').fadeIn(200); $('#trips tbody').fadeIn(200); + $('#trips tr.help').hide(); $("#all_journeys").removeAttr('disabled'); } else { $('#trips thead').hide(); @@ -375,6 +377,7 @@ function removeLineFromX(event, ui) { $('#rit-list .help').show(); $('#trips thead').show(); $('#trips tbody').show(); + $('#trips tr.help').show(); } else { lijnnr =$(this).parent().attr('id').replace('st', ''); //remove from selectTripMeasures & allTrips @@ -402,6 +405,10 @@ function removeLineFromX(event, ui) { removeLine($(this).parent().attr('id').substring(2)); colorSelectedRange(); } + if ($('#lines').val().length == 0) { + $('#div_id_begintime_part').addClass('hidden'); + $('#div_id_endtime_part').addClass('hidden'); + } } function removeLine(lijn) { @@ -447,7 +454,7 @@ function selectAllLines() { $('#div_id_begintime_part').removeClass('hidden'); $('#div_id_endtime_part').removeClass('hidden'); } - $('#trips tbody tr').remove(); + $('#trips tr').not('.help').remove(); $('.rit-overzicht').css("display","none"); $('#trips thead').hide(); $('#trips tbody').hide(); From 7e00092c1537ae4899f4436ea7c6f510425a809c Mon Sep 17 00:00:00 2001 From: baasje85 Date: Wed, 3 Feb 2021 15:36:18 +0100 Subject: [PATCH 14/25] validate add_change with ajax from .js --- openebs/form_kv17.py | 131 ------------------------- openebs/urls.py | 3 +- openebs/views_change.py | 133 +++++++++++++++++++++++++- openebs2/static/js/add_msg_journey.js | 94 +++++------------- 4 files changed, 158 insertions(+), 203 deletions(-) diff --git a/openebs/form_kv17.py b/openebs/form_kv17.py index f7df1db..9a95f29 100644 --- a/openebs/form_kv17.py +++ b/openebs/form_kv17.py @@ -33,137 +33,6 @@ class Kv17ChangeForm(forms.ModelForm): advicecontent = forms.CharField(max_length=255, label=_("Uitleg advies"), required=False, widget=forms.Textarea(attrs={'cols': 40, 'rows': 4, 'class': 'col-lg-6'})) - def clean(self): # should be redundant after jquery filter in html-form, but just in case - cleaned_data = super(Kv17ChangeForm, self).clean() - operatingday = parse_date(self.data['operatingday']) - if operatingday is None: - raise ValidationError(_("Er staan geen ritten in de database")) - - if 'journeys' not in self.data: - raise ValidationError(_("Een of meer geselecteerde ritten zijn ongeldig")) - - if self.data['begintime_part'] != '': - hh, mm = self.data['begintime_part'].split(':') - begintime = make_aware(datetime.combine(operatingday, time(int(hh), int(mm)))) - else: - begintime = None - - if self.data['endtime_part'] != '': - hh_e, mm_e = self.data['endtime_part'].split(':') - endtime = make_aware(datetime.combine(operatingday, time(int(hh_e), int(mm_e)))) - if begintime: - if begintime > endtime: # if endtime before begintime - endtime = endtime + timedelta(days=1) # endtime is next day - if endtime.time() >= time(6, 0): # and after 6 am: validation error - raise ValidationError(_("Eindtijd valt op volgende operationele dag")) - else: - endtime = None - - dataownercode = self.user.userprofile.company - if 'Alle ritten' in self.data['journeys']: - valid_journeys = self.clean_all_journeys(operatingday, dataownercode, begintime, endtime) - elif 'Hele vervoerder' in self.data['lines']: - valid_journeys = self.clean_all_lines(operatingday, dataownercode, begintime, endtime) - else: - valid_journeys = self.clean_journeys(operatingday, dataownercode) - - if valid_journeys == 0: - raise ValidationError(_("Er zijn geen ritten geselecteerd om op te heffen")) - - return cleaned_data - - def clean_journeys(self, operatingday, dataownercode): - valid_journeys = 0 - if self.data['journeys'] != '': - for journey in self.data['journeys'].split(',')[0:-1]: - journey_qry = Kv1Journey.objects.filter(dataownercode=dataownercode, pk=journey, dates__date=operatingday) - if journey_qry.count() == 0: - raise ValidationError(_("Een of meer geselecteerde ritten zijn ongeldig")) - - # delete recovered if query is the same. - Kv17Change.objects.filter(dataownercode=dataownercode, journey__pk=journey, line=journey_qry[0].line, - operatingday=operatingday, is_recovered=True).delete() - - else: - raise ValidationError(_("Er werd geen rit geselecteerd.")) - - valid_journeys += 1 - - return valid_journeys - - def clean_all_journeys(self, operatingday, dataownercode, begintime, endtime): - valid_journeys = 0 - - if 'lines' in self.data: - if self.data['lines'] != '': - for line in self.data['lines'].split(',')[0:-1]: - line_qry = Kv1Line.objects.filter(pk=line) - - if line_qry.count() == 0: - raise ValidationError(_("Geen lijn gevonden.")) - - database_alljourneys = Kv17Change.objects.filter(dataownercode=dataownercode, - is_alljourneysofline=True, line=line_qry[0], - operatingday=operatingday, is_recovered=False) - - database_alllines = Kv17Change.objects.filter(dataownercode=dataownercode, - is_alllines=True, operatingday=operatingday, - is_recovered=False) - - # delete recovered if query is the same. - Kv17Change.objects.filter(dataownercode=dataownercode, is_alljourneysofline=True, line=line_qry[0], - operatingday=operatingday, begintime=begintime, endtime=endtime, - is_recovered=True).delete() - - if operatingday == datetime.today().date(): - begintime = make_aware(datetime.now()) if begintime is None else begintime - else: - begintime = make_aware(datetime.combine(operatingday, time((int(4))))) \ - if begintime is None else begintime - - if database_alllines: - if database_alllines.filter(Q(endtime__gt=begintime) | Q(endtime=None), - Q(begintime__lte=begintime) | Q(begintime=None)): - raise ValidationError(_( - "De gehele vervoerder is al aangepast voor de aangegeven ingangstijd.")) - - elif database_alljourneys: - if database_alljourneys.filter(Q(endtime__gt=begintime) | Q(endtime=None), - Q(begintime__lte=begintime) | Q(begintime=None)): - raise ValidationError(_( - "Een of meer geselecteerde lijnen zijn al aangepast voor de aangegeven ingangstijd.")) - else: - raise ValidationError(_("Geen geldige lijn geselecteerd")) - - valid_journeys += 1 - - return valid_journeys - - def clean_all_lines(self, operatingday, dataownercode, begintime, endtime): - valid_journeys = 0 - - database_alllines = Kv17Change.objects.filter(dataownercode=dataownercode, is_alllines=True, - operatingday=operatingday, is_recovered=False) - - # delete recovered if query is the same. - Kv17Change.objects.filter(dataownercode=dataownercode, is_alllines=True, is_recovered=True, - operatingday=operatingday, begintime=begintime, endtime=endtime).delete() - - if database_alllines: - if operatingday == datetime.today().date(): - begintime = make_aware(datetime.now()) if begintime is None else begintime - else: - begintime = make_aware(datetime.combine(operatingday, time((int(4))))) \ - if begintime is None else begintime - - if database_alllines.filter(Q(endtime__gt=begintime) | Q(endtime=None), - Q(begintime__lte=begintime) | Q(begintime=None)): - raise ValidationError(_("De ingangstijd valt al binnen een geplande operatie.")) - - valid_journeys += 1 - - return valid_journeys - def save(self, force_insert=False, force_update=False, commit=True): ''' Save each of the journeys in the model. This is a disaster, we return the XML TODO: Figure out a better solution fo this! ''' diff --git a/openebs/urls.py b/openebs/urls.py index 980c43d..cddf0e3 100644 --- a/openebs/urls.py +++ b/openebs/urls.py @@ -3,7 +3,7 @@ from openebs.views import MessageListView, MessageCreateView, MessageDeleteView, MessageUpdateView, ActiveStopsAjaxView, MessageDetailsView, MessageStopsAjaxView, \ MessageStopsBoundAjaxView, MessageResendView, MessageValidationAjaxView from openebs.views_change import ChangeListView, ChangeCreateView, ChangeDeleteView, ActiveJourneysAjaxView, \ - ChangeUpdateView, ActiveLinesAjaxView + ChangeUpdateView, ActiveLinesAjaxView, ChangeValidationAjaxView from openebs.views_filters import FilterListView, FilterDeleteView, FilterUpdateView, FilterCreateView, \ FilterStopCreateView, FilterStopDeleteView from openebs.views_generic import ChangeCompanyView, TemplateRequestView @@ -53,6 +53,7 @@ url(r'^ritaanpassing/(?P\d+)/herstellen', ChangeUpdateView.as_view(), name="change_redo"), url(r'^ritaanpassing/ritten.json$', ActiveJourneysAjaxView.as_view(), name="active_journeys_ajax"), url(r'^ritaanpassing/lijnen.json$', ActiveLinesAjaxView.as_view(), name="active_lines_ajax"), + url(r'^ritaanpassing/validatie.json', ChangeValidationAjaxView.as_view(), name="change_validation"), url(r'^vervoerder/wijzig', ChangeCompanyView.as_view(), name="company_change"), url(r'^vervoerder/filter/halte/nieuw', FilterStopCreateView.as_view(), name="filter_stop_add"), diff --git a/openebs/views_change.py b/openebs/views_change.py index 10e68ad..af8954f 100644 --- a/openebs/views_change.py +++ b/openebs/views_change.py @@ -1,10 +1,10 @@ import logging -from datetime import timedelta, datetime +from datetime import timedelta, datetime, time from django.urls import reverse_lazy from django.db.models import Q from django.http import HttpResponseRedirect from django.views.generic import ListView, CreateView, DeleteView, DetailView -from kv1.models import Kv1Journey +from kv1.models import Kv1Journey, Kv1Line from openebs.form_kv17 import Kv17ChangeForm from openebs.models import Kv17Change from openebs.views_push import Kv17PushMixin @@ -12,7 +12,8 @@ from utils.time import get_operator_date, get_operator_date_aware from utils.views import AccessMixin, JSONListResponseMixin, AccessJsonMixin from django.utils.dateparse import parse_date -from django.utils.timezone import now +from django.utils.timezone import now, make_aware + log = logging.getLogger('openebs.views.changes') @@ -228,3 +229,129 @@ def get_object(self): 'all_lines': x['is_alllines']} for x in queryset.values('line', 'begintime', 'endtime', 'dataownercode', 'is_alljourneysofline', 'is_alllines')) + + +class ChangeValidationAjaxView(AccessJsonMixin, JSONListResponseMixin, DetailView): + permission_required = 'openebs.add_change' + model = Kv17Change + render_object = 'object' + + def get_object(self): # should be redundant after jquery filter in html-form, but just in case + change_validation = [] + operatingday = parse_date(self.request.GET.get('operatingday')) + journeys = self.request.GET.get('journeys') + lines = self.request.GET.get('lines') + begintime_part = self.request.GET.get('begintime') + endtime_part = self.request.GET.get('endtime') + + if operatingday is None: + change_validation.append("Er staan geen ritten in de database") + + if begintime_part != '': + hh, mm = begintime_part.split(':') + begintime = make_aware(datetime.combine(operatingday, time(int(hh), int(mm)))) + else: + begintime = None + + if endtime_part != '': + hh_e, mm_e = endtime_part.split(':') + endtime = make_aware(datetime.combine(operatingday, time(int(hh_e), int(mm_e)))) + if begintime: + if begintime > endtime: # if endtime before begintime + endtime = endtime + timedelta(days=1) # endtime is next day + if endtime.time() >= time(6, 0): # and after 6 am: validation error + change_validation.append("Eindtijd valt op volgende operationele dag") + else: + endtime = None + + dataownercode = self.request.user.userprofile.company + if 'Alle ritten' in journeys: + change_validation = self.clean_all_journeys(operatingday, dataownercode, lines, begintime, endtime, + change_validation) + elif 'Hele vervoerder' in lines: + change_validation = self.clean_all_lines(operatingday, dataownercode, begintime, endtime, change_validation) + else: + change_validation = self.clean_journeys(operatingday, dataownercode, journeys, change_validation) + + return change_validation + + def clean_journeys(self, operatingday, dataownercode, journeys, change_validation): + valid_journeys = 0 + if journeys != '': + for journey in journeys.split(',')[0:-1]: + journey_qry = Kv1Journey.objects.filter(dataownercode=dataownercode, pk=journey, dates__date=operatingday) + if journey_qry.count() == 0: + change_validation.append("Een of meer geselecteerde ritten zijn ongeldig") + else: + valid_journeys += 1 + + # delete recovered if query is the same. + Kv17Change.objects.filter(dataownercode=dataownercode, journey__pk=journey, line=journey_qry[0].line, + operatingday=operatingday, is_recovered=True).delete() + if valid_journeys == 0: + change_validation.append("Er zijn geen ritten geselecteerd om op te heffen") + + return change_validation + + def clean_all_journeys(self, operatingday, dataownercode, lines, begintime, endtime, change_validation): + if lines != '': + for line in lines.split(',')[0:-1]: + line_qry = Kv1Line.objects.filter(pk=line) + + if line_qry.count() == 0: + change_validation.append("Geen lijn gevonden.") + continue + + database_alljourneys = Kv17Change.objects.filter(dataownercode=dataownercode, + is_alljourneysofline=True, line=line_qry[0], + operatingday=operatingday, is_recovered=False) + + database_alllines = Kv17Change.objects.filter(dataownercode=dataownercode, + is_alllines=True, operatingday=operatingday, + is_recovered=False) + + # delete recovered if query is the same. + Kv17Change.objects.filter(dataownercode=dataownercode, is_alljourneysofline=True, line=line_qry[0], + operatingday=operatingday, begintime=begintime, endtime=endtime, + is_recovered=True).delete() + + if operatingday == datetime.today().date(): + begintime = make_aware(datetime.now()) if begintime is None else begintime + else: + begintime = make_aware(datetime.combine(operatingday, time((int(4))))) \ + if begintime is None else begintime + + if database_alllines: + if database_alllines.filter(Q(endtime__gt=begintime) | Q(endtime=None), + Q(begintime__lte=begintime) | Q(begintime=None)): + change_validation.append( + "De gehele vervoerder is al aangepast voor de aangegeven ingangstijd.") + + elif database_alljourneys: + if database_alljourneys.filter(Q(endtime__gt=begintime) | Q(endtime=None), + Q(begintime__lte=begintime) | Q(begintime=None)): + change_validation.append( + "Een of meer geselecteerde lijnen zijn al aangepast voor de aangegeven ingangstijd.") + + return change_validation + + def clean_all_lines(self, operatingday, dataownercode, begintime, endtime, change_validation): + database_alllines = Kv17Change.objects.filter(dataownercode=dataownercode, is_alllines=True, + operatingday=operatingday, is_recovered=False) + + # delete recovered if query is the same. + Kv17Change.objects.filter(dataownercode=dataownercode, is_alllines=True, is_recovered=True, + operatingday=operatingday, begintime=begintime, endtime=endtime).delete() + + if database_alllines: + if operatingday == datetime.today().date(): + begintime = make_aware(datetime.now()) if begintime is None else begintime + else: + begintime = make_aware(datetime.combine(operatingday, time((int(4))))) \ + if begintime is None else begintime + + if database_alllines.filter(Q(endtime__gt=begintime) | Q(endtime=None), + Q(begintime__lte=begintime) | Q(begintime=None)): + change_validation.append("De ingangstijd valt al binnen een geplande operatie.") + + return change_validation diff --git a/openebs2/static/js/add_msg_journey.js b/openebs2/static/js/add_msg_journey.js index 24f36a1..c068297 100644 --- a/openebs2/static/js/add_msg_journey.js +++ b/openebs2/static/js/add_msg_journey.js @@ -535,76 +535,34 @@ function changeOfRange() { } function formValidation() { - // check if operatingday is filled - validationerrors = [] - operatingday = $('#id_operatingday').val(); - if (operatingday === null) { - validationerrors.push("Er staan geen ritten in de database.") - } - // check if journeys are filled - if ($('#lines').val().length == 0 && $('#journeys').val().length == 0) { - validationerrors.push("Er zijn geen ritten geselecteerd om op te heffen.") - } else if ($('#lines').val().length !== 0) { - var begintime = null; - var endtime = null; - if ($('#id_begintime_part').val().length !== 0) { - begintime = stringToTime($('#id_begintime_part').val()); - } - if ($('#id_endtime_part').val().length !== 0) { - endtime = stringToTime($('#id_endtime_part').val()); - } - - if (begintime !== null && endtime !== null) { - if (endtime >= 25200 && endtime < begintime) { - validationerrors.push("Eindtijd valt op volgende operationele dag.") - } - } - var is_active = 0; - $.each(selectedLines, function(i, line_id) { - if (line_id == 'Hele vervoerder') { - line_id = null; - } - check_results = check_for_active_lines(line_id, begintime, endtime); - if (check_results !== 0) { - is_active += 1; - } - }); - if (is_active > 0) { - validationerrors.push("De ingangstijd valt al binnen een geplande operatie."); - } - } - - if (validationerrors.length == 0) { - $(".form").submit(); - } else { - if (!$("#error_list").hasClass('hidden')) { - $("#error_list").empty(); - } - $.each(validationerrors, function(i, error) { - $("#error_list").append('

'+error+'

'); - }); - if ($("#error_list").hasClass('hidden')) { - $("#error_list").removeClass('hidden'); - } - } -} - -function check_for_active_lines(line_id, begintime, endtime) { - count = 0; - cancelledLines.filter(measure => { - if (measure.id === line_id || measure.id === null) { - if (measure.begintime === null && measure.endtime === null) { - count += 1; - } else if (measure.begintime === null && measure.endtime > begintime) { - count += 1; - } else if (measure.begintime <= begintime && measure.endtime === null) { - count += 1; - } else if (measure.begintime <= begintime && measure.endtime >= begintime) { - count += 1; + $.ajax({url: '/ritaanpassing/validatie.json', + data: {'operatingday': $('#id_operatingday').val(), + 'lines': $('#lines').val(), + 'journeys': $('#journeys').val(), + 'begintime': $('#id_begintime_part').val(), + 'endtime': $('#id_endtime_part').val(), + }, + success : function(result) { + var validationerrors = result.object; + if (validationerrors.length == 0) { + $(".form").submit(); + } else { + if (validationerrors.length == 0) { + $(".form").submit(); + } else { + if (!$("#error_list").hasClass('hidden')) { + $("#error_list").empty(); + } + $.each(validationerrors, function(i, error) { + $("#error_list").append('

'+error+'

'); + }); + if ($("#error_list").hasClass('hidden')) { + $("#error_list").removeClass('hidden'); + } + } + } } - } }); - return count; } /* TIME FUNCTIONS */ From 04e3b5261968ccadb8fdd07dbe8f861129430be9 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Wed, 3 Feb 2021 17:47:53 +0100 Subject: [PATCH 15/25] stops with active messages now blocked within messagetime window --- .../openebs/snippet_halte-picker-js.html | 1 + openebs/views.py | 14 +- openebs2/static/css/site.css | 3 + openebs2/static/js/add_msg.js | 121 ++++++++++++++++-- 4 files changed, 122 insertions(+), 17 deletions(-) diff --git a/openebs/templates/openebs/snippet_halte-picker-js.html b/openebs/templates/openebs/snippet_halte-picker-js.html index f5d146c..579087c 100644 --- a/openebs/templates/openebs/snippet_halte-picker-js.html +++ b/openebs/templates/openebs/snippet_halte-picker-js.html @@ -21,6 +21,7 @@ }); $('body').on('change', '#id_messagestarttime,#id_messageendtime', calculateTime); $('body').on('change', '#id_messagestarttime,#id_messageendtime', checkMessageTime); +$('body').on('change', '#id_messagestarttime,#id_messageendtime', showStopsOnChange); $('body').on('change', '#id_messagedurationtype_1', function() { hideEndTime(); }); diff --git a/openebs/views.py b/openebs/views.py index e3f4f1b..b514af5 100644 --- a/openebs/views.py +++ b/openebs/views.py @@ -225,13 +225,21 @@ class ActiveStopsAjaxView(AccessJsonMixin, JSONListResponseMixin, DetailView): def get_object(self, **kwargs): # Note, can't set this on the view, because it triggers the queryset cache - queryset = self.model.objects.filter(messages__stopmessage__messagestarttime__lte=now(), - messages__stopmessage__messageendtime__gte=now(), + queryset = self.model.objects.filter(#messages__stopmessage__messagestarttime__lte=now(), + Q(messages__stopmessage__messageendtime__gte=now()) | + Q(messages__stopmessage__messageendtime=None), messages__stopmessage__isdeleted=False, # These two are double, but just in case messages__stopmessage__dataownercode=self.request.user.userprofile.company, dataownercode=self.request.user.userprofile.company).distinct() - return list(queryset.values('dataownercode', 'userstopcode')) + return list({'dataownercode': x['dataownercode'], + 'userstopcode': x['userstopcode'], + 'starttime': int(x['messages__stopmessage__messagestarttime'].timestamp()), + 'endtime': int(x['messages__stopmessage__messageendtime'].timestamp()) if + x['messages__stopmessage__messageendtime'] is not None else None, + 'message': x['messages__stopmessage__messagecontent']} for x in + queryset.values('dataownercode', 'userstopcode', 'messages__stopmessage__messagestarttime', + 'messages__stopmessage__messageendtime', 'messages__stopmessage__messagecontent')) class MessageStopsAjaxView(AccessJsonMixin, GeoJSONLayerView): diff --git a/openebs2/static/css/site.css b/openebs2/static/css/site.css index eecad04..bb4b455 100644 --- a/openebs2/static/css/site.css +++ b/openebs2/static/css/site.css @@ -232,3 +232,6 @@ span.stop-selection,span.trip-selection{ margin-bottom: 15px; } +.msg_warning { + background-color: #fcf8e3; +} diff --git a/openebs2/static/js/add_msg.js b/openebs2/static/js/add_msg.js index 11142fc..85187de 100644 --- a/openebs2/static/js/add_msg.js +++ b/openebs2/static/js/add_msg.js @@ -2,6 +2,8 @@ var selectedStops = [] var scenarioStops = [] var blockedStops = [] /* Already have messages set */ +var messageData = [] /* all info from blocked stops */ +var activeLine = null /* lineplanningnumber */ function changeSearch(event) { if ($("#line_search").val().length > 0) { @@ -58,14 +60,18 @@ function showStops(event) { } function selectStop(event, ui) { - $('#halte-list .help').remove() + var stop_id = $(ui.selected).attr('id').slice(1,-1); + if ($.inArray(stop_id, blockedStops) != -1 & $('#id_messagetype_3').parent().hasClass('active') === false) { // if blocked and no OVERRULE + return + } if (doSelectStop(ui.selected)) { + $('#halte-list .help').addClass('hidden'); writeHaltesField(); } } function selectStopFromBall(obj) { - $('#halte-list .help').remove() + $('#halte-list .help').addClass('hidden'); var did = false var parent = $(this).parents('.stopRow'); var left = $(parent).find(".stop-left"); @@ -85,6 +91,7 @@ function selectStopFromBall(obj) { } function selectAllVisibleStops() { + $('#halte-list .help').addClass('hidden'); $('#stops .stop').each(function(index, value) { /* Check this is not already selected */ index = $(this).attr('id').slice(0, -1); @@ -166,13 +173,19 @@ function removeStop(id) { $("#s"+id).remove(); $("#"+id+"l, #"+id+"r").removeClass('success') $("#"+id+"l .stop-check, #"+id+"r .stop-check").remove() + if (selectedStops.length == 0) { + $('#halte-list .help').removeClass('hidden'); + } writeHaltesField() } } function writeLine(data, status) { + //$('#stops').removeClass('msg_warning'); $('#stops').fadeOut(100).empty(); out = "" + blockedStops = []; + $.each(data.object.stop_map, function (i, stop) { out += renderRow(stop) }); @@ -182,6 +195,21 @@ function writeLine(data, status) { } function renderRow(row) { + var pathname = window.location.pathname; + if (pathname.indexOf('scenario') == -1) { + var currentStopMeasures = []; + var messagestarttime = epoch(parseDate($('#id_messagestarttime').val())); + var messageendtime = epoch(parseDate($('#id_messageendtime').val())); + + messageData.filter(measure => { + if (measure.starttime <= messagestarttime) { + if (measure.endtime >= messagestarttime || measure.endtime === null) { + stop = measure.dataownercode + '_' + measure.userstopcode; + currentStopMeasures.push([stop, measure.starttime, measure.endtime, measure.message]); + } + } + }); + } out = ''; if (row.left != null) { if ($.inArray(row.left.id, scenarioStops) != -1) { @@ -191,11 +219,24 @@ function renderRow(row) { if ($.inArray('s'+row.left.id, selectedStops) != -1) { out += ''+row.left.name+' ' } else { - out += ''+row.left.name; - if ($.inArray(row.left.id, blockedStops) != -1) { - out += '' + var pathname = window.location.pathname; + if (pathname.indexOf('scenario') == -1) { + var selected = currentStopMeasures.filter(message => message[0] === row.left.id); + if (selected.length > 0) { + out += ''+row.left.name; + out += ''; + blockedStops.push(row.left.id); + } else { + out += ''+row.left.name; + } + out += ''; + } else { + out += ''+row.left.name; + if ($.inArray(row.left.id, blockedStops) != -1) { + out += '' + } + out += ''; } - out += ''; } } } else { @@ -216,11 +257,24 @@ function renderRow(row) { if ($.inArray('s'+row.right.id, selectedStops) != -1) { out += ''+row.right.name+' '; } else { - out += ''+row.right.name; - if ($.inArray(row.right.id, blockedStops) != -1) { - out += '' + var pathname = window.location.pathname; + if (pathname.indexOf('scenario') == -1) { + var selected = currentStopMeasures.filter(message => message[0] === row.right.id); + if (selected.length > 0) { + out += ''+row.right.name; + out += '' + blockedStops.push(row.right.id); + } else { + out += ''+row.right.name; + } + out += ''; + } else { + out += ''+row.right.name; + if ($.inArray(row.right.id, blockedStops) != -1) { + out += '' + } + out += ''; } - out += ''; } } } else { @@ -252,10 +306,11 @@ function getHaltesWithMessages() { } function writeHaltesWithMessages(data, status) { - $.each(data.object, function (i, halte) { - stop = halte['dataownercode']+ '_' + halte['userstopcode'] - blockedStops.push(stop) - }); + messageData = data.object; + //$.each(data.object, function (i, halte) { + // stop = halte['dataownercode']+ '_' + halte['userstopcode'] + // blockedStops.push(stop) + //}); } function formValidation() { @@ -337,6 +392,40 @@ function formValidation() { }); } +function showStopsOnChange() { + $('.stopRow span').remove(); + $('.stop').removeClass('msg_warning'); + blockedStops = []; + if (messageData.length > 0) { + const filtered = messageData.filter(message => { + start_epoch = epoch(parseDate($('#id_messagestarttime').val())); + end_epoch = epoch(parseDate($('#id_messageendtime').val())); + if (message.starttime <= start_epoch) { + if (message.endtime >= start_epoch || message.endtime === null) { + return true + } + } + }); + var stops = []; + if (filtered.length > 0) { + filtered.filter(message => { + if ($.inArray(message.userstopcode, stops) == -1) { + stops.push(message.userstopcode); + blockedStops.push(message.dataownercode+"_"+message.userstopcode); + } + }); + + $.each(stops, function(i, stop) { + $('[id*='+stop+']').addClass('msg_warning') + $('[id*='+stop+']').append(''); + }); + } + } + //filterCurrentHalteList(); + $('.stopRow td.success').append(' '); + writeHaltesField(); + +} /* TIME FUNCTIONS */ function checkMessageTime(event, ui) { @@ -436,4 +525,8 @@ function showEndTime() { enddate.setDate(enddate.getDate()+1); $('#id_messageendtime').val(formatDate(enddate)); +} + +function epoch(date) { + return Date.parse(date) / 1000; } \ No newline at end of file From 323a1c5fe948ae2166f944b5ef0578756c7cfa47 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Wed, 3 Feb 2021 17:52:09 +0100 Subject: [PATCH 16/25] small improvement. Only one visible warning-sign on journey --- openebs2/static/js/add_msg_journey.js | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/openebs2/static/js/add_msg_journey.js b/openebs2/static/js/add_msg_journey.js index c068297..2202654 100644 --- a/openebs2/static/js/add_msg_journey.js +++ b/openebs2/static/js/add_msg_journey.js @@ -210,20 +210,19 @@ function renderTripCell(trip) { } }); - if ($.inArray(trip.id, activeJourneys) != -1) { - out = ''; - } else if (currentTripMeasures.length > 0) { + if (currentTripMeasures.length > 0) { out = ''; + } else if ($.inArray(trip.id, activeJourneys) != -1) { + out = ''; } else { out = ''; } out += "Rit "+trip.journeynumber+""; out += " Vertrek "+convertSecondsToTime(trip.departuretime)+""; - if ($.inArray(trip.id, activeJourneys) != -1) { - out += ''; - } if (currentTripMeasures.length > 0) { out += ''; + } else if ($.inArray(trip.id, activeJourneys) != -1) { + out += ''; } out += ""; return out; From 60469e4ba3ecef3593f6cc5d6c57586785707f56 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Thu, 4 Feb 2021 11:32:11 +0100 Subject: [PATCH 17/25] check for messageendtime < messagestarttime added --- openebs/views.py | 7 ++++-- openebs2/static/js/add_msg.js | 43 ----------------------------------- 2 files changed, 5 insertions(+), 45 deletions(-) diff --git a/openebs/views.py b/openebs/views.py index b514af5..7dd33d1 100644 --- a/openebs/views.py +++ b/openebs/views.py @@ -292,17 +292,20 @@ def get_object(self, **kwargs): if len(messagecontent.strip()) == 0 and messagetype != 'OVERRULE': message_validation.append("Bericht mag niet leeg zijn") - if hasattr(self.request.GET, 'messagestarttime'): + if 'messagestarttime' in self.request.GET: starttime = self.request.GET.get('messagestarttime') endtime = self.request.GET.get('messageendtime') datetimevalidation = [] try: - datetime.strptime(starttime, "%d-%m-%Y %H:%M:%S") + starttime = datetime.strptime(starttime, "%d-%m-%Y %H:%M:%S") except: datetimevalidation.append("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)") try: endtime = datetime.strptime(endtime, "%d-%m-%Y %H:%M:%S") + if endtime < starttime: + message_validation.append("De eindtijd moet na de begintijd zijn.") + if not is_aware(endtime): endtime = make_aware(endtime) except: diff --git a/openebs2/static/js/add_msg.js b/openebs2/static/js/add_msg.js index 85187de..9287181 100644 --- a/openebs2/static/js/add_msg.js +++ b/openebs2/static/js/add_msg.js @@ -313,49 +313,6 @@ function writeHaltesWithMessages(data, status) { //}); } -function formValidation() { - validationerrors = [] - - // check for empty messagecontent - if ($('#id_messagecontent').val().trim().length == 0) { - validationerrors.push("Bericht mag niet leeg zijn."); - } - - // check if begin- and endtime is filled correctly - var dates = [$('#id_messagestarttime').val().trim(), $('#id_messageendtime').val().trim()] - $.each(dates, function(i, date) { - var dateparts = date.split(' ')[0].split('-'); - if (dateparts.length !== 3 || - dateparts[0].length == 0 || dateparts[0].length > 2 || - dateparts[1].length == 0 || dateparts[1].length > 2 || dateparts[2].length !== 4) { - if (i == 0) { - validationerrors.push("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)") - } else { - validationerrors.push("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)") - } - } - }); - - // check if stops are filled - if ($('#haltes').val().length == 0) { - validationerrors.push("Selecteer minimaal een halte.") - } - - if (validationerrors.length == 0) { - $(".form").submit(); - } else { - if (!$("#error_list").hasClass('hidden')) { - $("#error_list").empty(); - } - $.each(validationerrors, function(i, error) { - $("#error_list").append('

'+error+'

'); - }); - if ($("#error_list").hasClass('hidden')) { - $("#error_list").removeClass('hidden'); - } - } -} - function formValidation() { validationerrors = [] From d0c8fdb742ca5841c0a353b74b682e2df8ad375d Mon Sep 17 00:00:00 2001 From: baasje85 Date: Thu, 4 Feb 2021 12:38:59 +0100 Subject: [PATCH 18/25] bugfix automatic messageenddate adjustment --- openebs2/static/js/add_msg.js | 39 +++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/openebs2/static/js/add_msg.js b/openebs2/static/js/add_msg.js index 9287181..133b13a 100644 --- a/openebs2/static/js/add_msg.js +++ b/openebs2/static/js/add_msg.js @@ -388,14 +388,16 @@ function showStopsOnChange() { function checkMessageTime(event, ui) { var starttime = parseDate($("#id_messagestarttime").val()); var endtime = parseDate($("#id_messageendtime").val()); - - if (starttime >= endtime) { - if ($(this).attr('id') == "id_messagestarttime") { - endtime.setDate(starttime.getDate()+1); - $("#id_messageendtime").val(formatDate(endtime)); - } else { - starttime.setDate(endtime.getDate()-1); - $("#id_messagestarttime").val(formatDate(starttime)); + if (starttime != 'Invalid Date') { + if (starttime >= endtime) { + var new_endtime = starttime; + if ($(this).attr('id') == "id_messagestarttime") { + new_endtime.setDate(new_endtime.getDate()+1); + $("#id_messageendtime").val(formatDate(new_endtime)); + } else { + starttime.setDate(endtime.getDate()-1); + $("#id_messagestarttime").val(formatDate(starttime)); + } } } } @@ -476,14 +478,21 @@ function hideEndTime() { } function showEndTime() { - $('#div_id_messageendtime').show(); - var enddate = new Date(); - enddate.setHours(3, 0, 0); - enddate.setDate(enddate.getDate()+1); - $('#id_messageendtime').val(formatDate(enddate)); - + $('#div_id_messageendtime').show(); + var enddate = new Date(); + enddate.setHours(3, 0, 0); + + var startdate = parseDate($('#id_messagestarttime').val()); + if (startdate != 'Invalid Date') { + var new_enddate = startdate; + new_enddate.setDate(new_enddate.getDate()+1); + $("#id_messageendtime").val(formatDate(new_enddate)); + } else { + enddate.setDate(enddate.getDate()+1); + $('#id_messageendtime').val(formatDate(enddate)); + } } function epoch(date) { return Date.parse(date) / 1000; -} \ No newline at end of file +} From d712a65f5107739b657c02d97075b275f66ddfe9 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Thu, 4 Feb 2021 12:39:13 +0100 Subject: [PATCH 19/25] bugfix check messageendtime --- openebs/views.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/openebs/views.py b/openebs/views.py index 7dd33d1..2f46d40 100644 --- a/openebs/views.py +++ b/openebs/views.py @@ -303,9 +303,6 @@ def get_object(self, **kwargs): try: endtime = datetime.strptime(endtime, "%d-%m-%Y %H:%M:%S") - if endtime < starttime: - message_validation.append("De eindtijd moet na de begintijd zijn.") - if not is_aware(endtime): endtime = make_aware(endtime) except: @@ -315,6 +312,9 @@ def get_object(self, **kwargs): message_validation.append("Voer een geldige begin- en eindtijd in (dd-mm-jjjj uu:mm:ss)") elif len(datetimevalidation) == 1: message_validation.append(datetimevalidation[0]) + elif len(datetimevalidation) == 0: + if endtime < starttime: + message_validation.append("De eindtijd moet na de begintijd zijn.") current = datetime.now() if not is_aware(current): From 5731b09247a4e0e4de8c448ae93da8215745313b Mon Sep 17 00:00:00 2001 From: baasje85 Date: Thu, 4 Feb 2021 12:45:46 +0100 Subject: [PATCH 20/25] bugfix2 check messageendtime --- openebs/views.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/openebs/views.py b/openebs/views.py index 2f46d40..42f4680 100644 --- a/openebs/views.py +++ b/openebs/views.py @@ -298,6 +298,8 @@ def get_object(self, **kwargs): datetimevalidation = [] try: starttime = datetime.strptime(starttime, "%d-%m-%Y %H:%M:%S") + if not is_aware(starttime): + starttime = make_aware(starttime) except: datetimevalidation.append("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)") @@ -313,6 +315,7 @@ def get_object(self, **kwargs): elif len(datetimevalidation) == 1: message_validation.append(datetimevalidation[0]) elif len(datetimevalidation) == 0: + if endtime < starttime: message_validation.append("De eindtijd moet na de begintijd zijn.") From 1d60e4e2b64fceec6e116e8346519865311f3c9e Mon Sep 17 00:00:00 2001 From: baasje85 Date: Thu, 4 Feb 2021 12:55:01 +0100 Subject: [PATCH 21/25] bugfix template --- openebs2/static/js/add_msg_journey.js | 1 + 1 file changed, 1 insertion(+) diff --git a/openebs2/static/js/add_msg_journey.js b/openebs2/static/js/add_msg_journey.js index 2202654..1619ac2 100644 --- a/openebs2/static/js/add_msg_journey.js +++ b/openebs2/static/js/add_msg_journey.js @@ -155,6 +155,7 @@ function writeTrips(data, status) { maxLen = Math.max(data.object.trips_1.length, data.object.trips_2.length); if (maxLen > 0) { $('#trips tbody').fadeOut(100); + $('#trips tbody').text(""); $('#trips tr').not('.help').remove(); tripRows = null; for (i = 0; i <= maxLen; i = i + 1) { From 79039110218a4b8aa77004ec8542cc38514f4239 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Fri, 5 Feb 2021 15:52:03 +0100 Subject: [PATCH 22/25] clean-function called from .js, no extra validation_view necessary --- openebs/form.py | 57 +++++++++++++++ .../openebs/kv15stopmessage_form.html | 2 +- openebs/urls.py | 3 +- openebs/views.py | 73 +------------------ openebs2/static/css/site.css | 4 + openebs2/static/js/add_msg.js | 55 ++++++++------ utils/views.py | 28 +++++++ 7 files changed, 125 insertions(+), 97 deletions(-) diff --git a/openebs/form.py b/openebs/form.py index 58a79db..099a0e8 100644 --- a/openebs/form.py +++ b/openebs/form.py @@ -15,6 +15,63 @@ class Kv15StopMessageForm(forms.ModelForm): + def clean(self): + # TODO Move _all_ halte parsing here! + datetimevalidation = [] + try: + datetime.strptime(self.data['messagestarttime'], "%d-%m-%Y %H:%M:%S") + except: + datetimevalidation.append(_("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)")) + + try: + endtime = datetime.strptime(self.data['messageendtime'], "%d-%m-%Y %H:%M:%S") + if not is_aware(endtime): + endtime = make_aware(endtime) + except: + datetimevalidation.append(_("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)")) + + validationerrors = [] + if len(datetimevalidation) == 2: + validationerrors.append(ValidationError(_("Voer een geldige begin- en eindtijd in (dd-mm-jjjj uu:mm:ss)"))) + elif len(datetimevalidation) == 1: + validationerrors.append(ValidationError(datetimevalidation[0])) + + current = datetime.now() + if not is_aware(current): + current = make_aware(current) + if current > endtime: + validationerrors.append(ValidationError(_("Eindtijd van bericht ligt in het verleden"))) + + valid_ids = [] + nonvalid_ids = [] + for halte in self.data['haltes'].split(','): + halte_split = halte.split('_') + if len(halte_split) == 2: + stop = Kv1Stop.find_stop(halte_split[0], halte_split[1]) + if stop: + valid_ids.append(stop.pk) + else: + nonvalid_ids.append(halte) + + if len(nonvalid_ids) != 0: + log.warning("Ongeldige haltes: %s" % ', '.join(nonvalid_ids)) + if len(valid_ids) == 0 and len(nonvalid_ids) != 0: + validationerrors.append(ValidationError(_("Er werd geen geldige halte geselecteerd."))) + elif len(valid_ids) == 0: + validationerrors.append(ValidationError(_("Selecteer minimaal een halte."))) + + if len(validationerrors) != 0: + raise ValidationError(validationerrors) + else: + return self.cleaned_data + + def clean_messagecontent(self): + # Improve: Strip spaces from message + if ('messagecontent' not in self.cleaned_data or self.cleaned_data['messagecontent'] is None or len( + self.cleaned_data['messagecontent']) < 1) \ + and self.cleaned_data['messagetype'] != 'OVERRULE': + raise ValidationError(_("Bericht mag niet leeg zijn")) + return self.cleaned_data['messagecontent'] class Meta(object): model = Kv15Stopmessage diff --git a/openebs/templates/openebs/kv15stopmessage_form.html b/openebs/templates/openebs/kv15stopmessage_form.html index ea45759..dd0c1f8 100644 --- a/openebs/templates/openebs/kv15stopmessage_form.html +++ b/openebs/templates/openebs/kv15stopmessage_form.html @@ -9,7 +9,7 @@

{% trans "Bericht" %}

-
+

{% if prefilled_stop %} diff --git a/openebs/urls.py b/openebs/urls.py index cddf0e3..fedccf3 100644 --- a/openebs/urls.py +++ b/openebs/urls.py @@ -1,7 +1,7 @@ from django.conf.urls import url from django.views.generic import RedirectView from openebs.views import MessageListView, MessageCreateView, MessageDeleteView, MessageUpdateView, ActiveStopsAjaxView, MessageDetailsView, MessageStopsAjaxView, \ - MessageStopsBoundAjaxView, MessageResendView, MessageValidationAjaxView + MessageStopsBoundAjaxView, MessageResendView from openebs.views_change import ChangeListView, ChangeCreateView, ChangeDeleteView, ActiveJourneysAjaxView, \ ChangeUpdateView, ActiveLinesAjaxView, ChangeValidationAjaxView from openebs.views_filters import FilterListView, FilterDeleteView, FilterUpdateView, FilterCreateView, \ @@ -28,7 +28,6 @@ url(r'^bericht/(?P\d+)/verwijderen$', MessageDeleteView.as_view(), name="msg_delete"), url(r'^bericht/(?P\d+)/haltes.geojson', MessageStopsAjaxView.as_view(), name="msg_stops_ajax"), # LEGACY: map url(r'^bericht/(?P\d+)/halte_bereik.geojson', MessageStopsBoundAjaxView.as_view(), name="msg_bounds_ajax"), # Map bounds to zoom - url(r'^bericht/validatie.json', MessageValidationAjaxView.as_view(), name="msg_validation"), # This next view is used as URL when adding a message (name is not used) url(r'^bericht/haltes.json', ActiveStopsAjaxView.as_view(), name="active_stops_ajax"), diff --git a/openebs/views.py b/openebs/views.py index 42f4680..6814e30 100644 --- a/openebs/views.py +++ b/openebs/views.py @@ -16,7 +16,7 @@ from openebs.views_push import Kv15PushMixin from openebs.views_utils import FilterDataownerMixin from utils.client import get_client_ip -from utils.views import JSONListResponseMixin, AccessMixin, AccessJsonMixin +from utils.views import JSONListResponseMixin, AccessMixin, AccessJsonMixin, JsonableResponseMixin from openebs.models import Kv15Stopmessage, Kv15Log, MessageStatus, Kv1StopFilter from openebs.form import Kv15StopMessageForm @@ -73,7 +73,7 @@ def is_view_all(self): (not user.is_superuser and (user.has_perm("openebs.view_all") or user.has_perm("openebs.edit_all"))) -class MessageCreateView(AccessMixin, Kv15PushMixin, CreateView): +class MessageCreateView(JsonableResponseMixin, AccessMixin, Kv15PushMixin, CreateView): permission_required = 'openebs.add_messages' model = Kv15Stopmessage form_class = Kv15StopMessageForm @@ -275,72 +275,3 @@ def get_queryset(self): qry = qry.filter(kv15stopmessage__dataownercode=self.request.user.userprofile.company) return qry - - -class MessageValidationAjaxView(AccessJsonMixin, JSONListResponseMixin, DetailView): - permission_required = 'openebs.add_messages' - model = Kv15Stopmessage - render_object = 'object' - - def get_object(self, **kwargs): - - message_validation = [] - messagecontent = self.request.GET.get('messagecontent') - messagetype = self.request.GET.get('messagetype') - haltes = self.request.GET.get('haltes') - - if len(messagecontent.strip()) == 0 and messagetype != 'OVERRULE': - message_validation.append("Bericht mag niet leeg zijn") - - if 'messagestarttime' in self.request.GET: - starttime = self.request.GET.get('messagestarttime') - endtime = self.request.GET.get('messageendtime') - datetimevalidation = [] - try: - starttime = datetime.strptime(starttime, "%d-%m-%Y %H:%M:%S") - if not is_aware(starttime): - starttime = make_aware(starttime) - except: - datetimevalidation.append("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)") - - try: - endtime = datetime.strptime(endtime, "%d-%m-%Y %H:%M:%S") - if not is_aware(endtime): - endtime = make_aware(endtime) - except: - datetimevalidation.append("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)") - - if len(datetimevalidation) == 2: - message_validation.append("Voer een geldige begin- en eindtijd in (dd-mm-jjjj uu:mm:ss)") - elif len(datetimevalidation) == 1: - message_validation.append(datetimevalidation[0]) - elif len(datetimevalidation) == 0: - - if endtime < starttime: - message_validation.append("De eindtijd moet na de begintijd zijn.") - - current = datetime.now() - if not is_aware(current): - current = make_aware(current) - if current > endtime: - message_validation.append("Eindtijd van bericht ligt in het verleden") - - valid_ids = [] - nonvalid_ids = [] - for halte in haltes.split(','): - halte_split = halte.split('_') - if len(halte_split) == 2: - stop = Kv1Stop.find_stop(halte_split[0], halte_split[1]) - if stop: - valid_ids.append(stop.pk) - else: - nonvalid_ids.append(halte) - - if len(nonvalid_ids) != 0: - log.warning("Ongeldige haltes: %s" % ', '.join(nonvalid_ids)) - if len(valid_ids) == 0 and len(nonvalid_ids) != 0: - message_validation.append("Er werd geen geldige halte geselecteerd.") - elif len(valid_ids) == 0: - message_validation.append("Selecteer minimaal een halte.") - - return message_validation diff --git a/openebs2/static/css/site.css b/openebs2/static/css/site.css index bb4b455..6a7c98b 100644 --- a/openebs2/static/css/site.css +++ b/openebs2/static/css/site.css @@ -235,3 +235,7 @@ span.stop-selection,span.trip-selection{ .msg_warning { background-color: #fcf8e3; } + +.error-label label { + color: #a94442; +} \ No newline at end of file diff --git a/openebs2/static/js/add_msg.js b/openebs2/static/js/add_msg.js index 133b13a..3326662 100644 --- a/openebs2/static/js/add_msg.js +++ b/openebs2/static/js/add_msg.js @@ -316,34 +316,43 @@ function writeHaltesWithMessages(data, status) { function formValidation() { validationerrors = [] - var pathname = window.location.pathname; - if (pathname.indexOf('scenario') == -1) { - validationdata = {'messagestarttime': $('#id_messagestarttime').val().trim(), - 'messageendtime': $('#id_messageendtime').val().trim(), - 'messagecontent': $('#id_messagecontent').val().trim(), - 'messagetype': $("input[name='messagetype']:checked").val(), - 'haltes': $('#haltes').val()} - } else { - validationdata = {'messagecontent': $('#id_messagecontent').val().trim(), - 'messagetype': $("input[name='messagetype']:checked").val(), - 'haltes': $('#haltes').val()} - } - $.ajax({url: '/bericht/validatie.json', + var validationdata = $('.form').serializeArray().reduce(function(obj, item) { + obj[item.name] = item.value; + return obj; + }, {}); + validationdata['csrfmiddlewaretoken'] = document.getElementsByName('csrfmiddlewaretoken')[0].value; + + $.ajax({url: window.location.pathname, data: validationdata, + method: 'POST', success : function(result) { - var validationerrors = result.object; - if (validationerrors.length == 0) { - $(".form").submit(); - } else { - if (!$("#error_list").hasClass('hidden')) { + window.location.href = '/bericht' + }, + error: function(result) { + var response = result.responseJSON; + if (!$("#error_list").hasClass('hidden')) { $("#error_list").empty(); - } - $.each(validationerrors, function(i, error) { + $(".has-error").removeClass('has-error'); + $(".error-label").removeClass('error-label'); + } + $.each(response, function(field, errorlist) { + $.each(errorlist, function(idx, error) { + error = error.toLowerCase(); + if (error.indexOf('begin') !== -1) { + $('#div_id_messagestarttime').addClass('has-error'); + } else if (error.indexOf('bericht') !== -1) { + $('#div_id_messagecontent').addClass('has-error'); + } else if (error.indexOf('halte') !== -1) { + $('#div_id_haltes').addClass('error-label'); + } + if (error.indexOf('eind') !== -1) { + $('#div_id_messageendtime').addClass('has-error'); + } $("#error_list").append('

'+error+'

'); }); - if ($("#error_list").hasClass('hidden')) { - $("#error_list").removeClass('hidden'); - } + }); + if ($("#error_list").hasClass('hidden')) { + $("#error_list").removeClass('hidden'); } } }); diff --git a/utils/views.py b/utils/views.py index 774f39e..3b49252 100644 --- a/utils/views.py +++ b/utils/views.py @@ -19,6 +19,7 @@ from django.shortcuts import redirect, render from utils.push import Push from django.db.models.query import QuerySet +from django.http import JsonResponse log = logging.getLogger('openebs.views.mixins') @@ -183,6 +184,33 @@ def dispatch(self, request, *args, **kwargs): request, *args, **kwargs) +class JsonableResponseMixin: + """ + Mixin to add JSON support to a form. + Must be used with an object-based FormView (e.g. CreateView) + """ + + def form_invalid(self, form): + response = super().form_invalid(form) + if self.request.is_ajax(): + return JsonResponse(form.errors, status=400) + else: + return response + + def form_valid(self, form): + # We make sure to call the parent's form_valid() method because + # it might do some processing (in the case of CreateView, it will + # call form.save() for example). + response = super().form_valid(form) + if self.request.is_ajax(): + data = { + 'pk': self.object.pk, + } + return JsonResponse(data) + else: + return response + + def handler403(request, exception): response = render(request, 'openebs/nopermission.html', {}) response.status_code = 404 From 647e013f2ad2d2c21757d9ff49a6e93f0bf6aef2 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Fri, 5 Feb 2021 16:06:22 +0100 Subject: [PATCH 23/25] clean-function called from .js, update for scenario-messages --- openebs2/static/js/add_msg.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/openebs2/static/js/add_msg.js b/openebs2/static/js/add_msg.js index 3326662..370c178 100644 --- a/openebs2/static/js/add_msg.js +++ b/openebs2/static/js/add_msg.js @@ -314,19 +314,23 @@ function writeHaltesWithMessages(data, status) { } function formValidation() { - validationerrors = [] - + var pathname = window.location.pathname; var validationdata = $('.form').serializeArray().reduce(function(obj, item) { obj[item.name] = item.value; return obj; }, {}); validationdata['csrfmiddlewaretoken'] = document.getElementsByName('csrfmiddlewaretoken')[0].value; - $.ajax({url: window.location.pathname, + $.ajax({url: pathname, data: validationdata, method: 'POST', success : function(result) { - window.location.href = '/bericht' + if (pathname.indexOf('scenario') !== -1) { + var base_href = pathname.split('bericht')[0]; + window.location.href = base_href + 'bewerk'; + } else { + window.location.href = '/bericht'; + } }, error: function(result) { var response = result.responseJSON; From 5e4d1bad62f2be376012785b46ee22bf8cb272c8 Mon Sep 17 00:00:00 2001 From: baasje85 Date: Sun, 7 Feb 2021 10:57:59 +0100 Subject: [PATCH 24/25] clean-function called from .js, update for journey --- openebs/form.py | 29 ++-- openebs/form_kv17.py | 124 +++++++++++++++- .../templates/openebs/kv17change_form.html | 4 +- openebs/urls.py | 3 +- openebs/views.py | 2 +- openebs/views_change.py | 136 +----------------- openebs2/static/js/add_msg.js | 45 +++--- openebs2/static/js/add_msg_journey.js | 61 ++++---- 8 files changed, 205 insertions(+), 199 deletions(-) diff --git a/openebs/form.py b/openebs/form.py index 099a0e8..1ef18f6 100644 --- a/openebs/form.py +++ b/openebs/form.py @@ -21,18 +21,18 @@ def clean(self): try: datetime.strptime(self.data['messagestarttime'], "%d-%m-%Y %H:%M:%S") except: - datetimevalidation.append(_("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss)")) + datetimevalidation.append(_("Voer een geldige begintijd in (dd-mm-jjjj uu:mm:ss).")) try: endtime = datetime.strptime(self.data['messageendtime'], "%d-%m-%Y %H:%M:%S") if not is_aware(endtime): endtime = make_aware(endtime) except: - datetimevalidation.append(_("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)")) + datetimevalidation.append(_("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss).")) validationerrors = [] if len(datetimevalidation) == 2: - validationerrors.append(ValidationError(_("Voer een geldige begin- en eindtijd in (dd-mm-jjjj uu:mm:ss)"))) + validationerrors.append(ValidationError(_("Voer een geldige begin- en eindtijd in (dd-mm-jjjj uu:mm:ss)."))) elif len(datetimevalidation) == 1: validationerrors.append(ValidationError(datetimevalidation[0])) @@ -40,7 +40,7 @@ def clean(self): if not is_aware(current): current = make_aware(current) if current > endtime: - validationerrors.append(ValidationError(_("Eindtijd van bericht ligt in het verleden"))) + validationerrors.append(ValidationError(_("Eindtijd van bericht ligt in het verleden."))) valid_ids = [] nonvalid_ids = [] @@ -66,11 +66,12 @@ def clean(self): return self.cleaned_data def clean_messagecontent(self): - # Improve: Strip spaces from message - if ('messagecontent' not in self.cleaned_data or self.cleaned_data['messagecontent'] is None or len( - self.cleaned_data['messagecontent']) < 1) \ + if 'messagetype' not in self.cleaned_data: + raise ValidationError(_("Type bericht moet zijn ingevuld.")) + elif ('messagecontent' not in self.cleaned_data or self.cleaned_data['messagecontent'] is None or len( + self.cleaned_data['messagecontent'].strip()) < 1) \ and self.cleaned_data['messagetype'] != 'OVERRULE': - raise ValidationError(_("Bericht mag niet leeg zijn")) + raise ValidationError(_("Bericht mag niet leeg zijn.")) return self.cleaned_data['messagecontent'] class Meta(object): @@ -178,20 +179,24 @@ def clean(self): qry = Kv1Stop.objects.filter(kv15scenariostop__message__scenario=self.data['scenario'], pk__in=ids) if self.instance.pk is not None: # Exclude ourselves if we've been saved qry = qry.exclude(kv15scenariostop__message=self.instance.pk) - + validationerrors = [] if qry.count() > 0: # Check that this stop isn't already in a messages for this scenario. If not, write a nice message out = "" for stop in qry: out += "%s, " % stop.name - raise ValidationError(_("Halte(s) ' %s ' bestaan al voor dit scenario") % out) + validationerrors.append(ValidationError(_("Halte(s) ' %s ' bestaan al voor dit scenario.") % out)) elif len(ids) == 0: # Select at least one stop for a message - raise ValidationError(_("Selecteer minimaal een halte")) + validationerrors.append(ValidationError(_("Selecteer minimaal een halte."))) + if 'messagetype' not in self.cleaned_data: + validationerrors.append(ValidationError(_("Type bericht moet zijn ingevuld."))) elif ('messagecontent' not in self.cleaned_data or self.cleaned_data['messagecontent'] is None or len( self.cleaned_data['messagecontent'].strip()) == 0) \ and self.cleaned_data['messagetype'] != 'OVERRULE': - raise ValidationError(_("Bericht mag niet leeg zijn")) + validationerrors.append(ValidationError(_("Bericht mag niet leeg zijn."))) + if len(validationerrors) != 0: + raise ValidationError(validationerrors) else: return self.cleaned_data diff --git a/openebs/form_kv17.py b/openebs/form_kv17.py index 9a95f29..bd469f9 100644 --- a/openebs/form_kv17.py +++ b/openebs/form_kv17.py @@ -13,7 +13,7 @@ from django.utils.dateparse import parse_date from datetime import datetime, timedelta, time from django.db.models import Q -from django.utils.timezone import make_aware, utc +from django.utils.timezone import make_aware log = logging.getLogger('openebs.forms') @@ -33,6 +33,128 @@ class Kv17ChangeForm(forms.ModelForm): advicecontent = forms.CharField(max_length=255, label=_("Uitleg advies"), required=False, widget=forms.Textarea(attrs={'cols': 40, 'rows': 4, 'class': 'col-lg-6'})) + def clean(self): + cleaned_data = super(Kv17ChangeForm, self).clean() + operatingday = parse_date(self.data['operatingday']) + validationerrors = [] + if operatingday is None: + validationerrors.append(ValidationError(_("Er staan geen ritten in de database"))) + + if 'journeys' not in self.data: + validationerrors.append(ValidationError(_("Een of meer geselecteerde ritten zijn ongeldig"))) + + if self.data['begintime_part'] != '': + hh, mm = self.data['begintime_part'].split(':') + begintime = make_aware(datetime.combine(operatingday, time(int(hh), int(mm)))) + else: + begintime = None + + if self.data['endtime_part'] != '': + hh_e, mm_e = self.data['endtime_part'].split(':') + endtime = make_aware(datetime.combine(operatingday, time(int(hh_e), int(mm_e)))) + if begintime: + if begintime > endtime: # if endtime before begintime + endtime = endtime + timedelta(days=1) # endtime is next day + if endtime.time() >= time(6, 0): # and after 6 am: validation error + validationerrors.append(ValidationError(_("Eindtijd valt op volgende operationele dag"))) + else: + endtime = None + + dataownercode = self.user.userprofile.company + if 'Alle ritten' in self.data['journeys']: + validationerrors = self.clean_all_journeys(operatingday, dataownercode, begintime, endtime, validationerrors) + elif 'Hele vervoerder' in self.data['lines']: + validationerrors = self.clean_all_lines(operatingday, dataownercode, begintime, endtime, validationerrors) + else: + validationerrors = self.clean_journeys(operatingday, dataownercode, validationerrors) + + if len(validationerrors) != 0: + raise ValidationError(validationerrors) + else: + return cleaned_data + + def clean_journeys(self, operatingday, dataownercode, validationerrors): + if self.data['journeys'] != '': + for journey in self.data['journeys'].split(',')[0:-1]: + journey_qry = Kv1Journey.objects.filter(dataownercode=dataownercode, pk=journey, + dates__date=operatingday) + if journey_qry.count() == 0: + validationerrors.append(ValidationError(_("Een of meer geselecteerde ritten zijn ongeldig"))) + + # delete recovered if query is the same. + Kv17Change.objects.filter(dataownercode=dataownercode, journey__pk=journey, line=journey_qry[0].line, + operatingday=operatingday, is_recovered=True).delete() + + else: + validationerrors.append(ValidationError(_("Er werd geen rit geselecteerd."))) + + return validationerrors + + def clean_all_journeys(self, operatingday, dataownercode, begintime, endtime, validationerrors): + if 'lines' in self.data: + if self.data['lines'] != '': + for line in self.data['lines'].split(',')[0:-1]: + line_qry = Kv1Line.objects.filter(pk=line) + + if line_qry.count() == 0: + validationerrors.append(ValidationError(_("Er werd geen lijn gevonden in de database."))) + + database_alljourneys = Kv17Change.objects.filter(dataownercode=dataownercode, + is_alljourneysofline=True, line=line_qry[0], + operatingday=operatingday, is_recovered=False) + + database_alllines = Kv17Change.objects.filter(dataownercode=dataownercode, + is_alllines=True, operatingday=operatingday, + is_recovered=False) + + # delete recovered if query is the same. + Kv17Change.objects.filter(dataownercode=dataownercode, is_alljourneysofline=True, line=line_qry[0], + operatingday=operatingday, begintime=begintime, endtime=endtime, + is_recovered=True).delete() + + if operatingday == datetime.today().date(): + begintime = make_aware(datetime.now()) if begintime is None else begintime + else: + begintime = make_aware(datetime.combine(operatingday, time((int(4))))) \ + if begintime is None else begintime + + if database_alllines: + if database_alllines.filter(Q(endtime__gt=begintime) | Q(endtime=None), + Q(begintime__lte=begintime) | Q(begintime=None)): + validationerrors.append(ValidationError(_( + "De gehele vervoerder is al aangepast voor de aangegeven ingangstijd."))) + + elif database_alljourneys: + if database_alljourneys.filter(Q(endtime__gt=begintime) | Q(endtime=None), + Q(begintime__lte=begintime) | Q(begintime=None)): + validationerrors.append(ValidationError(_( + "Een of meer geselecteerde lijnen zijn al aangepast voor de aangegeven ingangstijd."))) + else: + validationerrors.append(ValidationError(_("Geen geldige lijn geselecteerd"))) + + return validationerrors + + def clean_all_lines(self, operatingday, dataownercode, begintime, endtime, validationerrors): + database_alllines = Kv17Change.objects.filter(dataownercode=dataownercode, is_alllines=True, + operatingday=operatingday, is_recovered=False) + + # delete recovered if query is the same. + Kv17Change.objects.filter(dataownercode=dataownercode, is_alllines=True, is_recovered=True, + operatingday=operatingday, begintime=begintime, endtime=endtime).delete() + + if database_alllines: + if operatingday == datetime.today().date(): + begintime = make_aware(datetime.now()) if begintime is None else begintime + else: + begintime = make_aware(datetime.combine(operatingday, time((int(4))))) \ + if begintime is None else begintime + + if database_alllines.filter(Q(endtime__gt=begintime) | Q(endtime=None), + Q(begintime__lte=begintime) | Q(begintime=None)): + validationerrors.append(ValidationError(_("De ingangstijd valt al binnen een geplande operatie."))) + + return validationerrors + def save(self, force_insert=False, force_update=False, commit=True): ''' Save each of the journeys in the model. This is a disaster, we return the XML TODO: Figure out a better solution fo this! ''' diff --git a/openebs/templates/openebs/kv17change_form.html b/openebs/templates/openebs/kv17change_form.html index 1744194..dcfb235 100644 --- a/openebs/templates/openebs/kv17change_form.html +++ b/openebs/templates/openebs/kv17change_form.html @@ -64,7 +64,7 @@

{% trans "Ritaanpassing" %}

-