silverapp / silver

Automated billing and payments for Django with a REST API
https://www.presslabs.com/code/silver/
Other
301 stars 80 forks source link

Is it possible to call an external handler at the start or end of a subscription? #665

Closed ivanscm closed 4 years ago

bogdanpetrea commented 5 years ago

Hi @ivanscm ,

There is a way currently, but it's not that nice. Here's an example of how you can do it now:

from django_fsm import post_transition
from django.db.models.signals import post_save

@receiver(post_save, sender=Subscription, dispatch_uid="_subscription_post_save")
def _subscription_post_save(*args, **kwargs):
    if kwargs['raw']:
        return

    subscription = kwargs['instance']

    # The subscription has just been created
    if kwargs['created']:
        # you can add custom logic here 
        custom_post_creation_handler(subscription)

    # The subscription has just been transitioned (and saved)
    elif getattr(subscription, '.recently_transitioned', False):
        source = getattr(subscription, '.source_state')

        delattr(subscription, '.recently_transitioned')
        delattr(subscription, '.source_state')

        # you can add custom logic here 
        custom_post_transition_handler(subscription, source=source, target=subscription.state)

@receiver(post_transition, sender=Subscription,
          dispatch_uid='_subscription_post_transition_callback')
def _subscription_post_transition_callback(sender, source, target, **kwargs):
    # The subscription has been transitioned, but not saved yet
    subscription = kwargs['instance']
    setattr(subscription, '.recently_transitioned', target)
    setattr(subscription, '.source_state', source)

It would've been better if Silver implemented this and sent signals directly...