Skip to main content

yuki_cli/cli/
contacts.rs

1use crate::client::contact::{Contact, ContactClient};
2use crate::config::Config;
3use crate::error::YukiError;
4use crate::output::{
5    ListOptions, OutputFormat, apply_pagination, format_json, format_table, is_tty,
6};
7
8fn contacts_to_rows(contacts: &[Contact]) -> Vec<Vec<String>> {
9    contacts
10        .iter()
11        .map(|c| {
12            vec![
13                c.id.clone(),
14                c.name.clone(),
15                c.contact_type.clone(),
16                c.country.clone(),
17                if c.is_supplier { "Yes" } else { "No" }.to_string(),
18                if c.is_customer { "Yes" } else { "No" }.to_string(),
19            ]
20        })
21        .collect()
22}
23
24pub async fn search(
25    config: &Config,
26    _admin: Option<&str>,
27    query: &str,
28    format: Option<&str>,
29) -> Result<(), YukiError> {
30    let mut client = ContactClient::new();
31    client.authenticate(&config.api_key).await?;
32    let contacts = client.search_contacts(query).await?;
33
34    let headers = vec![
35        "ID".into(),
36        "Name".into(),
37        "Type".into(),
38        "Country".into(),
39        "Supplier".into(),
40        "Customer".into(),
41    ];
42    let rows = contacts_to_rows(&contacts);
43
44    let fmt = OutputFormat::from_flag(format, is_tty());
45    match fmt {
46        OutputFormat::Table => println!("{}", format_table(&headers, &rows)),
47        OutputFormat::Json => println!("{}", format_json(&headers, &rows)),
48    }
49    Ok(())
50}
51
52pub async fn list(
53    config: &Config,
54    _admin: Option<&str>,
55    contact_type: Option<&str>,
56    format: Option<&str>,
57    opts: ListOptions<'_>,
58) -> Result<(), YukiError> {
59    let mut client = ContactClient::new();
60    client.authenticate(&config.api_key).await?;
61    let contacts = client
62        .get_suppliers_and_customers(contact_type.unwrap_or(""))
63        .await?;
64
65    let headers = vec![
66        "ID".into(),
67        "Name".into(),
68        "Type".into(),
69        "Country".into(),
70        "Supplier".into(),
71        "Customer".into(),
72    ];
73    let mut rows = contacts_to_rows(&contacts);
74    apply_pagination(&mut rows, &opts);
75
76    let fmt = OutputFormat::from_flag(format, is_tty());
77    match fmt {
78        OutputFormat::Table => println!("{}", format_table(&headers, &rows)),
79        OutputFormat::Json => println!("{}", format_json(&headers, &rows)),
80    }
81    Ok(())
82}