right-tree/backend/right_tree/api/signals.py
Matthew Northcott 13c8436d98 [#41] Allow users to download the user/planng guide for a payment
- backend changes to support physical and digital checkouts
2023-04-20 14:59:00 +12:00

36 lines
1.2 KiB
Python

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)
def delete_export(sender, instance, *args, **kwargs):
"""Clean up created files on the filesystem when an export is deleted"""
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()