summaryrefslogblamecommitdiffstats
path: root/cli/src/api/client.rs
blob: df0ca965d27a964a544f85808c1099a73d503edb (plain) (tree)
1
2
3
4
5
6
7
8
9



                                                       
 
                                    
                     
                      
                      
 
                                                 
                   
                     
                
 




                                

                     



                  



                                                                       





                                                                                               
                                                                        













                                                                                


                             

     
// 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(())
    }
}