summaryrefslogtreecommitdiffstats
path: root/cli/src/store.rs
diff options
context:
space:
mode:
authorGustav Sörnäs <gustav@sornas.net>2021-07-29 13:23:28 +0200
committerGustav Sörnäs <gustav@sornas.net>2021-07-29 13:23:28 +0200
commit60cc74d344a97b368e7b31b37d3c29aa49fc1602 (patch)
tree79eb61b3e88847e41ab1af882174fbcf6c147754 /cli/src/store.rs
parent00a865bc08753898c3cdc0d924985f427abb9f74 (diff)
downloadmoney-60cc74d344a97b368e7b31b37d3c29aa49fc1602.tar.gz
model -> transaction/store
Diffstat (limited to 'cli/src/store.rs')
-rw-r--r--cli/src/store.rs62
1 files changed, 62 insertions, 0 deletions
diff --git a/cli/src/store.rs b/cli/src/store.rs
new file mode 100644
index 0000000..2bba9c8
--- /dev/null
+++ b/cli/src/store.rs
@@ -0,0 +1,62 @@
+use std::path::{Path, PathBuf};
+
+use crate::transaction::{Category, Transaction};
+
+#[derive(Debug)]
+pub struct Store {
+ root: PathBuf,
+ transactions: Vec<Transaction>,
+ new_transactions: Vec<Transaction>,
+}
+
+impl Store {
+ //TODO Result
+ pub fn open(root: PathBuf) -> Option<Self> {
+ Some(Self {
+ transactions: Self::open_dir(&root)?,
+ new_transactions: Vec::new(),
+ root,
+ })
+ }
+
+ //TODO check if hash matches
+ //TODO Result
+ //TODO overkill? maybe we can use subfolders later on
+ fn open_dir(dir: &Path) -> Option<Vec<Transaction>> {
+ let mut res = Vec::new();
+ for entry in std::fs::read_dir(dir).ok()? {
+ let entry = entry.ok()?;
+ if entry.file_type().ok()?.is_dir() {
+ let mut transactions = Self::open_dir(&entry.path())?;
+ res.append(&mut transactions);
+ } else {
+ res.push(Transaction::open(&entry.path())?);
+ }
+ }
+ Some(res)
+ }
+
+ pub fn push(&mut self, transaction: Transaction) {
+ self.new_transactions.push(transaction);
+ }
+
+ pub fn write(&self) -> std::io::Result<()> {
+ for transaction in &self.new_transactions {
+ let mut path = self.root.clone();
+ path.push(format!("{}", transaction.id()));
+ transaction.write(&path)?;
+ }
+ Ok(())
+ }
+
+ pub fn categories(&self) -> Vec<Category> {
+ let mut categories: Vec<_> = self
+ .transactions
+ .iter()
+ .map(|t| t.category.clone())
+ .collect();
+ categories.sort();
+ categories.dedup();
+ categories
+ }
+}