Created
January 31, 2018 05:56
-
-
Save dhruvbaldawa/601185f0582f58ac391ccf19d504ed2f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Payments(models.Model): | |
STATES = { | |
'started': 'Started', | |
'captured': 'Captured', | |
'completed': 'Completed', | |
'incomplete': 'Incomplete', # new incomplete state for us | |
} | |
def __init__(self, *args, **kwargs): | |
super(Payments, self).__init__(*args, **kwargs) | |
# Initialize the state machine | |
self.machine = Machine( | |
model=self, | |
states=self.STATES.keys(), | |
initial='started', | |
after_state_change='save', | |
) | |
self.machine.add_transition( | |
trigger='capture', | |
source='started', | |
destination='captured', | |
# we check only enter captured state if the payment is captured | |
# otherwise we go to incomplete, as you can see in the next | |
# transition | |
conditions=['has_captured_payment',], | |
) | |
self.machine.add_transition( | |
trigger='capture', | |
source='started', | |
destination='incomplete', | |
) | |
self.machine.add_transition( | |
trigger='retry', | |
source='incomplete', | |
destination='completed', | |
# similarly, we only go from incomplete to complete if the payment | |
# is captured, otherwise we stay as incomplete | |
conditions=['has_captured_payment',], | |
) | |
self.machine.add_transition( | |
trigger='retry', | |
source='incomplete', | |
destination='incomplete', | |
) | |
self.machine.add_transition( | |
trigger='complete', | |
source='captured', | |
destination='completed', | |
) | |
# we notify the user whenever we enter “complete” state, this | |
# this calls self.notify_user() | |
self.machine.on_enter_complete('notify_user') | |
def has_captured_payment(self): | |
try: | |
self.contact_payment_gateway() | |
except PaymentGatewayException: | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment