edifact-mapper 0.8.0

EDIFACT to BO4E bidirectional conversion for the German energy market
Documentation
//! Factory for creating condition evaluators by variant name and format version.

use automapper_validation::{
    ConditionEvaluator, ConditionExprEvaluator, ConditionResult, EvaluationContext,
};
use mig_bo4e::pid_requirements::PidRequirements;
use mig_bo4e::pid_validation::PidValidationError;
use serde_json::Value;

/// Run condition-aware validation using a boxed evaluator.
///
/// Internally dispatches to a concrete generic call to satisfy `Sized` bounds.
pub fn validate_with_boxed_evaluator(
    evaluator: &dyn ConditionEvaluator,
    json: &Value,
    requirements: &PidRequirements,
    pid: &str,
    segments: &[mig_types::segment::OwnedSegment],
) -> Vec<PidValidationError> {
    // We need a Sized type to pass to ConditionExprEvaluator.
    // Use a newtype wrapper around &dyn ConditionEvaluator.
    struct EvalRef<'a>(&'a dyn ConditionEvaluator);

    impl ConditionEvaluator for EvalRef<'_> {
        fn evaluate(&self, condition: u32, ctx: &EvaluationContext) -> ConditionResult {
            self.0.evaluate(condition, ctx)
        }

        fn is_external(&self, condition: u32) -> bool {
            self.0.is_external(condition)
        }

        fn is_known(&self, condition: u32) -> bool {
            self.0.is_known(condition)
        }

        fn message_type(&self) -> &str {
            self.0.message_type()
        }

        fn format_version(&self) -> &str {
            self.0.format_version()
        }
    }

    let wrapper = EvalRef(evaluator);
    let external = automapper_validation::MapExternalProvider::new(Default::default());
    let ctx = EvaluationContext::new(pid, &external, segments);
    let expr_eval = ConditionExprEvaluator::new(&wrapper);
    crate::conditional_validation::validate_with_conditions(json, requirements, &expr_eval, &ctx)
}

/// Create a condition evaluator for the given variant and format version.
///
/// Returns `None` if no evaluator exists for the combination. See
/// [`automapper_validation::evaluator_for`].
pub fn create_evaluator(variant: &str, fv: &str) -> Option<Box<dyn ConditionEvaluator>> {
    automapper_validation::evaluator_for(variant, fv)
}

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

    #[test]
    fn test_known_evaluators_exist() {
        assert!(create_evaluator("UTILMD_Strom", "FV2504").is_some());
        assert!(create_evaluator("MSCONS", "FV2504").is_some());
        assert!(create_evaluator("ORDERS", "FV2510").is_some());
        assert!(create_evaluator("UTILMD_Gas", "FV2604").is_some());
    }

    #[test]
    fn test_unknown_evaluator_returns_none() {
        assert!(create_evaluator("NONEXISTENT", "FV2504").is_none());
        assert!(create_evaluator("UTILMD_Strom", "FV9999").is_none());
    }
}