use edifact_rs::OwnedSegment;
use crate::{
DvgwMessageType,
message::{MessageCore, find_all_segments, find_segment, impl_dvgw_message},
};
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct AlocatQuantity {
pub location_code: String,
pub location_qualifier: String,
pub quantity: String,
pub quantity_qualifier: String,
pub unit: Option<String>,
pub status: Option<String>,
pub period_start: Option<String>,
pub period_end: Option<String>,
}
impl AlocatQuantity {
#[must_use]
pub fn quantity_f64(&self) -> Option<f64> {
if self.quantity.is_empty() {
None
} else {
self.quantity.parse().ok()
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AlocatMessage {
pub(crate) core: MessageCore,
pub reference_date: Option<String>,
pub clearing_number: Option<String>,
pub quantities: Vec<AlocatQuantity>,
}
impl_dvgw_message!(AlocatMessage);
impl AlocatMessage {
pub(crate) fn from_segments(segments: Vec<OwnedSegment>) -> Self {
let core = MessageCore::from_segments(segments, DvgwMessageType::Alocat);
let reference_date = extract_dtm(&core.segments, "137");
let clearing_number = find_segment(&core.segments, "RFF")
.and_then(|s| s.component_str(0, 1))
.map(str::to_owned);
let quantities = extract_quantities(&core.segments);
Self {
core,
reference_date,
clearing_number,
quantities,
}
}
}
fn extract_dtm(segs: &[OwnedSegment], qualifier: &str) -> Option<String> {
find_all_segments(segs, "DTM")
.find(|s| s.component_str(0, 0) == Some(qualifier))
.and_then(|s| s.component_str(0, 1))
.map(str::to_owned)
}
fn extract_quantities(segs: &[OwnedSegment]) -> Vec<AlocatQuantity> {
let mut result = Vec::new();
let mut i = 0;
while i < segs.len() {
let seg = &segs[i];
if seg.tag == "LOC" {
let location_qualifier = seg.element_str(0).unwrap_or("").to_owned();
let location_code = seg.component_str(1, 0).unwrap_or("").to_owned();
let mut quantity = String::new();
let mut quantity_qualifier = String::new();
let mut unit = None;
let mut status = None;
let mut period_start = None;
let mut period_end = None;
let mut j = i + 1;
while j < segs.len() && segs[j].tag != "LOC" {
match segs[j].tag.as_str() {
"QTY" => {
segs[j]
.component_str(0, 0)
.unwrap_or("")
.clone_into(&mut quantity_qualifier);
segs[j]
.component_str(0, 1)
.unwrap_or("")
.clone_into(&mut quantity);
unit = segs[j].component_str(0, 2).map(str::to_owned);
}
"STS" => {
status = segs[j].component_str(0, 0).map(str::to_owned);
}
"DTM" => {
let q = segs[j].component_str(0, 0).unwrap_or("");
let v = segs[j].component_str(0, 1).map(str::to_owned);
match q {
"163" => period_start = v,
"164" => period_end = v,
_ => {}
}
}
_ => {}
}
j += 1;
}
if !location_code.is_empty() && !quantity.is_empty() {
result.push(AlocatQuantity {
location_code,
location_qualifier,
quantity,
quantity_qualifier,
unit,
status,
period_start,
period_end,
});
}
i = j;
} else {
i += 1;
}
}
result
}