1use chrono::NaiveDate;
2use iati_types::{
3 money::{CurrencyCode, Money},
4 tx::{Transaction, TxType},
5 Activity,
6};
7use quick_xml::{
8 events::{attributes::Attributes, Event},
9 name::QName,
10 Reader, Writer,
11};
12
13use rust_decimal::Decimal;
14use std::str::FromStr;
15use thiserror::Error;
16
17#[derive(Debug, Error)]
18pub enum ParseError {
19 #[error("XML error: {0}")]
20 Xml(#[from] quick_xml::Error),
21 #[error("XML attribute error: {0}")]
22 XmlAttr(#[from] quick_xml::events::attributes::AttrError),
23 #[error("encoding error: {0}")]
24 Encoding(#[from] quick_xml::encoding::EncodingError),
25 #[error("io error: {0}")] Io(#[from] std::io::Error), #[error("missing required field: {0}")]
28 Missing(&'static str),
29 #[error("invalid decimal: {0}")]
30 Decimal(#[from] rust_decimal::Error),
31 #[error("invalid integer: {0}")]
32 Int(#[from] std::num::ParseIntError),
33 #[error("invalid date: {0}")]
34 Date(#[from] chrono::ParseError),
35}
36
37
38#[derive(Default)]
40struct TxBuild {
41 tx_type: Option<TxType>,
42 date: Option<NaiveDate>,
43 amount: Option<Decimal>,
44 value_currency: Option<CurrencyCode>,
45 value_date: Option<NaiveDate>,
46}
47
48fn parse_tx_type(mut attrs: Attributes<'_>, tx_build: &mut Option<TxBuild>) -> Result<(), ParseError> {
49 let mut code: Option<u16> = None;
50 for a in attrs.with_checks(false) {
51 let a = a?;
52 if a.key == QName(b"code") {
53 code = Some(a.unescape_value()?.into_owned().parse()?);
54 }
55 }
56 if let Some(b) = tx_build.as_mut() {
57 b.tx_type = Some(TxType::from(
58 code.ok_or(ParseError::Missing("transaction-type/@code"))?,
59 ));
60 }
61 Ok(())
62}
63
64fn parse_tx_date(mut attrs: Attributes<'_>, tx_build: &mut Option<TxBuild>) -> Result<(), ParseError> {
65 let mut iso: Option<String> = None;
66 for a in attrs.with_checks(false) {
67 let a = a?;
68 if a.key == QName(b"iso-date") {
69 iso = Some(a.unescape_value()?.into_owned());
70 }
71 }
72 if let Some(b) = tx_build.as_mut() {
73 let iso = iso.ok_or(ParseError::Missing("transaction-date/@iso-date"))?;
74 b.date = Some(NaiveDate::parse_from_str(&iso, "%Y-%m-%d")?);
75 }
76 Ok(())
77}
78
79pub fn parse_activity(xml: &str) -> Result<Activity, ParseError> {
81 let mut reader = Reader::from_str(xml);
82 reader.config_mut().trim_text(true); let mut buf = Vec::new();
85 let mut current_text: Option<String> = None;
86
87 let mut default_currency: Option<CurrencyCode> = None;
89 let mut iati_identifier: Option<String> = None;
90 let mut transactions: Vec<Transaction> = Vec::new();
91
92 let mut tx_build: Option<TxBuild> = None;
93
94 loop {
95 match reader.read_event_into(&mut buf)? {
96 Event::Start(e) => match e.name().as_ref() {
98 b"iati-activity" => {
99 for a in e.attributes().with_checks(false) {
100 let a = a?;
101 if a.key == QName(b"default-currency") {
102 default_currency = Some(CurrencyCode(a.unescape_value()?.into_owned()));
103 }
104 }
105 }
106 b"iati-identifier" => {
107 current_text = Some(String::new());
108 }
109 b"transaction" => {
110 tx_build = Some(TxBuild::default());
111 }
112 b"transaction-type" => {
113 parse_tx_type(e.attributes(), &mut tx_build)?;
114 }
115 b"transaction-date" => {
116 parse_tx_date(e.attributes(), &mut tx_build)?;
117 }
118 b"value" => {
119 current_text = Some(String::new()); if let Some(b) = tx_build.as_mut() {
121 for a in e.attributes().with_checks(false) {
122 let a = a?;
123 if a.key == QName(b"currency") {
124 b.value_currency =
125 Some(CurrencyCode::from(a.unescape_value()?.into_owned()));
126 }
127 if a.key == QName(b"value-date") {
128 let s = a.unescape_value()?.into_owned();
129 b.value_date = Some(NaiveDate::parse_from_str(&s, "%Y-%m-%d")?);
130 }
131 }
132 }
133 }
134 _ => {}
135 },
136
137 Event::Empty(e) => match e.name().as_ref() {
139 b"transaction-type" => {
140 parse_tx_type(e.attributes(), &mut tx_build)?;
141 }
142 b"transaction-date" => {
143 parse_tx_date(e.attributes(), &mut tx_build)?;
144 }
145 b"value" => {
146 if let Some(b) = tx_build.as_mut() {
148 for a in e.attributes().with_checks(false) {
149 let a = a?;
150 if a.key == QName(b"currency") {
151 b.value_currency =
152 Some(CurrencyCode::from(a.unescape_value()?.into_owned()));
153 }
154 if a.key == QName(b"value-date") {
155 let s = a.unescape_value()?.into_owned();
156 b.value_date = Some(NaiveDate::parse_from_str(&s, "%Y-%m-%d")?);
157 }
158 }
159 }
160 }
161 _ => {}
162 },
163
164 Event::Text(t) => {
166 if let Some(s) = current_text.as_mut() {
167 s.push_str(&t.decode()?); }
169 }
170
171 Event::End(e) => match e.name().as_ref() {
173 b"iati-identifier" => {
174 let val = current_text.take().unwrap_or_default();
175 iati_identifier = Some(val.trim().to_string());
176 }
177 b"value" => {
178 if let Some(b) = tx_build.as_mut() {
179 let val = current_text.take().unwrap_or_default();
180 let dec = Decimal::from_str(val.trim())?;
181 b.amount = Some(dec);
182 }
183 }
184 b"transaction" => {
185 if let Some(b) = tx_build.take() {
186 let tx_type = b.tx_type.ok_or(ParseError::Missing("transaction-type"))?;
187 let date = b.date.ok_or(ParseError::Missing("transaction-date/@iso-date"))?;
188 let mut money = Money::new(b.amount.ok_or(ParseError::Missing("value"))?);
189 money.currency = b.value_currency;
190 money.value_date = b.value_date;
191 let tx = Transaction::new(tx_type, date, money);
192 transactions.push(tx);
193 }
194 }
195 _ => {}
196 },
197
198 Event::Eof => break,
199 _ => {}
200 }
201 buf.clear();
202 }
203
204 let id = iati_identifier.ok_or(ParseError::Missing("iati-identifier"))?;
205 let mut activity = Activity::new(id);
206 activity.default_currency = default_currency;
207 activity.transactions = transactions;
208 Ok(activity)
209}
210
211pub fn parse_activities(xml: &str) -> Result<Vec<Activity>, ParseError> {
213 let mut reader = Reader::from_str(xml);
214 reader.config_mut().trim_text(true);
215
216 let mut buf = Vec::new();
217 let mut activities: Vec<Activity> = Vec::new();
218
219 let mut depth: usize = 0;
221 let mut writer: Option<Writer<Vec<u8>>> = None;
222
223 loop {
224 match reader.read_event_into(&mut buf)? {
225 Event::Start(e) if e.name().as_ref() == b"iati-activity" => {
226 depth = 1;
227 let mut w = Writer::new(Vec::<u8>::new());
228 w.write_event(Event::Start(e.to_owned()))?;
229 writer = Some(w);
230 }
231 Event::Empty(e) if e.name().as_ref() == b"iati-activity" => {
232 let mut w = Writer::new(Vec::<u8>::new());
234 w.write_event(Event::Empty(e.to_owned()))?;
235 let bytes = w.into_inner();
236 let frag = String::from_utf8(bytes).unwrap_or_default();
237 activities.push(parse_activity(&frag)?);
238 }
239 ev @ Event::Start(_) | ev @ Event::Empty(_) | ev @ Event::Text(_) | ev @ Event::CData(_) | ev @ Event::Comment(_) | ev @ Event::PI(_) => {
240 if let Some(w) = writer.as_mut() {
241 if let Event::Start(ref e) = ev {
242 if e.name().as_ref() == b"iati-activity" {
243 depth += 1;
244 }
245 }
246 w.write_event(ev.to_owned())?;
247 }
248 }
249 Event::End(e) => {
250 if let Some(w) = writer.as_mut() {
251 w.write_event(Event::End(e.to_owned()))?;
252 if e.name().as_ref() == b"iati-activity" {
253 depth = depth.saturating_sub(1);
254 if depth == 0 {
255 let bytes = writer.take().unwrap().into_inner();
256 let frag = String::from_utf8(bytes).unwrap_or_default();
257 activities.push(parse_activity(&frag)?);
258 }
259 }
260 }
261 }
262 Event::Eof => break,
263 _ => {}
264 }
265 buf.clear();
266 }
267
268 Ok(activities)
269}
270
271#[cfg(test)]
272mod tests {
273 use super::*;
274 use rust_decimal::Decimal;
275
276 #[test]
277 fn parse_minimal_activity_with_one_tx() {
278 let xml = r#"
279 <iati-activity default-currency="USD">
280 <iati-identifier>IATI-XYZ-12345</iati-identifier>
281 <transaction>
282 <transaction-type code="3"/>
283 <transaction-date iso-date="2023-05-01"/>
284 <value currency="EUR" value-date="2023-05-02">50.00</value>
285 </transaction>
286 </iati-activity>
287 "#;
288
289 let act = parse_activity(xml).expect("parsed");
290 assert_eq!(act.iati_identifier, "IATI-XYZ-12345");
291 assert_eq!(act.default_currency.as_ref().unwrap().0, "USD");
292 assert_eq!(act.transactions.len(), 1);
293
294 let tx = &act.transactions[0];
295 assert!(matches!(tx.tx_type, TxType::Disbursement));
296 assert_eq!(tx.date, NaiveDate::from_ymd_opt(2023, 5, 1).unwrap());
297 assert_eq!(tx.value.amount, Decimal::new(5000, 2));
298 assert_eq!(tx.value.currency.as_ref().unwrap().0, "EUR");
299 assert_eq!(
300 tx.value.value_date.unwrap(),
301 NaiveDate::from_ymd_opt(2023, 5, 2).unwrap()
302 );
303 }
304
305 #[test]
306 fn parse_two_activities_from_wrapper() {
307 let xml = r#"
308 <iati-activities version="2.03">
309 <iati-activity default-currency="USD">
310 <iati-identifier>ACT-1</iati-identifier>
311 <transaction>
312 <transaction-type code="3"/>
313 <transaction-date iso-date="2023-01-01"/>
314 <value currency="USD" value-date="2023-01-01">10.00</value>
315 </transaction>
316 </iati-activity>
317 <iati-activity default-currency="EUR">
318 <iati-identifier>ACT-2</iati-identifier>
319 <transaction>
320 <transaction-type code="4"/>
321 <transaction-date iso-date="2023-02-02"/>
322 <value currency="EUR" value-date="2023-02-03">20.00</value>
323 </transaction>
324 </iati-activity>
325 </iati-activities>
326 "#;
327
328 let acts = parse_activities(xml).expect("parsed doc");
329 assert_eq!(acts.len(), 2);
330 assert_eq!(acts[0].iati_identifier, "ACT-1");
331 assert_eq!(acts[1].iati_identifier, "ACT-2");
332 }
333
334 #[test]
335 fn empty_value_element_errors() {
336 let xml = r#"
338 <iati-activity>
339 <iati-identifier>ACT-EMPTY</iati-identifier>
340 <transaction>
341 <transaction-type code="3"/>
342 <transaction-date iso-date="2023-05-01"/>
343 <value currency="USD" value-date="2023-05-01"/>
344 </transaction>
345 </iati-activity>
346 "#;
347
348 let err = parse_activity(xml).unwrap_err();
349 assert!(matches!(err, ParseError::Missing("value")));
350 }
351}