Use Signal to calculate Priority

This commit is contained in:
sosokker 2023-11-06 22:18:20 +07:00
parent 39601926ff
commit 3baf716c6f
3 changed files with 30 additions and 21 deletions

View File

@ -4,3 +4,6 @@ from django.apps import AppConfig
class TasksConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'tasks'
def ready(self):
import tasks.signals

View File

@ -68,27 +68,8 @@ class Todo(Todo):
priority = models.PositiveSmallIntegerField(choices=EisenhowerMatrix.choices, default=EisenhowerMatrix.NOT_IMPORTANT_NOT_URGENT)
def calculate_eisenhower_matrix_category(self):
if self.end_event:
time_until_due = (self.end_event - timezone.now()).days
else:
time_until_due = float('inf')
urgency_threshold = 3
importance_threshold = 3
if time_until_due <= urgency_threshold and self.importance >= importance_threshold:
return Todo.EisenhowerMatrix.IMPORTANT_URGENT
elif time_until_due > urgency_threshold and self.importance >= importance_threshold:
return Todo.EisenhowerMatrix.IMPORTANT_NOT_URGENT
elif time_until_due <= urgency_threshold and self.importance < importance_threshold:
return Todo.EisenhowerMatrix.NOT_IMPORTANT_URGENT
else:
return Todo.EisenhowerMatrix.NOT_IMPORTANT_NOT_URGENT
def save(self, *args, **kwargs):
self.priority = self.calculate_eisenhower_matrix_category()
super(Todo, self).save(*args, **kwargs)
def __str__(self):
return self.title
class Subtask(models.Model):

25
backend/tasks/signals.py Normal file
View File

@ -0,0 +1,25 @@
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.utils import timezone
from tasks.models import Todo
@receiver(pre_save, sender=Todo)
def update_priority(sender, instance, **kwargs):
if instance.end_event:
time_until_due = (instance.end_event - timezone.now()).days
else:
time_until_due = float('inf')
urgency_threshold = 3
importance_threshold = 3
if time_until_due <= urgency_threshold and instance.importance >= importance_threshold:
instance.priority = Todo.EisenhowerMatrix.IMPORTANT_URGENT
elif time_until_due > urgency_threshold and instance.importance >= importance_threshold:
instance.priority = Todo.EisenhowerMatrix.IMPORTANT_NOT_URGENT
elif time_until_due <= urgency_threshold and instance.importance < importance_threshold:
instance.priority = Todo.EisenhowerMatrix.NOT_IMPORTANT_URGENT
else:
instance.priority = Todo.EisenhowerMatrix.NOT_IMPORTANT_NOT_URGENT