Skip to content

Instantly share code, notes, and snippets.

@dhruvbaldawa
Created January 31, 2018 05:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhruvbaldawa/601185f0582f58ac391ccf19d504ed2f to your computer and use it in GitHub Desktop.
Save dhruvbaldawa/601185f0582f58ac391ccf19d504ed2f to your computer and use it in GitHub Desktop.
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