summaryrefslogtreecommitdiffstats
path: root/cli/src/api/client.rs
blob: df0ca965d27a964a544f85808c1099a73d503edb (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
// SPDX-FileCopyrightText: 2024 Eilertsens Kodeknekkeri
// SPDX-FileCopyrightText: 2024 Harald Eilertsen
//
// SPDX-License-Identifier: AGPL-3.0-or-later

use serde::{Deserialize, Serialize};
use serde_json::json;
use std::error::Error;
use super::Connection;

#[derive(Debug, Default, Deserialize, Serialize)]
pub struct Client {
    #[serde(default)]
    pub id: u32,

    pub name: String,
    pub contact: Option<String>,
    pub address: Option<String>,
    pub email: String,
    pub phone: Option<String>,

    #[serde(default)]
    pub vat: bool,
}

impl Client {
    pub fn all(conn: Connection) -> Result<Vec<Self>, Box<dyn Error>> {
        Ok(conn.get("clients")?)
    }

    pub fn update(conn: Connection, client_id: u32, data: &str) -> Result<(), Box<dyn Error>> {
        let resp = conn.patch(&format!("clients?id=eq.{}", client_id), data)?;
        println!("{}", resp);
        Ok(())
    }

    pub fn save(&self, conn: Connection) -> Result<(), Box<dyn Error>> {
        // By default the `id` of a newly created client will be 0,
        // which will cause the API to add the client with id=0. This works once
        // but then fails for the next clients added.
        //
        // To fix this, we remove the `id` from the json payload before
        // we pass it to the API.
        let mut json = json!(&self)
            .as_object()
            .ok_or("not an object")?
            .clone();

        json.remove("id");

        let resp = conn.post("clients", &json)?;

        println!("{}", resp);
        Ok(())
    }
}