2022-09-18 15:06:28 +02:00
|
|
|
from django import forms
|
2023-07-31 23:52:38 +07:00
|
|
|
from django.utils.translation import gettext_lazy as _
|
2022-09-18 15:06:28 +02:00
|
|
|
|
2023-04-18 16:33:43 -04:00
|
|
|
from extras.choices import DurationChoices
|
2023-04-14 10:33:53 -04:00
|
|
|
from utilities.forms import BootstrapMixin
|
2023-04-18 16:33:43 -04:00
|
|
|
from utilities.forms.widgets import DateTimePicker, NumberWithOptions
|
2023-01-06 09:42:13 -05:00
|
|
|
from utilities.utils import local_now
|
2022-09-18 15:06:28 +02:00
|
|
|
|
|
|
|
__all__ = (
|
|
|
|
'ReportForm',
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class ReportForm(BootstrapMixin, forms.Form):
|
|
|
|
schedule_at = forms.DateTimeField(
|
|
|
|
required=False,
|
|
|
|
widget=DateTimePicker(),
|
2022-11-03 11:58:26 -07:00
|
|
|
label=_("Schedule at"),
|
|
|
|
help_text=_("Schedule execution of report to a set time"),
|
2022-10-09 21:05:31 +02:00
|
|
|
)
|
2022-12-08 18:17:13 -05:00
|
|
|
interval = forms.IntegerField(
|
|
|
|
required=False,
|
|
|
|
min_value=1,
|
|
|
|
label=_("Recurs every"),
|
2023-04-18 16:33:43 -04:00
|
|
|
widget=NumberWithOptions(
|
|
|
|
options=DurationChoices
|
|
|
|
),
|
2022-12-08 18:17:13 -05:00
|
|
|
help_text=_("Interval at which this report is re-run (in minutes)")
|
|
|
|
)
|
|
|
|
|
2023-04-17 13:12:14 -04:00
|
|
|
def __init__(self, *args, scheduling_enabled=True, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
# Annotate the current system time for reference
|
|
|
|
now = local_now().strftime('%Y-%m-%d %H:%M:%S')
|
2023-07-31 23:52:38 +07:00
|
|
|
self.fields['schedule_at'].help_text += _(' (current time: <strong>{now}</strong>)').format(now=now)
|
2023-04-17 13:12:14 -04:00
|
|
|
|
|
|
|
# Remove scheduling fields if scheduling is disabled
|
|
|
|
if not scheduling_enabled:
|
|
|
|
self.fields.pop('schedule_at')
|
|
|
|
self.fields.pop('interval')
|
|
|
|
|
2023-03-28 19:49:18 +05:30
|
|
|
def clean(self):
|
2023-04-17 13:12:14 -04:00
|
|
|
scheduled_time = self.cleaned_data.get('schedule_at')
|
2023-03-28 19:49:18 +05:30
|
|
|
if scheduled_time and scheduled_time < local_now():
|
2022-12-08 18:17:13 -05:00
|
|
|
raise forms.ValidationError(_('Scheduled time must be in the future.'))
|
|
|
|
|
2023-04-17 13:12:14 -04:00
|
|
|
# When interval is used without schedule at, schedule for the current time
|
|
|
|
if self.cleaned_data.get('interval') and not scheduled_time:
|
2023-03-28 19:49:18 +05:30
|
|
|
self.cleaned_data['schedule_at'] = local_now()
|
|
|
|
|
|
|
|
return self.cleaned_data
|