Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement Block stops with active messages #191

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
05662cf
uniform check for empty strings
Baasje85 Feb 2, 2021
1926290
typfout gecorrigeerd in choices model FerryKv6Messages
Baasje85 Feb 2, 2021
156ac2d
validity check user-entered times
Baasje85 Feb 2, 2021
643e592
added date to future activeMessages
Baasje85 Feb 2, 2021
848dc55
validate 'ritaanpassing' within .js
Baasje85 Feb 2, 2021
88a1c78
bugfix automatic adjusted endtime
Baasje85 Feb 2, 2021
caff64f
bugfix only check messagetimes on change, not blur
Baasje85 Feb 2, 2021
c831b21
validate add message within .js
Baasje85 Feb 2, 2021
e4d72a0
validate add scenariomessage within .js
Baasje85 Feb 2, 2021
f8abde4
validate update-pages within .js
Baasje85 Feb 2, 2021
d1fb2a2
validate add_message with ajax from .js
Baasje85 Feb 3, 2021
7016e32
validate add_scenario_message with ajax from .js
Baasje85 Feb 3, 2021
7ba3d67
small improvements in add_msg_journey.js
Baasje85 Feb 3, 2021
7e00092
validate add_change with ajax from .js
Baasje85 Feb 3, 2021
04e3b52
stops with active messages now blocked within messagetime window
Baasje85 Feb 3, 2021
323a1c5
small improvement. Only one visible warning-sign on journey
Baasje85 Feb 3, 2021
60469e4
check for messageendtime < messagestarttime added
Baasje85 Feb 4, 2021
d0c8fdb
bugfix automatic messageenddate adjustment
Baasje85 Feb 4, 2021
d712a65
bugfix check messageendtime
Baasje85 Feb 4, 2021
5731b09
bugfix2 check messageendtime
Baasje85 Feb 4, 2021
1d60e4e
bugfix template
Baasje85 Feb 4, 2021
7903911
clean-function called from .js, no extra validation_view necessary
Baasje85 Feb 5, 2021
647e013
clean-function called from .js, update for scenario-messages
Baasje85 Feb 5, 2021
5e4d1ba
clean-function called from .js, update for journey
Baasje85 Feb 7, 2021
d943a43
added filter in clean-function of create-msg + template functions imp…
Baasje85 Feb 8, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions ferry/migrations/0017_auto_20210202_1254.py
Original file line number Diff line number Diff line change
@@ -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'),
),
]
2 changes: 1 addition & 1 deletion ferry/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")),
)
Expand Down
84 changes: 63 additions & 21 deletions openebs/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
import floppyforms.__future__ as forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.db.models import Q

from kv1.models import Kv1Stop
from openebs.models import Kv15Stopmessage, Kv15Scenario, Kv15ScenarioMessage, get_end_service
from openebs.models import Kv15Stopmessage, Kv15Scenario, Kv15ScenarioMessage, get_end_service, Kv15MessageStop
from datetime import datetime

log = logging.getLogger('openebs.forms')
Expand All @@ -17,30 +19,32 @@
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")
starttime = datetime.strptime(self.data['messagestarttime'], "%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)"))
pass
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)"))
pass
datetimevalidation.append(_("Voer een geldige eindtijd in (dd-mm-jjjj uu:mm:ss)."))

validationerrors = []
if len(datetimevalidation) == 2:
raise 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:
raise ValidationError(datetimevalidation[0])
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 = []
Expand All @@ -50,26 +54,41 @@ def clean(self):
stop = Kv1Stop.find_stop(halte_split[0], halte_split[1])
if stop:
valid_ids.append(stop.pk)
if starttime:
if 'messagetype' in self.data and self.data['messagetype'] != 'OVERRULE':
dataownercode = self.instance.dataownercode
if len(valid_ids) > 0:
msg_count = Kv15MessageStop.objects.filter(~Q(stopmessage__id=self.instance.id),
stopmessage__dataownercode=dataownercode,
stop__id=stop.pk,
stopmessage__messagestarttime__lte=starttime,
stopmessage__messageendtime__gte=starttime,
stopmessage__isdeleted=False).count()
if msg_count > 0:
validationerrors.append(
ValidationError(_("Halte heeft al een bericht voor deze begintijd.")))
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."))
validationerrors.append(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"))
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) \
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):
Expand Down Expand Up @@ -177,20 +196,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

Expand Down Expand Up @@ -274,8 +297,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):
Expand Down
67 changes: 29 additions & 38 deletions openebs/form_kv17.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand All @@ -36,11 +36,12 @@ class Kv17ChangeForm(forms.ModelForm):
def clean(self):
cleaned_data = super(Kv17ChangeForm, self).clean()
operatingday = parse_date(self.data['operatingday'])
validationerrors = []
if operatingday is None:
raise ValidationError(_("Er staan geen ritten in de database"))
validationerrors.append(ValidationError(_("Er staan geen ritten in de database")))

if 'journeys' not in self.data:
raise ValidationError(_("Een of meer geselecteerde ritten zijn ongeldig"))
validationerrors.append(ValidationError(_("Een of meer geselecteerde ritten zijn ongeldig")))

if self.data['begintime_part'] != '':
hh, mm = self.data['begintime_part'].split(':')
Expand All @@ -55,52 +56,48 @@ def clean(self):
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"))
validationerrors.append(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)
validationerrors = self.clean_all_journeys(operatingday, dataownercode, begintime, endtime, validationerrors)
elif 'Hele vervoerder' in self.data['lines']:
valid_journeys = self.clean_all_lines(operatingday, dataownercode, begintime, endtime)
validationerrors = self.clean_all_lines(operatingday, dataownercode, begintime, endtime, validationerrors)
else:
valid_journeys = self.clean_journeys(operatingday, dataownercode)
validationerrors = self.clean_journeys(operatingday, dataownercode, validationerrors)

if valid_journeys == 0:
raise ValidationError(_("Er zijn geen ritten geselecteerd om op te heffen"))

return cleaned_data
if len(validationerrors) != 0:
raise ValidationError(validationerrors)
else:
return cleaned_data

def clean_journeys(self, operatingday, dataownercode):
valid_journeys = 0
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)
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"))
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:
raise ValidationError(_("Er werd geen rit geselecteerd."))

valid_journeys += 1

return valid_journeys
validationerrors.append(ValidationError(_("Er werd geen rit geselecteerd.")))

def clean_all_journeys(self, operatingday, dataownercode, begintime, endtime):
valid_journeys = 0
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:
raise ValidationError(_("Geen lijn gevonden."))
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],
Expand All @@ -124,24 +121,20 @@ def clean_all_journeys(self, operatingday, dataownercode, begintime, endtime):
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."))
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)):
raise ValidationError(_(
"Een of meer geselecteerde lijnen zijn al aangepast voor de aangegeven ingangstijd."))
validationerrors.append(ValidationError(_(
"Een of meer geselecteerde lijnen zijn al aangepast voor de aangegeven ingangstijd.")))
else:
raise ValidationError(_("Geen geldige lijn geselecteerd"))
validationerrors.append(ValidationError(_("Geen geldige lijn geselecteerd")))

valid_journeys += 1

return valid_journeys

def clean_all_lines(self, operatingday, dataownercode, begintime, endtime):
valid_journeys = 0
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)

Expand All @@ -158,11 +151,9 @@ def clean_all_lines(self, operatingday, dataownercode, begintime, endtime):

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
validationerrors.append(ValidationError(_("De ingangstijd valt al binnen een geplande operatie.")))

return valid_journeys
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
Expand Down
4 changes: 2 additions & 2 deletions openebs/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ class Meta(object):

def __str__(self):
message = self.messagecontent
if message == "":
if not message or len(message.strip()) == 0:
message = _("<geen bericht>")
return "%s|%s#%s : %s" % (self.dataownercode, self.messagecodedate, self.messagecodenumber, message)

Expand Down Expand Up @@ -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 = _("<geen bericht>")
return "%s : %s" % (self.scenario.name, message)

Expand Down
6 changes: 4 additions & 2 deletions openebs/templates/openebs/kv15scenariomessage_form.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ <h2>{% trans "Bericht" %}</h2>
<input type="hidden" id="haltes" name="haltes"
value="{% for halte in object.kv15messagestop_set.all %}{{ halte.stop.dataownercode }}_{{ halte.stop.userstopcode }},{% endfor %}" />
</div>
<div id="error_list" class="hidden"></div>

<div class="clearfix"></div>
{% crispy form form.helper %}
<div class="form-group">
<br />
<button type="submit" class="btn btn-primary">{% trans "Toevoegen" %}</button>
<br />
<button type="button" class="btn btn-primary" onclick="formValidation()">{% trans "Toevoegen" %}</button>
</div>
</form>
</div>
Expand Down
3 changes: 2 additions & 1 deletion openebs/templates/openebs/kv15scenariomessage_update.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,13 @@ <h2>Bericht</h2>
<input type="hidden" id="haltes" name="haltes"
value="{% for halte in object.stops.all %}{{ halte.stop.dataownercode }}_{{ halte.stop.userstopcode }},{% endfor %}" />
</div>
<div id="error_list" class="hidden"></div>
<div class="clearfix"></div>
{% csrf_token %}
{% crispy form form.helper %}
<br />
<div class="form-group">
<button type="submit" class="btn btn-primary">{% trans "Opslaan" %}</button>
<button type="button" class="btn btn-primary" onclick="formValidation()">{% trans "Opslaan" %}</button>
</div>
</form>
</div>
Expand Down
Loading