yuki-cli 0.1.5

CLI client for the Yuki bookkeeping SOAP API
Documentation
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use quick_xml::Reader;
use quick_xml::events::Event;

use crate::error::YukiError;

use super::local_name;
use super::soap_client::{SoapClient, SoapEnvelope};

const BASE_URL: &str = "https://api.yukiworks.nl/ws/Archive.asmx";

/// A Yuki cost category.
#[derive(Debug, Clone)]
pub struct CostCategory {
    pub id: String,
    pub description: String,
}

/// A Yuki payment method.
#[derive(Debug, Clone)]
pub struct PaymentMethod {
    pub id: String,
    pub description: String,
}

/// A document returned by the Yuki archive search.
#[derive(Debug, Clone)]
pub struct ArchiveDocument {
    pub id: String,
    pub subject: String,
    pub document_date: String,
    pub amount: String,
    pub folder: String,
    pub contact_name: String,
    pub file_name: String,
    pub reference: String,
}

/// Client for the Yuki Archive SOAP service.
pub struct ArchiveClient {
    soap: SoapClient,
}

impl ArchiveClient {
    pub fn new() -> Self {
        Self {
            soap: SoapClient::new(BASE_URL),
        }
    }

    fn require_session(&self) -> Result<&str, YukiError> {
        self.soap.session_id().ok_or_else(|| {
            YukiError::AuthFailed("not authenticated — call authenticate() first".to_string())
        })
    }

    /// Authenticate with the Yuki API and store the session ID.
    pub async fn authenticate(&mut self, api_key: &str) -> Result<String, YukiError> {
        self.soap.authenticate(api_key).await
    }

    /// List all documents in an archive folder by folder ID.
    pub async fn documents_in_folder(
        &self,
        folder_id: i32,
        start_date: &str,
        end_date: &str,
    ) -> Result<Vec<ArchiveDocument>, YukiError> {
        let session = self.require_session()?;
        let envelope = SoapEnvelope::new("DocumentsInFolder")
            .session(session)
            .param("folderID", &folder_id.to_string())
            .param("sortOrder", "DocumentDateDesc")
            .param("startDate", start_date)
            .param("endDate", end_date)
            .param("numberOfRecords", "100")
            .param("startRecord", "0")
            .build();
        let body = self.soap.call("DocumentsInFolder", envelope).await?;
        Self::parse_archive_documents(&body)
    }

    /// List all documents of a given document type.
    pub async fn documents_by_type(&self, doc_type: i32) -> Result<String, YukiError> {
        let session = self.require_session()?;
        let envelope = SoapEnvelope::new("DocumentsByType")
            .session(session)
            .param("documentType", &doc_type.to_string())
            .build();
        self.soap.call("DocumentsByType", envelope).await
    }

    /// Search documents in the archive using a free-text query within a date range.
    ///
    /// Pass an empty string for `search_text` to retrieve all documents in the period.
    /// Returns up to 500 results sorted by document date descending.
    pub async fn search_documents(
        &self,
        search_text: &str,
        start_date: &str,
        end_date: &str,
    ) -> Result<Vec<ArchiveDocument>, YukiError> {
        let session = self.require_session()?;
        let envelope = SoapEnvelope::new("SearchDocuments")
            .session(session)
            .param("searchOption", "All")
            .param("searchText", search_text)
            .param("folderID", "-1")
            .param("tabID", "-1")
            .param("sortOrder", "DocumentDateDesc")
            .param("startDate", start_date)
            .param("endDate", end_date)
            .param("numberOfRecords", "500")
            .param("startRecord", "0")
            .build();
        let body = self.soap.call("SearchDocuments", envelope).await?;
        Self::parse_archive_documents(&body)
    }

    /// List documents of a given type that were modified since the specified date.
    pub async fn modified_documents_by_type(
        &self,
        doc_type: i32,
        modified_since: &str,
    ) -> Result<String, YukiError> {
        let session = self.require_session()?;
        let envelope = SoapEnvelope::new("ModifiedDocumentsByType")
            .session(session)
            .param("documentType", &doc_type.to_string())
            .param("modifiedSince", modified_since)
            .build();
        self.soap.call("ModifiedDocumentsByType", envelope).await
    }

    /// Upload a document to the archive without additional metadata.
    ///
    /// Returns the document ID assigned by Yuki.
    pub async fn upload_document(
        &self,
        admin_id: &str,
        filename: &str,
        data_base64: &str,
        folder_id: i32,
    ) -> Result<String, YukiError> {
        let session = self.require_session()?;
        let envelope = SoapEnvelope::new("UploadDocument")
            .session(session)
            .param("fileName", filename)
            .param("data", data_base64)
            .param("folder", &folder_id.to_string())
            .param("administrationID", admin_id)
            .build();
        let body = self.soap.call("UploadDocument", envelope).await?;
        SoapClient::parse_single_result(&body, "UploadDocumentResult")
    }

    /// Upload a document to the archive with invoice metadata.
    ///
    /// Returns the document ID assigned by Yuki.
    #[allow(clippy::too_many_arguments)]
    pub async fn upload_document_with_data(
        &self,
        admin_id: &str,
        filename: &str,
        data_base64: &str,
        folder_id: i32,
        currency: &str,
        amount: f64,
        cost_category: Option<&str>,
        payment_method: Option<&str>,
        project: Option<&str>,
        remarks: Option<&str>,
    ) -> Result<String, YukiError> {
        let session = self.require_session()?;
        let amount_str = format!("{amount:.2}");
        let envelope = SoapEnvelope::new("UploadDocumentWithData")
            .session(session)
            .param("fileName", filename)
            .param("data", data_base64)
            .param("folder", &folder_id.to_string())
            .param("administrationID", admin_id)
            .param("currency", currency)
            .param("amount", &amount_str)
            .param("costCategory", cost_category.unwrap_or(""))
            .param("paymentMethod", payment_method.unwrap_or("0"))
            .param("project", project.unwrap_or(""))
            .param("remarks", remarks.unwrap_or(""))
            .build();
        let body = self.soap.call("UploadDocumentWithData", envelope).await?;
        SoapClient::parse_single_result(&body, "UploadDocumentWithDataResult")
    }

    /// Retrieve all available cost categories.
    pub async fn cost_categories(&self) -> Result<Vec<CostCategory>, YukiError> {
        let session = self.require_session()?;
        let envelope = SoapEnvelope::new("CostCategories").session(session).build();
        let body = self.soap.call("CostCategories", envelope).await?;
        Self::parse_cost_categories(&body)
    }

    /// Retrieve all available payment methods.
    pub async fn payment_methods(&self) -> Result<Vec<PaymentMethod>, YukiError> {
        let session = self.require_session()?;
        let envelope = SoapEnvelope::new("PaymentMethods").session(session).build();
        let body = self.soap.call("PaymentMethods", envelope).await?;
        Self::parse_payment_methods(&body)
    }

    /// Parse a SearchDocuments or DocumentsInFolder SOAP response into a list of documents.
    ///
    /// Each `<Document ID="uuid">` element carries child elements for each field.
    /// The document ID is an XML attribute; all other fields are child text nodes.
    pub fn parse_archive_documents(xml: &str) -> Result<Vec<ArchiveDocument>, YukiError> {
        let mut reader = Reader::from_str(xml);
        reader.config_mut().trim_text(true);

        let mut documents = Vec::new();
        let mut in_document = false;
        let mut current_field = String::new();
        let mut doc = ArchiveDocument {
            id: String::new(),
            subject: String::new(),
            document_date: String::new(),
            amount: String::new(),
            folder: String::new(),
            contact_name: String::new(),
            file_name: String::new(),
            reference: String::new(),
        };
        let mut buf = Vec::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(ref e)) => {
                    let local = local_name(e.name().as_ref()).to_string();
                    match local.as_str() {
                        "Document" => {
                            in_document = true;
                            doc = ArchiveDocument {
                                id: String::new(),
                                subject: String::new(),
                                document_date: String::new(),
                                amount: String::new(),
                                folder: String::new(),
                                contact_name: String::new(),
                                file_name: String::new(),
                                reference: String::new(),
                            };
                            for attr in e.attributes().flatten() {
                                if attr.key.as_ref() == b"ID" {
                                    doc.id = String::from_utf8_lossy(&attr.value).to_string();
                                }
                            }
                        }
                        "Subject" | "DocumentDate" | "Amount" | "Folder" | "ContactName"
                        | "FileName" | "Reference"
                            if in_document =>
                        {
                            current_field = local;
                        }
                        _ => {}
                    }
                }
                Ok(Event::Text(ref e)) if in_document && !current_field.is_empty() => {
                    let text = e
                        .unescape()
                        .map_err(|e| YukiError::Xml(e.to_string()))?
                        .trim()
                        .to_string();
                    match current_field.as_str() {
                        "Subject" => doc.subject = text,
                        "DocumentDate" => doc.document_date = text,
                        "Amount" => doc.amount = text,
                        "Folder" => doc.folder = text,
                        "ContactName" => doc.contact_name = text,
                        "FileName" => doc.file_name = text,
                        "Reference" => doc.reference = text,
                        _ => {}
                    }
                }
                Ok(Event::End(ref e)) => {
                    let name = e.name();
                    let local = local_name(name.as_ref());
                    match local {
                        "Subject" | "DocumentDate" | "Amount" | "Folder" | "ContactName"
                        | "FileName" | "Reference" => {
                            current_field.clear();
                        }
                        "Document" => {
                            if !doc.id.is_empty() {
                                documents.push(doc.clone());
                            }
                            in_document = false;
                        }
                        _ => {}
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(YukiError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(documents)
    }

    /// Parse a CostCategories SOAP response.
    ///
    /// Each `CostCategory` element carries an `ID` attribute and a `Description` child element:
    /// `<CostCategory ID="45100"><Description>...</Description></CostCategory>`
    pub fn parse_cost_categories(xml: &str) -> Result<Vec<CostCategory>, YukiError> {
        let mut reader = Reader::from_str(xml);
        reader.config_mut().trim_text(true);

        let mut categories = Vec::new();
        let mut current_id = String::new();
        let mut current_desc = String::new();
        let mut in_category = false;
        let mut in_description = false;
        let mut buf = Vec::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(ref e)) => {
                    let local = local_name(e.name().as_ref()).to_string();
                    match local.as_str() {
                        "CostCategory" => {
                            in_category = true;
                            current_id.clear();
                            current_desc.clear();
                            for attr in e.attributes().flatten() {
                                if attr.key.as_ref() == b"ID" {
                                    current_id = String::from_utf8_lossy(&attr.value).to_string();
                                }
                            }
                        }
                        "Description" if in_category => {
                            in_description = true;
                        }
                        _ => {}
                    }
                }
                Ok(Event::Text(ref e)) if in_description => {
                    current_desc = e
                        .unescape()
                        .map_err(|e| YukiError::Xml(e.to_string()))?
                        .trim()
                        .to_string();
                }
                Ok(Event::End(ref e)) => {
                    let name = e.name();
                    let local = local_name(name.as_ref());
                    match local {
                        "Description" => in_description = false,
                        "CostCategory" => {
                            if !current_id.is_empty() {
                                categories.push(CostCategory {
                                    id: current_id.clone(),
                                    description: current_desc.clone(),
                                });
                            }
                            in_category = false;
                        }
                        _ => {}
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(YukiError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(categories)
    }

    /// Parse a PaymentMethods SOAP response.
    ///
    /// Each `PaymentMethod` element carries an `ID` attribute and a `Description` child element:
    /// `<PaymentMethod ID="4"><Description>...</Description></PaymentMethod>`
    pub fn parse_payment_methods(xml: &str) -> Result<Vec<PaymentMethod>, YukiError> {
        let mut reader = Reader::from_str(xml);
        reader.config_mut().trim_text(true);

        let mut methods = Vec::new();
        let mut current_id = String::new();
        let mut current_desc = String::new();
        let mut in_method = false;
        let mut in_description = false;
        let mut buf = Vec::new();

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(Event::Start(ref e)) => {
                    let local = local_name(e.name().as_ref()).to_string();
                    match local.as_str() {
                        "PaymentMethod" => {
                            in_method = true;
                            current_id.clear();
                            current_desc.clear();
                            for attr in e.attributes().flatten() {
                                if attr.key.as_ref() == b"ID" {
                                    current_id = String::from_utf8_lossy(&attr.value).to_string();
                                }
                            }
                        }
                        "Description" if in_method => {
                            in_description = true;
                        }
                        _ => {}
                    }
                }
                Ok(Event::Text(ref e)) if in_description => {
                    current_desc = e
                        .unescape()
                        .map_err(|e| YukiError::Xml(e.to_string()))?
                        .trim()
                        .to_string();
                }
                Ok(Event::End(ref e)) => {
                    let name = e.name();
                    let local = local_name(name.as_ref());
                    match local {
                        "Description" => in_description = false,
                        "PaymentMethod" => {
                            if !current_id.is_empty() {
                                methods.push(PaymentMethod {
                                    id: current_id.clone(),
                                    description: current_desc.clone(),
                                });
                            }
                            in_method = false;
                        }
                        _ => {}
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(YukiError::Xml(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(methods)
    }
}

impl Default for ArchiveClient {
    fn default() -> Self {
        Self::new()
    }
}