pub(crate) mod location;
pub use location::ContrlLocation;
pub(crate) use location::{Anchor, Detail, Target, anchor_for_code, detail_of, place};
use crate::envelope::{
FunctionalGroupEnvelope, InterchangeEnvelope, MessageEnvelope, ValidatedInterchange,
};
use crate::model::{Element, OwnedElement, OwnedSegment, Segment};
use crate::recover::{MessageIdentity, RecoveredInterchange};
use crate::report::{ValidationIssue, ValidationReport};
use crate::{EdifactError, Writer};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Action {
Rejected,
Acknowledged,
Received,
}
impl Action {
#[must_use]
pub const fn code(self) -> &'static str {
match self {
Self::Rejected => "4",
Self::Acknowledged => "7",
Self::Received => "8",
}
}
}
impl std::fmt::Display for Action {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.code())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ReportingLevel {
Interchange,
Group,
Message,
Segment,
DataElement,
}
impl ReportingLevel {
#[must_use]
pub const fn tag(self) -> &'static str {
match self {
Self::Interchange => "UCI",
Self::Group => "UCF",
Self::Message => "UCM",
Self::Segment => "UCS",
Self::DataElement => "UCD",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SyntaxError {
SyntaxVersionNotSupported,
NotActualRecipient,
InvalidValue,
Missing,
ValueNotSupportedHere,
NotSupportedHere,
TooManyConstituents,
NoAgreement,
Unspecified,
InvalidAsServiceCharacter,
InvalidCharacters,
InvalidServiceCharacters,
UnknownSender,
TooOld,
TestIndicatorNotSupported,
DuplicateDetected,
ReferencesDoNotMatch,
ControlCountMismatch,
GroupsAndMessagesMixed,
LowerLevelEmpty,
InvalidOccurrenceOutsideMessage,
TooManyRepetitions,
TooManyGroupRepetitions,
InvalidCharacterType,
DataElementTooLong,
DataElementTooShort,
TrailingSeparator,
CharacterSetNotSupported,
EnvelopeFunctionalityNotSupported,
}
impl SyntaxError {
#[must_use]
pub const fn code(self) -> &'static str {
match self {
Self::SyntaxVersionNotSupported => "2",
Self::NotActualRecipient => "7",
Self::InvalidValue => "12",
Self::Missing => "13",
Self::ValueNotSupportedHere => "14",
Self::NotSupportedHere => "15",
Self::TooManyConstituents => "16",
Self::NoAgreement => "17",
Self::Unspecified => "18",
Self::InvalidAsServiceCharacter => "20",
Self::InvalidCharacters => "21",
Self::InvalidServiceCharacters => "22",
Self::UnknownSender => "23",
Self::TooOld => "24",
Self::TestIndicatorNotSupported => "25",
Self::DuplicateDetected => "26",
Self::ReferencesDoNotMatch => "28",
Self::ControlCountMismatch => "29",
Self::GroupsAndMessagesMixed => "30",
Self::LowerLevelEmpty => "32",
Self::InvalidOccurrenceOutsideMessage => "33",
Self::TooManyRepetitions => "35",
Self::TooManyGroupRepetitions => "36",
Self::InvalidCharacterType => "37",
Self::DataElementTooLong => "39",
Self::DataElementTooShort => "40",
Self::TrailingSeparator => "45",
Self::CharacterSetNotSupported => "46",
Self::EnvelopeFunctionalityNotSupported => "47",
}
}
#[must_use]
pub const fn description(self) -> &'static str {
match self {
Self::SyntaxVersionNotSupported => "syntax version or level not supported",
Self::NotActualRecipient => "interchange recipient not actual recipient",
Self::InvalidValue => "invalid value",
Self::Missing => "missing",
Self::ValueNotSupportedHere => "value not supported in this position",
Self::NotSupportedHere => "not supported in this position",
Self::TooManyConstituents => "too many constituents",
Self::NoAgreement => "no agreement",
Self::Unspecified => "unspecified error",
Self::InvalidAsServiceCharacter => "character invalid as service character",
Self::InvalidCharacters => "invalid character(s)",
Self::InvalidServiceCharacters => "invalid service character(s)",
Self::UnknownSender => "unknown interchange sender",
Self::TooOld => "too old",
Self::TestIndicatorNotSupported => "test indicator not supported",
Self::DuplicateDetected => "duplicate detected",
Self::ReferencesDoNotMatch => "references do not match",
Self::ControlCountMismatch => {
"control or octet count does not match number of instances received"
}
Self::GroupsAndMessagesMixed => "groups and messages/packages mixed",
Self::LowerLevelEmpty => "lower level empty",
Self::InvalidOccurrenceOutsideMessage => {
"invalid occurrence outside message, package or group"
}
Self::TooManyRepetitions => "too many repetitions",
Self::TooManyGroupRepetitions => "too many segment group repetitions",
Self::InvalidCharacterType => "invalid type of character(s)",
Self::DataElementTooLong => "data element too long",
Self::DataElementTooShort => "data element too short",
Self::TrailingSeparator => "trailing separator",
Self::CharacterSetNotSupported => "character set not supported",
Self::EnvelopeFunctionalityNotSupported => "envelope functionality not supported",
}
}
#[must_use]
pub const fn permitted_at(self, level: ReportingLevel) -> bool {
use ReportingLevel as L;
match self {
Self::SyntaxVersionNotSupported
| Self::NotActualRecipient
| Self::InvalidAsServiceCharacter
| Self::UnknownSender
| Self::CharacterSetNotSupported => matches!(l_of(level), L::Interchange),
Self::InvalidValue
| Self::Missing
| Self::ValueNotSupportedHere
| Self::NotSupportedHere
| Self::TooManyConstituents
| Self::Unspecified
| Self::InvalidCharacters => true,
Self::NoAgreement | Self::TestIndicatorNotSupported => matches!(
l_of(level),
L::Interchange | L::Group | L::Message | L::Segment
),
Self::InvalidServiceCharacters => true,
Self::TooOld => matches!(l_of(level), L::Interchange | L::Group),
Self::DuplicateDetected
| Self::ReferencesDoNotMatch
| Self::ControlCountMismatch
| Self::GroupsAndMessagesMixed => {
matches!(l_of(level), L::Interchange | L::Group | L::Message)
}
Self::LowerLevelEmpty | Self::InvalidOccurrenceOutsideMessage => {
matches!(l_of(level), L::Interchange | L::Group)
}
Self::TooManyRepetitions => {
matches!(l_of(level), L::Message | L::Segment | L::DataElement)
}
Self::TooManyGroupRepetitions => matches!(l_of(level), L::Segment),
Self::InvalidCharacterType | Self::DataElementTooLong | Self::DataElementTooShort => {
matches!(
l_of(level),
L::Interchange | L::Group | L::Message | L::DataElement
)
}
Self::TrailingSeparator => matches!(
l_of(level),
L::Interchange | L::Group | L::Message | L::Segment
),
Self::EnvelopeFunctionalityNotSupported => matches!(l_of(level), L::Group | L::Message),
}
}
#[must_use]
pub fn for_error(error: &EdifactError) -> Self {
use EdifactError as E;
match error {
E::MessageCountMismatch { .. }
| E::GroupCountMismatch { .. }
| E::SegmentCountMismatch { .. } => Self::ControlCountMismatch,
E::QualifierMismatch { .. } => Self::ReferencesDoNotMatch,
E::DuplicateReference { .. } => Self::DuplicateDetected,
E::MissingRequiredElement { .. }
| E::MissingRequiredComponent { .. }
| E::MissingSegment { .. } => Self::Missing,
E::InvalidCodeValue { .. } | E::InvalidFieldValue { .. } => Self::InvalidValue,
E::InvalidSegmentForMessage { .. } | E::ConditionalRequirementNotMet { .. } => {
Self::NotSupportedHere
}
E::InvalidElementCount { .. } | E::InvalidComponentCount { .. } => {
Self::TooManyConstituents
}
E::UnrecognisedSyntaxIdentifier(_) | E::UnsupportedCharset { .. } => {
Self::CharacterSetNotSupported
}
E::CharacterNotInRepertoire { .. } | E::InvalidText { .. } => Self::InvalidCharacters,
E::InvalidUna | E::InvalidDelimiter { .. } | E::InvalidReleaseSequence { .. } => {
Self::InvalidServiceCharacters
}
E::EmptyInterchange { .. } | E::EmptyMessage { .. } | E::EmptyGroup { .. } => {
Self::LowerLevelEmpty
}
E::SegmentWithoutDataElements { .. } => Self::Missing,
E::BlankDataElementValue { .. } => Self::InvalidValue,
E::PackageNotSupported { .. }
| E::InteractiveSegmentNotSupported { .. }
| E::SecuritySegmentNotSupported { .. } => Self::EnvelopeFunctionalityNotSupported,
E::ReservedServiceSegmentTag { .. } => Self::NotSupportedHere,
E::DataAfterInterchangeTrailer { .. } => Self::InvalidOccurrenceOutsideMessage,
E::UnsupportedSyntaxVersion { .. } => Self::SyntaxVersionNotSupported,
E::InvalidDateTime { .. } => Self::InvalidValue,
E::SegmentTooLong { .. } | E::DataElementTooLong { .. } => Self::DataElementTooLong,
E::DataElementTooShort { .. } => Self::DataElementTooShort,
E::InvalidCharacterType { .. } => Self::InvalidCharacterType,
E::TooManyRepetitions { .. } | E::TooManySegmentOccurrences { .. } => {
Self::TooManyRepetitions
}
E::TooManyGroupOccurrences { .. } => Self::TooManyGroupRepetitions,
E::SegmentNotPlaced { .. } => Self::NotSupportedHere,
E::TrailingSeparator { .. } => Self::TrailingSeparator,
E::GroupsAndMessagesMixed { .. } => Self::GroupsAndMessagesMixed,
E::InsignificantCharacters { .. } => Self::InvalidValue,
E::UnexpectedDataToken { .. } | E::InvalidSegmentTag(_) => {
Self::InvalidOccurrenceOutsideMessage
}
_ => Self::Unspecified,
}
}
#[must_use]
pub fn for_issue(issue: &ValidationIssue) -> Self {
match issue.error_code() {
Some("E004" | "E005" | "E054") => Self::ControlCountMismatch,
Some("E016") => Self::ReferencesDoNotMatch,
Some("E032") => Self::DuplicateDetected,
Some("E008" | "E015" | "E021" | "E046") => Self::Missing,
Some("E014" | "E027" | "E045" | "E060") => Self::InvalidValue,
Some("E011" | "E017" | "E057" | "E068") => Self::NotSupportedHere,
Some("E012" | "E013") => Self::TooManyConstituents,
Some("E031" | "E039") => Self::CharacterSetNotSupported,
Some("E003" | "E038") => Self::InvalidCharacters,
Some("E002" | "E007" | "E019") => Self::InvalidServiceCharacters,
Some("E042" | "E043" | "E061") => Self::LowerLevelEmpty,
Some("E044" | "E055" | "E056") => Self::EnvelopeFunctionalityNotSupported,
Some("E059") => Self::SyntaxVersionNotSupported,
Some("E020" | "E049") => Self::DataElementTooLong,
Some("E050") => Self::DataElementTooShort,
Some("E048") => Self::InvalidCharacterType,
Some("E047" | "E069") => Self::TooManyRepetitions,
Some("E070") => Self::TooManyGroupRepetitions,
Some("E051") => Self::TrailingSeparator,
Some("E052") => Self::GroupsAndMessagesMixed,
Some("E053") => Self::InvalidValue,
Some("E006" | "E028" | "E058") => Self::InvalidOccurrenceOutsideMessage,
_ => Self::Unspecified,
}
}
}
#[inline]
const fn l_of(level: ReportingLevel) -> ReportingLevel {
level
}
impl std::fmt::Display for SyntaxError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.code(), self.description())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ContrlIdentifier {
version: String,
release: String,
agency: String,
association: Option<String>,
}
impl ContrlIdentifier {
#[must_use]
pub fn syntax_4() -> Self {
Self {
version: "4".to_owned(),
release: "1".to_owned(),
agency: "UN".to_owned(),
association: None,
}
}
#[must_use]
pub fn syntax_3() -> Self {
Self {
version: "D".to_owned(),
release: "3".to_owned(),
agency: "UN".to_owned(),
association: None,
}
}
#[must_use]
pub fn for_syntax_version(version: &str) -> Self {
match version {
"1" | "2" | "3" => Self::syntax_3(),
_ => Self::syntax_4(),
}
}
pub fn new(
version: impl Into<String>,
release: impl Into<String>,
agency: impl Into<String>,
) -> Result<Self, EdifactError> {
Ok(Self {
version: identifier_component("0052", version.into(), 3)?,
release: identifier_component("0054", release.into(), 3)?,
agency: identifier_component("0051", agency.into(), 3)?,
association: None,
})
}
pub fn with_association(mut self, code: impl Into<String>) -> Result<Self, EdifactError> {
self.association = Some(identifier_component("0057", code.into(), 6)?);
Ok(self)
}
#[must_use]
pub fn version(&self) -> &str {
&self.version
}
#[must_use]
pub fn release(&self) -> &str {
&self.release
}
#[must_use]
pub fn agency(&self) -> &str {
&self.agency
}
#[must_use]
pub fn association(&self) -> Option<&str> {
self.association.as_deref()
}
fn components(&self) -> Vec<String> {
let mut out = vec![
"CONTRL".to_owned(),
self.version.clone(),
self.release.clone(),
self.agency.clone(),
];
if let Some(association) = &self.association {
out.push(association.clone());
}
out
}
}
fn identifier_component(
data_element: &'static str,
value: String,
max: usize,
) -> Result<String, EdifactError> {
let length = value.chars().count();
if length == 0 || length > max {
return Err(EdifactError::InvalidContrlIdentifier {
data_element,
value,
});
}
Ok(value)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActionPolicy {
interchange: u8,
group: u8,
message: u8,
}
const ALL_ACTIONS: u8 = 0b111;
const fn action_bit(action: Action) -> u8 {
match action {
Action::Rejected => 0b001,
Action::Acknowledged => 0b010,
Action::Received => 0b100,
}
}
impl Default for ActionPolicy {
fn default() -> Self {
Self {
interchange: ALL_ACTIONS,
group: ALL_ACTIONS,
message: ALL_ACTIONS,
}
}
}
impl ActionPolicy {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn permit(mut self, level: ReportingLevel, actions: &[Action]) -> Self {
let set = actions.iter().fold(0, |set, a| set | action_bit(*a));
match level {
ReportingLevel::Interchange => self.interchange = set,
ReportingLevel::Group => self.group = set,
ReportingLevel::Message => self.message = set,
ReportingLevel::Segment | ReportingLevel::DataElement => {}
}
self
}
#[must_use]
pub fn permits(&self, level: ReportingLevel, action: Action) -> bool {
let set = match level {
ReportingLevel::Interchange => self.interchange,
ReportingLevel::Group => self.group,
ReportingLevel::Message => self.message,
ReportingLevel::Segment | ReportingLevel::DataElement => return true,
};
set & action_bit(action) != 0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum RejectionScope {
#[default]
PerLevel,
Interchange,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ContrlOptions {
identifier: Option<ContrlIdentifier>,
actions: ActionPolicy,
rejection: RejectionScope,
report_warnings: bool,
}
impl Default for ContrlOptions {
fn default() -> Self {
Self {
identifier: None,
actions: ActionPolicy::default(),
rejection: RejectionScope::default(),
report_warnings: true,
}
}
}
impl ContrlOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn identifier(mut self, id: ContrlIdentifier) -> Self {
self.identifier = Some(id);
self
}
#[must_use]
pub fn actions(mut self, policy: ActionPolicy) -> Self {
self.actions = policy;
self
}
#[must_use]
pub fn rejection(mut self, scope: RejectionScope) -> Self {
self.rejection = scope;
self
}
#[must_use]
pub fn report_warnings(mut self, report: bool) -> Self {
self.report_warnings = report;
self
}
fn resolve_identifier(&self, syntax_version: &str) -> ContrlIdentifier {
self.identifier
.clone()
.unwrap_or_else(|| ContrlIdentifier::for_syntax_version(syntax_version))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Finding {
location: ContrlLocation,
rejects: bool,
states_code: bool,
}
impl Finding {
fn level(&self) -> ReportingLevel {
self.location.level()
}
fn message_index(&self) -> Option<usize> {
match self.level() {
ReportingLevel::Message | ReportingLevel::Segment | ReportingLevel::DataElement => {
self.location.message()
}
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct LevelError {
code: SyntaxError,
service_segment: Option<&'static str>,
element: Option<u32>,
component: Option<u32>,
}
impl LevelError {
const fn code(code: SyntaxError) -> Self {
Self {
code,
service_segment: None,
element: None,
component: None,
}
}
fn of(location: &ContrlLocation) -> Self {
let service_segment = location.service_segment();
Self {
code: location.error(),
service_segment,
element: service_segment.and(location.element_position()),
component: service_segment.and(location.component_position()),
}
}
fn push_onto(&self, elements: &mut Vec<OwnedElement>) {
elements.push(OwnedElement::of(&[self.code.code()]));
if let Some(tag) = self.service_segment {
elements.push(OwnedElement::of(&[tag]));
if let Some(element) = self.element {
let mut s011 = vec![element.to_string()];
if let Some(component) = self.component {
s011.push(component.to_string());
}
elements.push(OwnedElement::of(&s011));
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct MessageName {
reference: String,
message_type: String,
version: String,
release: String,
agency: String,
association: String,
}
impl From<&MessageEnvelope> for MessageName {
fn from(message: &MessageEnvelope) -> Self {
Self {
reference: message.message_ref.clone(),
message_type: message.message_type.clone(),
version: message.version.clone(),
release: message.release.clone(),
agency: message.controlling_agency.clone(),
association: message.association_code.clone(),
}
}
}
impl From<&MessageIdentity> for MessageName {
fn from(identity: &MessageIdentity) -> Self {
Self {
reference: identity.message_ref().to_owned(),
message_type: identity.message_type().to_owned(),
version: identity.version().to_owned(),
release: identity.release().to_owned(),
agency: identity.controlling_agency().to_owned(),
association: identity.association_code().to_owned(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct GroupName {
reference: String,
sender: String,
sender_qualifier: String,
recipient: String,
recipient_qualifier: String,
}
impl From<&FunctionalGroupEnvelope> for GroupName {
fn from(group: &FunctionalGroupEnvelope) -> Self {
Self {
reference: group.group_ref.clone(),
sender: group.app_sender.clone(),
sender_qualifier: group.app_sender_qualifier.clone(),
recipient: group.app_recipient.clone(),
recipient_qualifier: group.app_recipient_qualifier.clone(),
}
}
}
struct Shape {
messages: Vec<(Option<MessageName>, Option<usize>)>,
groups: Vec<Option<GroupName>>,
}
impl Shape {
fn of_validated(subject: &ValidatedInterchange) -> Self {
if subject.functional_groups.is_empty() {
return Self {
messages: subject
.messages
.iter()
.map(|m| (Some(MessageName::from(m)), None))
.collect(),
groups: Vec::new(),
};
}
let mut messages = Vec::new();
let mut groups = Vec::new();
for (index, group) in subject.functional_groups.iter().enumerate() {
messages.extend(
group
.messages
.iter()
.map(|m| (Some(MessageName::from(m)), Some(index))),
);
groups.push(Some(GroupName::from(group)));
}
Self { messages, groups }
}
fn of_recovered(recovered: &RecoveredInterchange<'_>) -> Self {
Self {
messages: recovered
.messages()
.iter()
.map(|w| (w.identity().map(MessageName::from), w.group()))
.collect(),
groups: (0..recovered.groups().len())
.map(|g| {
let reference = recovered.groups()[g].group_ref()?.to_owned();
let [sender, sender_qualifier, recipient, recipient_qualifier] =
recovered.group_parties(g);
Some(GroupName {
reference,
sender,
sender_qualifier,
recipient,
recipient_qualifier,
})
})
.collect(),
}
}
fn names_message(&self, index: usize) -> bool {
let Some((name, group)) = self.messages.get(index) else {
return false;
};
name.is_some() && (self.groups.is_empty() || group.is_some_and(|g| self.names_group(g)))
}
fn names_group(&self, index: usize) -> bool {
self.groups.get(index).is_some_and(Option::is_some)
}
}
#[derive(Debug, Clone)]
pub struct Contrl {
control_ref: String,
sender: String,
sender_qualifier: String,
recipient: String,
recipient_qualifier: String,
identifier: ContrlIdentifier,
action: Action,
interchange_error: Option<LevelError>,
message_ref: Option<String>,
messages: Vec<MessageReport>,
groups: Vec<GroupReport>,
findings: Vec<Finding>,
}
#[derive(Debug, Clone)]
struct MessageReport {
index: usize,
name: MessageName,
action: Action,
error: Option<LevelError>,
}
#[derive(Debug, Clone)]
struct GroupReport {
name: GroupName,
action: Action,
error: Option<LevelError>,
messages: Vec<MessageReport>,
}
impl Contrl {
fn base(interchange: &InterchangeEnvelope, action: Action, options: &ContrlOptions) -> Self {
Self {
control_ref: interchange.header.control_ref.clone(),
sender: interchange.header.sender.id.clone(),
sender_qualifier: interchange
.header
.sender
.qualifier
.clone()
.unwrap_or_default(),
recipient: interchange.header.recipient.id.clone(),
recipient_qualifier: interchange
.header
.recipient
.qualifier
.clone()
.unwrap_or_default(),
identifier: options
.resolve_identifier(&interchange.header.syntax_version.number().to_string()),
action,
interchange_error: None,
message_ref: None,
messages: Vec::new(),
groups: Vec::new(),
findings: Vec::new(),
}
}
#[must_use]
pub fn receipt(interchange: &InterchangeEnvelope) -> Self {
Self::base(interchange, Action::Received, &ContrlOptions::default())
}
pub fn receipt_with(
interchange: &InterchangeEnvelope,
options: &ContrlOptions,
) -> Result<Self, EdifactError> {
Self::base(interchange, Action::Received, options).checked(options)
}
#[must_use]
pub fn acknowledgement(subject: &ValidatedInterchange) -> Self {
Self::base(
&subject.interchange,
Action::Acknowledged,
&ContrlOptions::default(),
)
}
pub fn acknowledgement_with(
subject: &ValidatedInterchange,
options: &ContrlOptions,
) -> Result<Self, EdifactError> {
Self::base(&subject.interchange, Action::Acknowledged, options).checked(options)
}
#[must_use]
pub fn from_report(
subject: &ValidatedInterchange,
segments: &[Segment<'_>],
report: &ValidationReport,
) -> Self {
Self::reporting(subject, segments, report, &ContrlOptions::default())
}
pub fn from_report_with(
subject: &ValidatedInterchange,
segments: &[Segment<'_>],
report: &ValidationReport,
options: &ContrlOptions,
) -> Result<Self, EdifactError> {
Self::reporting(subject, segments, report, options).checked(options)
}
pub fn from_recovered(
recovered: &RecoveredInterchange<'_>,
extra: &[ContrlLocation],
options: &ContrlOptions,
) -> Result<Self, EdifactError> {
let address = recovered
.address()
.ok_or_else(|| EdifactError::MissingSegment {
tag: "UNB".to_owned(),
expected_position: "interchange header with readable sender, recipient and \
control reference"
.to_owned(),
})?;
let mut contrl = Self {
control_ref: address.control_ref().to_owned(),
sender: address.sender_id().to_owned(),
sender_qualifier: address.sender_qualifier().to_owned(),
recipient: address.recipient_id().to_owned(),
recipient_qualifier: address.recipient_qualifier().to_owned(),
identifier: options.resolve_identifier(address.syntax_version()),
action: Action::Acknowledged,
interchange_error: None,
message_ref: None,
messages: Vec::new(),
groups: Vec::new(),
findings: Vec::new(),
};
let findings = recovered
.fault_locations()
.into_iter()
.chain(extra.iter().cloned())
.map(|location| Finding {
location,
rejects: true,
states_code: true,
})
.collect();
contrl.assemble(
findings,
&Shape::of_recovered(recovered),
!recovered.is_complete(),
options,
);
contrl.checked(options)
}
fn reporting(
subject: &ValidatedInterchange,
segments: &[Segment<'_>],
report: &ValidationReport,
options: &ContrlOptions,
) -> Self {
let mut contrl = Self::base(&subject.interchange, Action::Acknowledged, options);
let messages = message_boundaries(segments);
let groups = group_boundaries(segments);
let findings = report
.errors()
.iter()
.map(|i| (i, true))
.chain(report.warnings().iter().map(|i| (i, false)))
.map(|(issue, rejects)| {
let error = SyntaxError::for_issue(issue);
let location = locate_issue(segments, &messages, &groups, issue, error);
let stand_in = location.level() == ReportingLevel::Interchange
&& location.error() == SyntaxError::Unspecified
&& error != SyntaxError::Unspecified;
Finding {
location,
rejects,
states_code: !stand_in,
}
})
.collect();
contrl.assemble(findings, &Shape::of_validated(subject), false, options);
contrl
}
fn assemble(
&mut self,
findings: Vec<Finding>,
shape: &Shape,
forced: bool,
options: &ContrlOptions,
) {
let mut unattributed = forced;
let mut interchange_rejected = false;
let mut lower = Vec::new();
for finding in findings {
if !finding.rejects && !options.report_warnings {
continue;
}
match finding.level() {
ReportingLevel::Interchange => {
interchange_rejected |= finding.rejects;
if self.interchange_error.is_none() && finding.states_code {
self.interchange_error = Some(LevelError::of(&finding.location));
}
}
ReportingLevel::Group => {
if finding
.location
.group()
.is_some_and(|g| shape.names_group(g))
{
lower.push(finding);
} else {
unattributed |= finding.rejects;
}
}
_ => {
if finding
.message_index()
.is_some_and(|m| shape.names_message(m))
{
lower.push(finding);
} else {
unattributed |= finding.rejects;
}
}
}
}
if interchange_rejected {
self.action = Action::Rejected;
return;
}
self.findings = lower;
let whole = options.rejection == RejectionScope::Interchange || unattributed;
let message_reports: Vec<Option<MessageReport>> = (0..shape.messages.len())
.map(|index| self.message_verdict(index, shape))
.collect();
let group_faults: Vec<Option<(bool, LevelError)>> = (0..shape.groups.len())
.map(|index| self.group_verdict(index))
.collect();
let any_rejected = unattributed
|| message_reports
.iter()
.flatten()
.any(|m| m.action == Action::Rejected)
|| group_faults.iter().flatten().any(|(rejected, _)| *rejected);
let uci_rejected = whole && any_rejected;
if uci_rejected {
self.action = Action::Rejected;
self.interchange_error = None;
}
let keep = |report: &MessageReport| !uci_rejected || report.action == Action::Rejected;
if shape.groups.is_empty() {
self.messages = message_reports.into_iter().flatten().filter(keep).collect();
return;
}
let mut message_reports = message_reports;
let mut reports = Vec::new();
for (index, name) in shape.groups.iter().enumerate() {
let Some(name) = name else { continue };
let fault = group_faults[index];
let own_rejected = fault.is_some_and(|(rejected, _)| rejected);
let messages: Vec<MessageReport> = if own_rejected {
Vec::new()
} else {
shape
.messages
.iter()
.enumerate()
.filter(|(_, (_, group))| *group == Some(index))
.filter_map(|(m, _)| message_reports[m].take())
.filter(keep)
.collect()
};
let child_rejected = messages.iter().any(|m| m.action == Action::Rejected);
let rejected = own_rejected || (whole && child_rejected);
if fault.is_none() && messages.is_empty() {
continue; }
if uci_rejected && !rejected {
continue;
}
reports.push(GroupReport {
name: name.clone(),
action: if rejected {
Action::Rejected
} else {
Action::Acknowledged
},
error: fault
.filter(|(own, _)| *own || !rejected)
.map(|(_, error)| error),
messages,
});
}
self.groups = reports;
}
fn message_verdict(&self, index: usize, shape: &Shape) -> Option<MessageReport> {
let mut found = false;
let mut rejected = false;
let mut error = None;
for finding in self
.findings
.iter()
.filter(|f| f.message_index() == Some(index))
{
found = true;
rejected |= finding.rejects;
if error.is_none() && finding.level() == ReportingLevel::Message {
error = Some(LevelError::of(&finding.location));
}
}
if !found {
return None;
}
Some(MessageReport {
index,
name: shape.messages[index].0.clone()?,
action: if rejected {
Action::Rejected
} else {
Action::Acknowledged
},
error,
})
}
fn group_verdict(&self, index: usize) -> Option<(bool, LevelError)> {
let mut faults = self
.findings
.iter()
.filter(|f| f.level() == ReportingLevel::Group && f.location.group() == Some(index));
let first = faults.next()?;
let rejected = first.rejects || faults.any(|f| f.rejects);
Some((rejected, LevelError::of(&first.location)))
}
fn checked(self, options: &ContrlOptions) -> Result<Self, EdifactError> {
let policy = options.actions;
let check = |level: ReportingLevel, action: Action| {
if policy.permits(level, action) {
Ok(())
} else {
Err(EdifactError::ActionNotPermitted {
segment_tag: level.tag(),
action: action.code(),
})
}
};
check(ReportingLevel::Interchange, self.action)?;
for message in &self.messages {
check(ReportingLevel::Message, message.action)?;
}
for group in &self.groups {
check(ReportingLevel::Group, group.action)?;
for message in &group.messages {
check(ReportingLevel::Message, message.action)?;
}
}
Ok(self)
}
#[must_use]
pub fn with_message_reference(mut self, reference: impl Into<String>) -> Self {
self.message_ref = Some(reference.into());
self
}
#[must_use]
pub fn with_identifier(mut self, id: ContrlIdentifier) -> Self {
self.identifier = id;
self
}
#[must_use]
pub fn identifier(&self) -> &ContrlIdentifier {
&self.identifier
}
#[must_use]
pub fn with_interchange_error(mut self, error: SyntaxError) -> Self {
if error.permitted_at(ReportingLevel::Interchange) {
self.interchange_error = Some(LevelError::code(error));
}
self
}
#[must_use]
pub const fn action(&self) -> Action {
self.action
}
#[must_use]
pub fn message_reference(&self) -> &str {
self.message_ref.as_deref().unwrap_or(&self.control_ref)
}
#[must_use]
pub fn segments(&self) -> Vec<OwnedSegment> {
let mut out = Vec::new();
let reference = self.message_reference().to_owned();
out.push(OwnedSegment::new(
"UNH",
vec![
OwnedElement::of(std::slice::from_ref(&reference)),
OwnedElement::of(&self.identifier.components()),
],
));
let mut uci = vec![
OwnedElement::of(std::slice::from_ref(&self.control_ref)),
party(&self.sender, &self.sender_qualifier),
party(&self.recipient, &self.recipient_qualifier),
OwnedElement::of(&[self.action.code()]),
];
if let Some(error) = &self.interchange_error {
error.push_onto(&mut uci);
}
out.push(OwnedSegment::new("UCI", uci));
for message in &self.messages {
out.extend(self.message_report(message));
}
for group in &self.groups {
let mut ucf = vec![
OwnedElement::of(std::slice::from_ref(&group.name.reference)),
party(&group.name.sender, &group.name.sender_qualifier),
party(&group.name.recipient, &group.name.recipient_qualifier),
OwnedElement::of(&[group.action.code()]),
];
if let Some(error) = &group.error {
error.push_onto(&mut ucf);
}
out.push(OwnedSegment::new("UCF", ucf));
for message in &group.messages {
out.extend(self.message_report(message));
}
}
let count = (out.len() + 1).to_string();
out.push(OwnedSegment::new(
"UNT",
vec![OwnedElement::of(&[count]), OwnedElement::of(&[reference])],
));
out
}
fn message_report(&self, report: &MessageReport) -> Vec<OwnedSegment> {
let name = &report.name;
let mut s009 = vec![
name.message_type.clone(),
name.version.clone(),
name.release.clone(),
name.agency.clone(),
];
if !name.association.is_empty() {
s009.push(name.association.clone());
}
let mut ucm = vec![
OwnedElement::of(std::slice::from_ref(&name.reference)),
OwnedElement::of(&s009),
OwnedElement::of(&[report.action.code()]),
];
if let Some(error) = &report.error {
error.push_onto(&mut ucm);
}
let mut out = vec![OwnedSegment::new("UCM", ucm)];
out.extend(self.segment_reports(report.index));
out
}
fn segment_reports(&self, message_index: usize) -> Vec<OwnedSegment> {
let mut out = Vec::new();
let mut reported_positions: Vec<u32> = Vec::new();
for finding in self
.findings
.iter()
.filter(|f| f.message_index() == Some(message_index))
{
let level = finding.level();
let Some(position) = finding.location.segment_position() else {
continue;
};
if !reported_positions.contains(&position) {
reported_positions.push(position);
let position_text = position.to_string();
let mut ucs = vec![OwnedElement::of(&[position_text])];
if level == ReportingLevel::Segment {
ucs.push(OwnedElement::of(&[finding.location.error().code()]));
}
out.push(OwnedSegment::new("UCS", ucs));
}
if level == ReportingLevel::DataElement {
let element_text = finding
.location
.element_position()
.expect("DataElement level implies a known element position")
.to_string();
let mut identification = vec![element_text];
if let Some(component) = finding.location.component_position() {
identification.push(component.to_string());
}
out.push(OwnedSegment::new(
"UCD",
vec![
OwnedElement::of(&[finding.location.error().code()]),
OwnedElement::of(&identification),
],
));
}
}
out
}
pub fn to_bytes(&self) -> Result<Vec<u8>, EdifactError> {
crate::segments_to_bytes(&self.segments())
}
pub fn to_edifact_string(&self) -> Result<String, EdifactError> {
String::from_utf8(self.to_bytes()?).map_err(|_| EdifactError::InvalidUtf8)
}
pub fn to_interchange_bytes(
&self,
syntax_identifier: &str,
syntax_version: &str,
date: &str,
time: &str,
control_reference: &str,
) -> Result<Vec<u8>, EdifactError> {
let header = self.reply_header(
syntax_identifier,
syntax_version,
date,
time,
control_reference,
)?;
let mut writer = Writer::new(Vec::new());
writer.begin_interchange(&header)?;
for segment in self.segments() {
writer.write_segment(&segment)?;
}
writer.end_interchange()?;
writer.finish()
}
fn reply_header(
&self,
syntax_identifier: &str,
syntax_version: &str,
date: &str,
time: &str,
control_reference: &str,
) -> Result<crate::InterchangeHeader, EdifactError> {
let unb = Segment::new(
"UNB",
vec![
Element::of(&[syntax_identifier, syntax_version]),
Element::of(&party_components(
&self.recipient,
&self.recipient_qualifier,
)),
Element::of(&party_components(&self.sender, &self.sender_qualifier)),
Element::of(&[date, time]),
Element::of(&[control_reference]),
],
);
crate::InterchangeHeader::parse(&unb)
}
pub fn to_interchange_string(
&self,
syntax_identifier: &str,
syntax_version: &str,
date: &str,
time: &str,
control_reference: &str,
) -> Result<String, EdifactError> {
let bytes = self.to_interchange_bytes(
syntax_identifier,
syntax_version,
date,
time,
control_reference,
)?;
let charset = crate::Charset::from_syntax_identifier(syntax_identifier)?;
Ok(charset.decode(&bytes)?.into_owned())
}
}
fn party_components<'a>(id: &'a str, qualifier: &'a str) -> Vec<&'a str> {
if qualifier.is_empty() {
vec![id]
} else {
vec![id, qualifier]
}
}
fn party(id: &str, qualifier: &str) -> OwnedElement {
if qualifier.is_empty() {
OwnedElement::of(&[id.to_owned()])
} else {
OwnedElement::of(&[id.to_owned(), qualifier.to_owned()])
}
}
fn message_boundaries(segments: &[Segment<'_>]) -> Vec<(usize, usize)> {
spans_between(segments, "UNH", "UNT")
}
fn group_boundaries(segments: &[Segment<'_>]) -> Vec<(usize, usize)> {
spans_between(segments, "UNG", "UNE")
}
fn spans_between(segments: &[Segment<'_>], open: &str, close: &str) -> Vec<(usize, usize)> {
let mut out = Vec::new();
let mut start: Option<usize> = None;
for (index, segment) in segments.iter().enumerate() {
if segment.tag == open {
start = Some(index);
} else if segment.tag == close
&& let Some(from) = start.take()
{
out.push((from, index));
}
}
out
}
fn locate_issue(
segments: &[Segment<'_>],
messages: &[(usize, usize)],
groups: &[(usize, usize)],
issue: &ValidationIssue,
error: SyntaxError,
) -> ContrlLocation {
let stable = issue.error_code();
let detail = match issue.span {
Some(span) => Detail {
anchor: Anchor::Span(span),
element_index: issue.element_index.map(usize::from),
component_index: issue.component_index.map(usize::from),
},
None => anchor_for_code(stable),
};
let target = match detail.anchor {
Anchor::Span(span) => segment_target(segments, messages, groups, span.start),
Anchor::Service(tag) => Some(Target {
tag: Some(tag),
..Target::interchange(true)
}),
_ => Some(Target::interchange(true)),
};
let target = target
.unwrap_or(Target::interchange(true))
.with_indices(detail.element_index, detail.component_index);
place(target, error, stable)
}
fn segment_target<'s>(
segments: &'s [Segment<'_>],
messages: &[(usize, usize)],
groups: &[(usize, usize)],
offset: usize,
) -> Option<Target<'s>> {
let index = match segments.binary_search_by(|segment| segment.span.start.cmp(&offset)) {
Ok(exact) => exact,
Err(0) => return None,
Err(next) => next - 1,
};
let message = messages
.iter()
.enumerate()
.find(|(_, (start, end))| (*start..=*end).contains(&index))
.map(|(message_index, (start, _))| (message_index, u32::try_from(index - start + 1).ok()));
let group = groups
.iter()
.position(|(start, end)| (*start..=*end).contains(&index));
Some(Target {
tag: Some(segments[index].tag()),
message,
group,
..Target::interchange(true)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(input: &[u8]) -> Vec<OwnedSegment> {
crate::from_bytes(input)
.map(|r| r.map(|s| s.into_owned()))
.collect::<Result<Vec<_>, _>>()
.expect("parse")
}
#[test]
fn annex_a_permits_a_code_only_where_the_table_says() {
assert!(SyntaxError::NotActualRecipient.permitted_at(ReportingLevel::Interchange));
assert!(!SyntaxError::NotActualRecipient.permitted_at(ReportingLevel::Group));
assert!(SyntaxError::TooManyGroupRepetitions.permitted_at(ReportingLevel::Segment));
assert!(!SyntaxError::TooManyGroupRepetitions.permitted_at(ReportingLevel::DataElement));
assert!(SyntaxError::LowerLevelEmpty.permitted_at(ReportingLevel::Group));
assert!(!SyntaxError::LowerLevelEmpty.permitted_at(ReportingLevel::Message));
assert!(SyntaxError::EnvelopeFunctionalityNotSupported.permitted_at(ReportingLevel::Group));
assert!(
!SyntaxError::EnvelopeFunctionalityNotSupported
.permitted_at(ReportingLevel::Interchange)
);
for level in [
ReportingLevel::Interchange,
ReportingLevel::Group,
ReportingLevel::Message,
ReportingLevel::Segment,
ReportingLevel::DataElement,
] {
assert!(SyntaxError::InvalidValue.permitted_at(level), "{level:?}");
}
}
#[test]
fn every_code_is_permitted_somewhere() {
for error in ALL_ERRORS {
assert!(
[
ReportingLevel::Interchange,
ReportingLevel::Group,
ReportingLevel::Message,
ReportingLevel::Segment,
ReportingLevel::DataElement,
]
.iter()
.any(|level| error.permitted_at(*level)),
"{error:?} is permitted nowhere"
);
}
}
#[test]
fn codes_are_unique() {
let mut codes: Vec<&str> = ALL_ERRORS.iter().map(|e| e.code()).collect();
codes.sort_unstable();
let before = codes.len();
codes.dedup();
assert_eq!(before, codes.len(), "duplicate DE 0085 code");
}
const ALL_ERRORS: &[SyntaxError] = &[
SyntaxError::SyntaxVersionNotSupported,
SyntaxError::NotActualRecipient,
SyntaxError::InvalidValue,
SyntaxError::Missing,
SyntaxError::ValueNotSupportedHere,
SyntaxError::NotSupportedHere,
SyntaxError::TooManyConstituents,
SyntaxError::NoAgreement,
SyntaxError::Unspecified,
SyntaxError::InvalidAsServiceCharacter,
SyntaxError::InvalidCharacters,
SyntaxError::InvalidServiceCharacters,
SyntaxError::UnknownSender,
SyntaxError::TooOld,
SyntaxError::TestIndicatorNotSupported,
SyntaxError::DuplicateDetected,
SyntaxError::ReferencesDoNotMatch,
SyntaxError::ControlCountMismatch,
SyntaxError::GroupsAndMessagesMixed,
SyntaxError::LowerLevelEmpty,
SyntaxError::InvalidOccurrenceOutsideMessage,
SyntaxError::TooManyRepetitions,
SyntaxError::TooManyGroupRepetitions,
SyntaxError::InvalidCharacterType,
SyntaxError::DataElementTooLong,
SyntaxError::DataElementTooShort,
SyntaxError::TrailingSeparator,
SyntaxError::CharacterSetNotSupported,
SyntaxError::EnvelopeFunctionalityNotSupported,
];
#[test]
fn an_acknowledgement_validates_against_the_shipped_layouts() {
let raw = b"UNB+UNOC:3+SENDER:14+RECEIVER:14+260101:0900+IC4711'\
UNH+MSG1+ORDERS:D:96A:UN'BGM+220+PO-1+9'UNT+3+MSG1'\
UNZ+1+IC4711'";
let owned = parse(raw);
let validated = crate::validate_envelope(&owned).expect("valid subject");
let contrl = Contrl::acknowledgement(&validated).with_message_reference("ACK1");
let wire = contrl.to_edifact_string().expect("render");
assert_eq!(
wire,
"UNH+ACK1+CONTRL:D:3:UN'UCI+IC4711+SENDER:14+RECEIVER:14+7'UNT+3+ACK1'"
);
let reparsed = parse(wire.as_bytes());
let validator = crate::DirectoryValidator::new(
"iso-9735-4",
crate::service::lookup,
|_, _| true,
|_, _| None,
|_, _| None,
None,
);
let report = crate::ValidationContext::builder()
.with_validator(crate::ValidationLayer::Structure, validator)
.build()
.validate(&reparsed);
assert!(!report.has_errors(), "{:#?}", report.errors());
}
#[test]
fn a_receipt_carries_action_8_and_nothing_else() {
let raw =
b"UNB+UNOC:3+S+R+260101:0900+IC1'UNH+M1+ORDERS:D:96A:UN'BGM+220'UNT+3+M1'UNZ+1+IC1'";
let owned = parse(raw);
let validated = crate::validate_envelope(&owned).expect("valid subject");
let wire = Contrl::receipt(&validated.interchange)
.to_edifact_string()
.expect("render");
assert!(wire.contains("UCI+IC1+S+R+8'"), "{wire}");
assert_eq!(
Contrl::receipt(&validated.interchange).action(),
Action::Received
);
}
#[test]
fn the_message_reference_defaults_to_the_subject_control_reference() {
let raw = b"UNB+UNOC:3+S+R+260101:0900+IC-42'UNH+M1+ORDERS:D:96A:UN'BGM+220'UNT+3+M1'UNZ+1+IC-42'";
let owned = parse(raw);
let validated = crate::validate_envelope(&owned).expect("valid subject");
assert_eq!(
Contrl::acknowledgement(&validated).message_reference(),
"IC-42"
);
}
#[test]
fn a_forbidden_interchange_level_code_is_not_recorded() {
let raw =
b"UNB+UNOC:3+S+R+260101:0900+IC1'UNH+M1+ORDERS:D:96A:UN'BGM+220'UNT+3+M1'UNZ+1+IC1'";
let owned = parse(raw);
let validated = crate::validate_envelope(&owned).expect("valid subject");
let wire = Contrl::acknowledgement(&validated)
.with_interchange_error(SyntaxError::TooManyGroupRepetitions)
.to_edifact_string()
.expect("render");
assert!(wire.contains("UCI+IC1+S+R+7'"), "{wire}");
}
fn report_for(raw: &[u8]) -> Contrl {
let owned = parse(raw);
let validated = crate::validate_envelope_lenient(&owned)
.interchange
.expect("subject must be structurally interpretable");
let report = crate::ValidationContext::builder()
.with_envelope_validation()
.with_syntax_validation()
.build()
.validate(&owned);
Contrl::from_report(&validated, &owned, &report)
}
#[test]
fn a_data_element_fault_is_reported_at_the_ucd_level() {
let raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'\
UNH+M1+ORDERS:D:96A:UN'FTX+ 'UNT+3+M1'\
UNZ+1+IC1'";
let contrl = report_for(raw);
assert_eq!(contrl.action(), Action::Acknowledged);
let wire = contrl.to_edifact_string().expect("render");
assert!(wire.contains("UCM+M1+ORDERS:D:96A:UN+7'"), "{wire}");
assert!(wire.contains("UCS+2'"), "{wire}");
assert!(wire.contains("UCD+12+2:1'"), "{wire}");
}
#[test]
fn a_rejected_message_is_named_by_its_ucm() {
let raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'\
UNH+M1+ORDERS:D:96A:UN'BGM+220'UNT+3+M1'\
UNH+M1+ORDERS:D:96A:UN'BGM+221'UNT+3+M1'\
UNZ+2+IC1'";
let contrl = report_for(raw);
assert_eq!(contrl.action(), Action::Acknowledged);
let wire = contrl.to_edifact_string().expect("render");
assert_eq!(
wire,
"UNH+IC1+CONTRL:D:3:UN'\
UCI+IC1+S+R+7'\
UCM+M1+ORDERS:D:96A:UN+4+26+UNH'\
UNT+4+IC1'"
);
}
#[test]
fn an_envelope_fault_rejects_the_interchange_and_emits_no_ucm() {
let raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'\
UNH+M1+ORDERS:D:96A:UN'BGM+220'UNT+3+M1'\
UNZ+1+IC-OTHER'";
let contrl = report_for(raw);
assert_eq!(contrl.action(), Action::Rejected);
let wire = contrl.to_edifact_string().expect("render");
assert_eq!(
wire,
"UNH+IC1+CONTRL:D:3:UN'UCI+IC1+S+R+4+28+UNZ'UNT+3+IC1'"
);
}
#[test]
fn a_count_mismatch_is_reported_on_the_message_that_got_it_wrong() {
let raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'\
UNH+M1+ORDERS:D:96A:UN'BGM+220'UNT+9+M1'\
UNZ+1+IC1'";
let contrl = report_for(raw);
assert_eq!(contrl.action(), Action::Acknowledged);
let wire = contrl.to_edifact_string().expect("render");
assert_eq!(
wire,
"UNH+IC1+CONTRL:D:3:UN'\
UCI+IC1+S+R+7'\
UCM+M1+ORDERS:D:96A:UN+4+29+UNT'\
UNT+4+IC1'"
);
}
#[test]
fn a_finding_lands_at_the_lowest_level_annex_a_permits() {
let in_body = Target {
tag: Some("BGM"),
message: Some((0, Some(2))),
element_position: Some(2),
..Target::interchange(true)
};
let duplicate = place(in_body, SyntaxError::DuplicateDetected, None);
assert_eq!(duplicate.level(), ReportingLevel::Message);
let invalid = place(in_body, SyntaxError::InvalidValue, None);
assert_eq!(invalid.level(), ReportingLevel::DataElement);
let segment_only = Target {
element_position: None,
..in_body
};
let segment_only = place(segment_only, SyntaxError::InvalidValue, None);
assert_eq!(segment_only.level(), ReportingLevel::Segment);
let group_repetitions = place(in_body, SyntaxError::TooManyGroupRepetitions, None);
assert_eq!(group_repetitions.level(), ReportingLevel::Segment);
}
#[test]
fn an_empty_message_is_reported_as_missing_never_as_lower_level_empty() {
let raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'\
UNH+M1+ORDERS:D:96A:UN'UNT+2+M1'\
UNZ+1+IC1'";
let contrl = report_for(raw);
let wire = contrl.to_edifact_string().expect("render");
assert!(wire.contains("UCM+M1+ORDERS:D:96A:UN+4+13+UNH'"), "{wire}");
assert!(!wire.contains("+32'"), "{wire}");
}
#[test]
fn a_generated_contrl_reparses_and_counts_its_own_segments() {
let raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'\
UNH+M1+ORDERS:D:96A:UN'FTX+ 'UNT+3+M1'\
UNZ+1+IC1'";
let contrl = report_for(raw);
let wire = contrl
.to_interchange_string("UNOC", "3", "260101", "0930", "ACK-1")
.expect("render");
let segments: Vec<_> = crate::from_bytes(wire.as_bytes())
.collect::<Result<Vec<_>, _>>()
.expect("generated CONTRL must reparse");
let validated =
crate::validate_envelope(&segments).expect("generated CONTRL must validate");
assert_eq!(validated.messages.len(), 1);
assert_eq!(validated.messages[0].message_type, "CONTRL");
assert_eq!(validated.messages[0].version, "D");
assert_eq!(validated.messages[0].release, "3");
assert_eq!(
validated.messages[0].declared_segment_count,
validated.messages[0].actual_segment_count
);
}
#[test]
fn a_grouped_interchange_is_reported_through_ucf() {
let raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'\
UNG+ORDERS+SND:14+RCV:14+260101:0900+GRP1+UN+D:96A'\
UNH+M1+ORDERS:D:96A:UN'FTX+ 'UNT+3+M1'\
UNE+1+GRP1'\
UNZ+1+IC1'";
let contrl = report_for(raw);
assert_eq!(contrl.action(), Action::Acknowledged);
let wire = contrl.to_edifact_string().expect("render");
assert_eq!(
wire,
"UNH+IC1+CONTRL:D:3:UN'\
UCI+IC1+S+R+7'\
UCF+GRP1+SND:14+RCV:14+7'\
UCM+M1+ORDERS:D:96A:UN+7'\
UCS+2'\
UCD+12+2:1'\
UNT+7+IC1'"
);
}
#[test]
fn a_group_envelope_fault_rejects_only_that_group() {
let raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'\
UNG+ORDERS+SND+RCV+260101:0900+GRP1+UN+D:96A'\
UNH+M1+ORDERS:D:96A:UN'BGM+220'UNT+3+M1'\
UNE+1+GRP-OTHER'\
UNZ+1+IC1'";
let contrl = report_for(raw);
assert_eq!(contrl.action(), Action::Acknowledged);
let wire = contrl.to_edifact_string().expect("render");
assert_eq!(
wire,
"UNH+IC1+CONTRL:D:3:UN'\
UCI+IC1+S+R+7'\
UCF+GRP1+SND+RCV+4+28+UNE'\
UNT+4+IC1'"
);
}
#[test]
fn a_clean_grouped_interchange_needs_no_ucf() {
let raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'\
UNG+ORDERS+SND+RCV+260101:0900+GRP1+UN+D:96A'\
UNH+M1+ORDERS:D:96A:UN'BGM+220'UNT+3+M1'\
UNE+1+GRP1'\
UNZ+1+IC1'";
let contrl = report_for(raw);
assert_eq!(
contrl.to_edifact_string().expect("render"),
"UNH+IC1+CONTRL:D:3:UN'UCI+IC1+S+R+7'UNT+3+IC1'"
);
}
#[test]
fn group_placement_errors_map_to_their_annex_a_codes() {
use EdifactError as E;
let span = crate::Span::new(0, 3);
let cases = [
(
E::SegmentNotPlaced {
tag: "RFF".to_owned(),
reason: crate::group::UnplacedReason::NotHere,
span,
},
SyntaxError::NotSupportedHere,
"15",
),
(
E::TooManySegmentOccurrences {
tag: "DTM".to_owned(),
max: 1,
span,
},
SyntaxError::TooManyRepetitions,
"35",
),
(
E::TooManyGroupOccurrences {
group: "SG8".to_owned(),
max: 2,
span,
},
SyntaxError::TooManyGroupRepetitions,
"36",
),
];
for (error, expected, code) in cases {
assert_eq!(SyntaxError::for_error(&error), expected, "{error}");
assert_eq!(expected.code(), code);
let issue = ValidationIssue::new(crate::ValidationSeverity::Error, error.to_string())
.with_error_code(error.stable_code());
assert_eq!(SyntaxError::for_issue(&issue), expected, "{error}");
}
}
#[test]
fn error_mapping_picks_the_narrowest_annex_a_code() {
use EdifactError as E;
let cases: [(EdifactError, SyntaxError); 6] = [
(
E::MessageCountMismatch {
expected: 1,
actual: 2,
span: crate::Span::new(0, 9),
},
SyntaxError::ControlCountMismatch,
),
(
E::DuplicateReference {
tag: "UNH".to_owned(),
reference: "1".to_owned(),
span: crate::Span::new(0, 1),
},
SyntaxError::DuplicateDetected,
),
(
E::UnsupportedCharset {
syntax_identifier: "UNOX".to_owned(),
},
SyntaxError::CharacterSetNotSupported,
),
(E::InvalidUna, SyntaxError::InvalidServiceCharacters),
(
E::EmptyInterchange {
control_ref: "IC1".to_owned(),
},
SyntaxError::LowerLevelEmpty,
),
(
E::PackageNotSupported {
tag: "UNO".to_owned(),
span: crate::Span::new(0, 1),
},
SyntaxError::EnvelopeFunctionalityNotSupported,
),
];
for (error, expected) in cases {
assert_eq!(SyntaxError::for_error(&error), expected, "{error:?}");
}
}
}