
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "auto_examples/order_control_machine.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        Click :ref:`here <sphx_glr_download_auto_examples_order_control_machine.py>`
        to download the full example code

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_auto_examples_order_control_machine.py:


Order control machine
---------------------

An StateMachine that demonstrates :ref:`Guards` being used to control the state flow.

.. GENERATED FROM PYTHON SOURCE LINES 8-47



.. image-sg:: /auto_examples/images/sphx_glr_order_control_machine_001.svg
   :alt: order control machine
   :srcset: /auto_examples/images/sphx_glr_order_control_machine_001.svg
   :class: sphx-glr-single-img





.. code-block:: default

    from statemachine import State
    from statemachine import StateMachine


    class OrderControl(StateMachine):
        waiting_for_payment = State("Waiting for payment", initial=True)
        processing = State("Processing")
        shipping = State("Shipping")
        completed = State("Completed", final=True)

        add_to_order = waiting_for_payment.to(waiting_for_payment)
        receive_payment = waiting_for_payment.to(
            processing, cond="payments_enough"
        ) | waiting_for_payment.to(waiting_for_payment, unless="payments_enough")
        process_order = processing.to(shipping, cond="payment_received")
        ship_order = shipping.to(completed)

        def __init__(self):
            self.order_total = 0
            self.payments = []
            self.payment_received = False
            super(OrderControl, self).__init__()

        def payments_enough(self, amount):
            return sum(self.payments) + amount >= self.order_total

        def before_add_to_order(self, amount):
            self.order_total += amount
            return self.order_total

        def before_receive_payment(self, amount):
            self.payments.append(amount)
            return self.payments

        def after_receive_payment(self):
            self.payment_received = True

        def on_enter_waiting_for_payment(self):
            self.payment_received = False


.. _sphx_glr_download_auto_examples_order_control_machine.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example


    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: order_control_machine.py <order_control_machine.py>`

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: order_control_machine.ipynb <order_control_machine.ipynb>`
