aboutsummaryrefslogtreecommitdiff
path: root/apps/koffice/libko/src/store.rs
blob: 7ce33ce5fd51e55c3a246445d123522c6b67c55b (plain)
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
use crate::{
    cass::{Cassiopeia, TimeFile},
    Address, Client, Io,
};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::{
    fs::File,
    io::{Read, Write},
    path::PathBuf,
};
use xdg::BaseDirectories as BaseDirs;

#[derive(Debug)]
pub struct Meta {
    clients: BTreeMap<String, Client>,
    pub dir: BaseDirs,
    pub invoice_dir: PathBuf,
    pub template: Option<PathBuf>,
    pub revisioning: bool,

    /// Optional current timefile path
    pub timefile: Option<TimeFile>,
    pub project_id: Option<String>,
}

///
#[derive(Debug, Serialize, Deserialize)]
pub struct Config {
    pub revisioning: bool,
    pub invoice_dir: PathBuf,
}

impl Meta {
    pub fn new(dir: BaseDirs) -> Self {
        // Get the path to the configuration, and make sure a default
        // configuration is created if none exists yet.
        let path = dir.find_config_file("config.yml").unwrap_or_else(|| {
            let path = dir.place_config_file("config.yml").unwrap();
            let mut cfg = File::create(path.clone()).unwrap();

            let buf = "revisioning: true
invoicedir: $HOME/.local/k-office/";
            cfg.write_all(buf.as_bytes()).unwrap();
            path
        });

        let mut cfg = File::open(path).unwrap();

        let mut buf = String::new();
        cfg.read_to_string(&mut buf).unwrap();
        let yml = Config::from_yaml(buf);

        Self {
            dir,
            clients: BTreeMap::new(),
            invoice_dir: yml.invoice_dir,
            template: None,
            revisioning: yml.revisioning,
            timefile: None,
            project_id: None,
        }
    }

    pub fn load_timefile(&mut self, path: &str) {
        let timefile = Cassiopeia::load(path)
            .expect("Timefile not found")
            .timefile();
        self.timefile = Some(timefile);
    }

    pub fn client_mut(&mut self, name: &str) -> Option<&mut Client> {
        self.clients.get_mut(name)
    }

    pub fn new_client(&mut self, name: &str, address: Address) {
        self.clients.insert(
            name.to_string(),
            Client {
                name: name.to_string(),
                address,
                last_project: None,
            },
        );
    }
}

/// Initialise a k-office application state
pub fn initialise() -> Meta {
    let dir = BaseDirs::with_prefix("k-koffice").unwrap();
    dir.create_config_directory("")
        .expect("Couldn't create config directory");
    Meta::new(dir)
}