right-tree/backend/right_tree/api/signals.py

37 lines
1.2 KiB
Python
Raw Normal View History

2023-03-30 15:29:23 +13:00
from pathlib import Path
from shutil import rmtree
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from .models import Export, ActivationKey, ActivationKeySet, Questionnaire
from .resource_generation_utils import storage
@receiver(post_delete, sender=Export)
2023-03-28 12:03:13 +13:00
def delete_export(sender, instance, *args, **kwargs):
"""Clean up created files on the filesystem when an export is deleted"""
2023-03-30 15:29:23 +13:00
path = storage.path(f"export_{instance.pk}")
if Path(path).exists():
rmtree(path)
@receiver(post_save, sender=ActivationKeySet)
def create_keys(sender, instance, created, *args, **kwargs):
"""Create n ActivationKey objects where n is the ActivationKeySet.size value"""
if created:
ActivationKey.objects.bulk_create([
ActivationKey(key_set=instance, remaining_activations=instance.initial_activations)
for _ in range(instance.size)
])
@receiver(post_save, sender=Questionnaire)
def activate_key(sender, instance, created, *args, **kwargs):
"""Consume one activation on the key associated with the created Questionnaire"""
if created and (key := instance.key):
key.remaining_activations -= 1
key.activations += 1
key.save()