summaryrefslogtreecommitdiffstats
path: root/cli/src/main.rs
blob: 794db9f6fe189125aa979882dd43c2764168fc0f (plain) (blame)
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
// Command line app for the fatura invoicing system
//
// SPDX-FileCopyrightText: 2024 Eilertsens Kodeknekkeri
// SPDX-FileCopyrightText: 2024 Harald Eilertsen
//
// SPDX-License-Identifier: AGPL-3.0-or-later

mod api;

use api::{Client, Connection};

fn main() -> Result<(), Box<dyn std::error::Error>> {

    let conn = Connection::new(
        std::env::var("FAKTURA_API_URL")?,
        std::env::var("FAKTURA_JWT_TOKEN")?
    );

    let mut args = std::env::args().skip(1);
    if let Some(cmd) = args.next() {
        match cmd.as_str() {
            "--list-clients" => {
                list_clients(conn)?;
            },
            "--add-client" => {
                add_client(conn, &args.next()
                    .expect("expected new client json data"))?;
            },
            "--edit-client" => {
                let client_id = args.next().expect("missing client id").parse()?;
                let json = args.next().expect("missing json data");
                Client::update(conn, client_id, &json)?;
            },
            &_ => {
                println!("Unknown command: {}", cmd);
            }
        }
    }

    Ok(())
}

fn list_clients(conn: Connection) -> Result<(), Box<dyn std::error::Error>> {
    let clients = Client::all(conn)?;

    for c in clients {
        print!("{}: {} <{}>", c.id, c.name, c.email);
        if let Some(contact) = c.contact {
            print!(", c/o {}", contact);
        }
        if let Some(address) = c.address {
            print!(", {}", address);
        }
        if let Some(phone) = c.phone {
            print!(", ph: {}", phone);
        }
        if c.vat {
            print!(", VAT");
        }
        println!("");
    }

    Ok(())
}

fn add_client(conn: Connection, json: &str) -> Result<(), Box<dyn std::error::Error>> {
    let client: Client = serde_json::from_str(json)?;
    println!("{:?}", client);
    client.save(conn)
}