cdb/src/db.rs

55 lines
1.5 KiB
Rust
Raw Normal View History

2024-09-23 07:26:11 +00:00
use std::collections::HashMap;
2024-06-22 00:05:22 +00:00
use crate::item::Item;
2024-05-03 16:22:59 +00:00
2024-06-22 00:05:22 +00:00
/// Item database
2024-10-07 19:02:23 +00:00
#[derive(Debug, Clone)]
2024-05-03 16:22:59 +00:00
pub struct ItemDB {
2024-09-23 07:26:11 +00:00
index: HashMap<String, Item>,
2024-05-03 16:22:59 +00:00
}
impl ItemDB {
2024-06-22 00:05:22 +00:00
/// Create a new item database using `dir` as the base.
///
/// The directory should contain markdown documents with valid frontmatter to be parsed into `Item`s
2024-05-10 08:56:07 +00:00
pub async fn new(dir: &str) -> Self {
2024-05-03 16:22:59 +00:00
// scan for markdown item entries
2024-09-23 07:26:11 +00:00
let index = mdq::Index::new(dir, false);
let mut items = HashMap::new();
2024-05-03 16:22:59 +00:00
for item in &index.documents {
2024-06-22 00:05:22 +00:00
let item = Item::new(item);
2024-10-07 18:53:58 +00:00
items.insert(item.id.clone(), item);
2024-05-03 16:22:59 +00:00
}
2024-09-23 07:26:11 +00:00
Self { index: items }
2024-05-03 16:22:59 +00:00
}
/// Retrieves an item by name
2024-09-23 07:26:11 +00:00
pub fn get_item(&self, item: &str) -> Option<&Item> {
self.index.get(item)
2024-05-03 16:22:59 +00:00
}
/// Get all items
2024-09-23 07:26:11 +00:00
pub fn items(&self) -> Vec<&String> {
self.index.keys().collect()
2024-05-03 16:22:59 +00:00
}
}
2024-09-12 08:58:49 +00:00
/// Get all item variants which inventory is under the minimum. Returns a Vec with the item variants id and the missing quanity to reach minimum.
pub async fn get_items_without_min_satisfied(db: &ItemDB) -> Vec<(String, i64)> {
let mut ret = Vec::new();
for item in db.items() {
let item = db.get_item(&item).unwrap();
for var in &item.variants {
let res = var.1.is_below_min().await;
if res.0 {
ret.push((format!("{}::{}", var.1.item, var.1.variant), res.1));
}
}
}
ret
}