1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use crate::edi_parse_error::EdiParseError;

use crate::transaction::Transaction;

use crate::tokenizer::SegmentTokens;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::VecDeque;

/// Represents a GS/GE segment which wraps a functional group.
/// Documentation here gleaned mostly from [here](http://u.sezna.dev/b)
#[derive(PartialEq, Debug, Serialize, Deserialize)]
pub struct FunctionalGroup<'a, 'b> {
    /// Identifies the function of this group.
    /// See http://ecomgx17.ecomtoday.com/edi/EDI_4010/el479.htm for a list of
    /// functional identifier codes.
    #[serde(borrow)]
    pub functional_identifier_code: Cow<'a, str>,
    /// Identifies the sender of this group.
    #[serde(borrow)]
    pub application_sender_code: Cow<'a, str>,
    /// Identifies the receiver of this group.
    #[serde(borrow)]
    pub application_receiver_code: Cow<'a, str>,
    /// Identifies the date of the function performed.
    #[serde(borrow)]
    pub date: Cow<'a, str>,
    /// Identifies the time of the function performed.
    ///  Expressed in 24-hour clock time as follows: HHMM, or HHMMSS, or
    /// HHMMSSD, or HHMMSSDD, where H = hours (00-23), M = minutes (00-59), S = integer
    /// seconds (00-59) and DD = decimal seconds; decimal seconds are expressed as follows: D
    /// = tenths (0-9) and DD = hundredths (00-99)
    #[serde(borrow)]
    pub time: Cow<'a, str>,
    /// An ID code for this specific control group. Should
    /// be the same in the GE (group end) segment.
    #[serde(borrow)]
    pub group_control_number: Cow<'a, str>,
    /// Code identifying the issuer of the standard
    #[serde(borrow)]
    pub responsible_agency_code: Cow<'a, str>,
    ///  Code indicating the version, release, subrelease, and industry identifier of the
    ///  EDI standard being used, including the GS and GE segments; If code DE455 in GS
    /// segment is X, then in DE 480 positions 1-3 are the version number; positions 4-6 are the
    /// release and subrelease, level of the version; and positions 7-12 are the industry or trade
    /// association identifiers (optionally assigned by user); if code in DE455 in GS segment is T,
    /// then other formats are allowed
    #[serde(borrow)]
    pub version: Cow<'a, str>,
    /// The transactions that this functional group contains.
    #[serde(borrow = "'a + 'b")]
    pub transactions: VecDeque<Transaction<'a, 'b>>,
}

impl<'a, 'b> FunctionalGroup<'a, 'b> {
    /// Given [SegmentTokens] (where the first token is "GS"), construct a [FunctionalGroup].
    #[doc(skip)]
    pub fn parse_from_tokens(
        input: SegmentTokens<'a>,
    ) -> Result<FunctionalGroup<'a, 'b>, EdiParseError> {
        let elements: Vec<&str> = input.iter().map(|x| x.trim()).collect();
        // I always inject invariants wherever I can to ensure debugging is quick and painless,
        // and to check my assumptions.
        edi_assert!(
            elements[0] == "GS",
            "attempted to parse GS from non-GS segment",
            input
        );
        edi_assert!(
            elements.len() >= 9,
            "GS segment does not contain enough elements. At least 9 required",
            input
        );
        let (
            functional_identifier_code,
            application_sender_code,
            application_receiver_code,
            date,
            time,
            group_control_number,
            responsible_agency_code,
            version,
        ) = (
            Cow::from(elements[1]),
            Cow::from(elements[2]),
            Cow::from(elements[3]),
            Cow::from(elements[4]),
            Cow::from(elements[5]),
            Cow::from(elements[6]),
            Cow::from(elements[7]),
            Cow::from(elements[8]),
        );

        Ok(FunctionalGroup {
            functional_identifier_code,
            application_sender_code,
            application_receiver_code,
            date,
            time,
            group_control_number,
            responsible_agency_code,
            version,
            transactions: VecDeque::new(),
        })
    }

    #[doc(skip)]
    /// Enqueue a [Transaction] into the group. Subsequent segments will be enqueued into this transaction.
    pub fn add_transaction(&mut self, tokens: SegmentTokens<'a>) -> Result<(), EdiParseError> {
        self.transactions
            .push_back(Transaction::parse_from_tokens(tokens)?);
        Ok(())
    }

    #[doc(skip)]
    /// Enqueue a [GenericSegment] into the most recently enqueued [Transaction].
    pub fn add_generic_segment(&mut self, tokens: SegmentTokens<'a>) -> Result<(), EdiParseError> {
        if let Some(transaction) = self.transactions.back_mut() {
            transaction.add_generic_segment(tokens)
        } else {
            Err(EdiParseError::new(
                "unable to enqueue generic segment when no transactions have been enqueued",
                Some(tokens),
            ))
        }
    }

    #[doc(skip)]
    /// Verify this [FunctionalGroup] with a GE segment.
    pub fn validate_functional_group(
        &self,
        tokens: SegmentTokens<'a>,
    ) -> Result<(), EdiParseError> {
        edi_assert!(
            tokens[0] == "GE",
            "attempted to call GE verification on non-GE segment",
            tokens
        );
        edi_assert!(
            self.transactions.len() == str::parse::<usize>(tokens[1]).unwrap(),
            "functional group validation failed: incorrect number of transactions",
            self.transactions.len(),
            str::parse::<usize>(tokens[1]).unwrap(),
            tokens
        );
        edi_assert!(
            self.group_control_number == tokens[2],
            "functional group validation failed: mismatched ID",
            self.group_control_number,
            tokens[2],
            tokens
        );
        Ok(())
    }

    #[doc(skip)]
    /// Validate the latest [Transaction] within this functional group with an SE segment.
    pub fn validate_transaction(&self, tokens: SegmentTokens<'a>) -> Result<(), EdiParseError> {
        if let Some(transaction) = self.transactions.back() {
            transaction.validate_transaction(tokens)
        } else {
            Err(EdiParseError::new(
                "unable to validate nonexistent transaction",
                Some(tokens),
            ))
        }
    }
}

#[test]
fn construct_functional_group() {
    let expected_result = FunctionalGroup {
        functional_identifier_code: Cow::from("PO"),
        application_sender_code: Cow::from("SENDERGS"),
        application_receiver_code: Cow::from("007326879"),
        date: Cow::from("20020226"),
        time: Cow::from("1534"),
        group_control_number: Cow::from("1"),
        responsible_agency_code: Cow::from("X"),
        version: Cow::from("004010"),
        transactions: VecDeque::new(),
    };

    let test_input = vec![
        "GS",
        "PO",
        "SENDERGS",
        "007326879",
        "20020226",
        "1534",
        "1",
        "X",
        "004010",
    ];

    assert_eq!(
        FunctionalGroup::parse_from_tokens(test_input).unwrap(),
        expected_result
    );
}