cdb/src/db.rs

63 lines
1.7 KiB
Rust
Raw Normal View History

2024-08-28 07:38:10 +00:00
use mongod::Model;
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-05-03 16:22:59 +00:00
pub struct ItemDB {
index: mdq::Index,
}
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
let index = mdq::Index::new(dir, true);
for item in &index.documents {
2024-06-22 00:05:22 +00:00
let item = Item::new(item);
2024-08-28 07:38:10 +00:00
item.insert_overwrite().await.unwrap();
2024-07-24 14:38:56 +00:00
log::info!("Adding item {} to DB", item.name);
2024-05-03 16:22:59 +00:00
}
2024-05-10 08:56:07 +00:00
Self { index }
2024-05-03 16:22:59 +00:00
}
/// Retrieves an item by name
pub fn get_item(&self, item: &str) -> Option<Item> {
2024-08-28 07:38:10 +00:00
self.index
.documents
.iter()
.map(Item::new) // <-- todo : performance?
.find(|x| x.name == item)
2024-05-03 16:22:59 +00:00
}
/// Get all items
pub fn items(&self) -> Vec<String> {
let mut ret = vec![];
for item in &self.index.documents {
2024-06-22 00:05:22 +00:00
let item = Item::new(item);
2024-05-03 16:22:59 +00:00
ret.push(item.name);
}
ret
}
}
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
}