42 lines
1.3 KiB
Python
42 lines
1.3 KiB
Python
from django.db.models.signals import post_save, post_delete
|
|
from django.dispatch import receiver
|
|
from channels.layers import get_channel_layer
|
|
from asgiref.sync import async_to_sync
|
|
from .models import Expense
|
|
|
|
@receiver(post_save, sender=Expense)
|
|
def expense_saved(sender, instance, created, **kwargs):
|
|
channel_layer = get_channel_layer()
|
|
action = 'created' if created else 'updated'
|
|
|
|
expense_data = {
|
|
'id': instance.id,
|
|
'amount': str(instance.amount_clp),
|
|
'category': instance.category.name if instance.category else None,
|
|
'project': instance.project.name if instance.project else None,
|
|
'user': instance.user.username if instance.user else None,
|
|
'date': instance.date.strftime('%Y-%m-%d'),
|
|
'description': instance.description,
|
|
}
|
|
|
|
async_to_sync(channel_layer.group_send)(
|
|
'expenses_updates',
|
|
{
|
|
'type': 'expense_update',
|
|
'action': action,
|
|
'expense': expense_data
|
|
}
|
|
)
|
|
|
|
@receiver(post_delete, sender=Expense)
|
|
def expense_deleted(sender, instance, **kwargs):
|
|
channel_layer = get_channel_layer()
|
|
async_to_sync(channel_layer.group_send)(
|
|
'expenses_updates',
|
|
{
|
|
'type': 'expense_update',
|
|
'action': 'deleted',
|
|
'expense': {'id': instance.id}
|
|
}
|
|
)
|