backbone-events 0.4.0

Events core + the sale/booth/crm/sms/desk overlay — registrations under one authoritative seat counter, the sale seam (order-minted registrations, forward-only paid heal, SO-cancel mirror cascade), booth bookings with the DB exclusivity wall, closed-vocabulary lead rules through a host sink port, the dual-channel (mail/sms) self-arming scheduler, and the exact-match desk verb (Odoo event port, core + overlay)
//! State machine for registration_state workflow
//!
//! Generated by metaphor-schema

use serde::{Deserialize, Serialize};
use std::str::FromStr;

/// States for registration_state workflow
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum registration_stateState {
    Draft,
    /// Initial state
    Open,
    /// Final state
    Done,
    Cancel,
}

impl Default for registration_stateState {
    fn default() -> Self {
        Self::Open
    }
}

impl std::fmt::Display for registration_stateState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Draft => write!(f, "draft"),
            Self::Open => write!(f, "open"),
            Self::Done => write!(f, "done"),
            Self::Cancel => write!(f, "cancel"),
        }
    }
}

impl FromStr for registration_stateState {
    type Err = StateMachineError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "draft" => Ok(Self::Draft),
            "open" => Ok(Self::Open),
            "done" => Ok(Self::Done),
            "cancel" => Ok(Self::Cancel),
            _ => Err(StateMachineError::InvalidState(s.to_string())),
        }
    }
}

impl registration_stateState {
    /// Check if this is the initial state
    pub fn is_initial(&self) -> bool {
        matches!(self, Self::Open)
    }

    /// Check if this is a final state
    pub fn is_final(&self) -> bool {
        matches!(self, Self::Done)
    }

    /// Get all possible states
    pub fn all() -> Vec<Self> {
        vec![
            Self::Draft,
            Self::Open,
            Self::Done,
            Self::Cancel,
        ]
    }
}

/// Transitions for registration_state workflow
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum registration_stateTransition {
    /// * -> draft
    SetDraft,
    /// * -> open
    Confirm,
    /// * -> done
    SetDone,
    /// * -> cancel
    Cancel,
}

impl std::fmt::Display for registration_stateTransition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SetDraft => write!(f, "set_draft"),
            Self::Confirm => write!(f, "confirm"),
            Self::SetDone => write!(f, "set_done"),
            Self::Cancel => write!(f, "cancel"),
        }
    }
}

impl FromStr for registration_stateTransition {
    type Err = StateMachineError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "set_draft" => Ok(Self::SetDraft),
            "confirm" => Ok(Self::Confirm),
            "set_done" => Ok(Self::SetDone),
            "cancel" => Ok(Self::Cancel),
            _ => Err(StateMachineError::InvalidTransition(s.to_string())),
        }
    }
}

impl registration_stateTransition {
    /// Get the target state of this transition
    pub fn target_state(&self) -> registration_stateState {
        match self {
            Self::SetDraft => registration_stateState::Draft,
            Self::Confirm => registration_stateState::Open,
            Self::SetDone => registration_stateState::Done,
            Self::Cancel => registration_stateState::Cancel,
        }
    }

    /// Get all transitions
    pub fn all() -> Vec<Self> {
        vec![
            Self::SetDraft,
            Self::Confirm,
            Self::SetDone,
            Self::Cancel,
        ]
    }

    /// Get allowed roles for this transition
    pub fn allowed_roles(&self) -> &'static [&'static str] {
        match self {
            Self::SetDraft => &[],
            Self::Confirm => &[],
            Self::SetDone => &[],
            Self::Cancel => &[],
        }
    }
}

use super::StateMachineError;

/// State machine for registration_state workflow
#[derive(Debug, Clone)]
pub struct registration_stateStateMachine {
    current_state: registration_stateState,
}

impl registration_stateStateMachine {
    /// Create a new state machine with initial state
    pub fn new() -> Self {
        Self {
            current_state: registration_stateState::default(),
        }
    }

    /// Create from an existing state
    pub fn from_state(state: registration_stateState) -> Self {
        Self { current_state: state }
    }

    /// Get the current state
    pub fn current_state(&self) -> registration_stateState {
        self.current_state
    }

    /// Check if a transition is allowed from the current state
    pub fn can_transition(&self, transition: registration_stateTransition) -> bool {
        if matches!(self.current_state, registration_stateState::Done) {
            return false;
        }

        match (self.current_state, transition) {
            (_, registration_stateTransition::SetDraft) => true,
            (_, registration_stateTransition::Confirm) => true,
            (_, registration_stateTransition::SetDone) => true,
            (_, registration_stateTransition::Cancel) => true,
            _ => false,
        }
    }

    /// Check if a transition is allowed for a given role
    pub fn can_transition_with_role(&self, transition: registration_stateTransition, role: &str) -> bool {
        if !self.can_transition(transition) {
            return false;
        }

        let allowed_roles = transition.allowed_roles();
        if allowed_roles.is_empty() {
            return true; // No role restriction
        }

        allowed_roles.iter().any(|r| *r == role || *r == "*")
    }

    /// Apply a transition, returning the new state
    pub fn transition(&mut self, transition: registration_stateTransition) -> Result<registration_stateState, StateMachineError> {
        if !self.can_transition(transition) {
            return Err(StateMachineError::TransitionNotAllowed {
                transition: transition.to_string(),
                from: self.current_state.to_string(),
            });
        }

        self.current_state = transition.target_state();
        Ok(self.current_state)
    }

    /// Apply a transition with role check
    pub fn transition_with_role(&mut self, transition: registration_stateTransition, role: &str) -> Result<registration_stateState, StateMachineError> {
        // Check basic transition validity first
        if !self.can_transition(transition) {
            return Err(StateMachineError::TransitionNotAllowed {
                transition: transition.to_string(),
                from: self.current_state.to_string(),
            });
        }

        // Check role authorization
        if !self.can_transition_with_role(transition, role) {
            return Err(StateMachineError::RoleNotAuthorized {
                role: role.to_string(),
                transition: transition.to_string(),
            });
        }

        self.current_state = transition.target_state();
        Ok(self.current_state)
    }

    /// Get all available transitions from the current state
    pub fn available_transitions(&self) -> Vec<registration_stateTransition> {
        registration_stateTransition::all()
            .into_iter()
            .filter(|t| self.can_transition(*t))
            .collect()
    }

    /// Get all available transitions for a given role
    pub fn available_transitions_for_role(&self, role: &str) -> Vec<registration_stateTransition> {
        registration_stateTransition::all()
            .into_iter()
            .filter(|t| self.can_transition_with_role(*t, role))
            .collect()
    }

    /// Attempt to transition directly to a target state.
    ///
    /// Finds any transition that leads to the target state and applies it.
    /// Returns Err if no valid transition leads from current state to target.
    pub fn transition_to_state(&mut self, target: registration_stateState) -> Result<registration_stateState, StateMachineError> {
        let valid = registration_stateTransition::all().into_iter()
            .filter(|t| self.can_transition(*t))
            .find(|t| t.target_state() == target);
        match valid {
            Some(t) => self.transition(t),
            None => Err(StateMachineError::TransitionNotAllowed {
                transition: target.to_string(),
                from: self.current_state.to_string(),
            }),
        }
    }
}

impl Default for registration_stateStateMachine {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_initial_state() {
        let sm = registration_stateStateMachine::new();
        assert_eq!(sm.current_state(), registration_stateState::Open);
        assert!(sm.current_state().is_initial());
    }

    #[test]
    fn test_valid_transition() {
        let mut sm = registration_stateStateMachine::new();
        assert!(sm.can_transition(registration_stateTransition::SetDraft));
        let result = sm.transition(registration_stateTransition::SetDraft);
        assert!(result.is_ok());
        assert_eq!(sm.current_state(), registration_stateState::Draft);
    }

    #[test]
    fn test_invalid_transition() {
        // All transitions are valid from all states (wildcard), test passes
        assert!(true);
    }

    #[test]
    fn test_state_parsing() {
        let state: registration_stateState = "draft".parse().unwrap();
        assert_eq!(state, registration_stateState::Draft);
    }

    #[test]
    fn test_available_transitions() {
        let sm = registration_stateStateMachine::new();
        let available = sm.available_transitions();
        // Should have at least some transitions available from initial state
        assert!(!available.is_empty() || sm.current_state().is_final());
    }
}