7. Workflow and business rules
Objectives
- model explicit document states
- protect transitions with buttons and validation
- make irreversible effects idempotent
Mental model
A workflow is a state machine, not a decorative Selection. Transitions define permitted movement; buttons expose it; methods enforce conditions and side effects.
Guided practice
- Draw states and transitions before coding.
- Declare Workflow transitions and button visibility.
- Validate prerequisites before changing state.
- Perform accounting, numbering, or notifications exactly once.
- Define a controlled correction path instead of direct SQL.
Minimal example
from trytond.model import ModelSQL, ModelView, Workflow, fields
class Loan(Workflow, ModelSQL, ModelView):
"Library Loan"
__name__ = 'library.loan'
state = fields.Selection([
('draft', "Draft"), ('confirmed', "Confirmed"),
('done', "Done"), ('cancelled', "Cancelled"),
], "State", required=True, readonly=True)
@classmethod
@ModelView.button
@Workflow.transition('confirmed')
def confirm(cls, loans):
for loan in loans:
loan.check_can_confirm()
@classmethod
def default_state(cls):
return 'draft'
How to read the example
Keep the transition method batch-safe. Reopening finalized fiscal documents is not a generic reverse transition: analyze numbering, moves, reports, external transmissions, and audit history.
Exercise
Add return and cancellation transitions, write a transition table, then test every permitted and forbidden edge.
Run the exercise first with a minimal valid case, then add an invalid case and turn both into repeatable tests.
Verifiable result
The same call cannot create duplicate side effects, and invalid transitions fail with a translatable business message.
Common mistakes
- writing state directly
- sending external messages before the transaction is safe
- assuming one record per button call
- allowing deletion instead of a traceable cancellation
Ready-to-advance criteria
- I can explain the concepts without looking at the code.
- Valid and invalid cases have tests.
- I tested with a non-administrative user.
- I know how to upgrade and restore the training database.
Version and references
Series 8.0 requires at least Python 3.10 according to official metadata. The official server declares its project with pyproject.toml; new modules should use modern packaging and verify wheel contents. Do not confuse this historical minimum with the Python version certified by your organization.
This edition pins examples and dependencies to series 8.0. Check the official 8.0 tutorial, server API, and source branch before moving a pattern to production.