cdb/src/db.rs
2024-09-21 01:49:56 +02:00

62 lines
1.7 KiB
Rust

use mongod::{Model, Referencable};
use crate::item::Item;
/// Item database
pub struct ItemDB {
index: mdq::Index,
}
impl ItemDB {
/// 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
pub async fn new(dir: &str) -> Self {
// scan for markdown item entries
let index = mdq::Index::new(dir, true);
for item in &index.documents {
let item = Item::new(item);
item.insert_overwrite().await.unwrap();
log::info!("Adding item {} to DB", item.name);
}
Self { index }
}
/// Retrieves an item by name
pub fn get_item(&self, item: &str) -> Option<Item> {
self.index
.documents
.iter()
.map(Item::new) // <-- todo : performance?
.find(|x| x.id() == item)
}
/// Get all items
pub fn items(&self) -> Vec<String> {
let mut ret = vec![];
for item in &self.index.documents {
let item = Item::new(item);
ret.push(item.name);
}
ret
}
}
/// 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
}