use crate::cli::{ProductCommand, UnitCommand}; use anyhow::{Context, Result}; use rocie_client::{ apis::{ api_get_product_api::{product_by_id, products}, api_get_unit_api::{unit_by_id, units}, api_set_product_api::{associate_barcode, register_product}, api_set_unit_api::register_unit, configuration::Configuration, }, models::{Barcode, UnitAmount, UnitStub}, }; pub(crate) async fn product(config: &Configuration, command: ProductCommand) -> Result<()> { match command { ProductCommand::Register { name, description, parent, } => { let new_id = register_product( config, rocie_client::models::ProductStub { description: Some(description), // TODO: Fix the duplicate option name, parent, }, ) .await .context("Failed to register new product")?; println!("Registered new product with id: {new_id}"); } ProductCommand::Get { id } => { let product = product_by_id(config, id.to_string().as_str()) .await .with_context(|| format!("Failed to get product with id: {id}"))?; println!("{product:#?}"); } ProductCommand::AssociateBarcode { product_id, barcode_number, amount_value, amount_unit_id, } => associate_barcode( config, product_id.to_string().as_str(), Barcode { id: i64::from(barcode_number), amount: Box::new(UnitAmount { unit: amount_unit_id, value: i64::from(amount_value), }), }, ) .await .context("Failed to associated barcode")?, ProductCommand::List {} => { let all = products(config) .await .context("Failed to get all products")?; for product in all { print!("{}: {}", product.name, product.id); if let Some(description) = product .description .expect("Superflous Option wrapping in api") { println!(" ({description})"); } else { println!(); } for barcode in product.associated_bar_codes { let unit = unit_by_id(config, barcode.amount.unit.to_string().as_str()).await?; println!( " - {}: {} {}", barcode.id, barcode.amount.value, if barcode.amount.value == 1 { unit.full_name_singular } else { unit.full_name_plural } ); } } } } Ok(()) } pub(crate) async fn unit(config: &Configuration, command: UnitCommand) -> Result<()> { match command { UnitCommand::Register { full_name_singular, full_name_plural, short_name, description, } => { let new_id = register_unit( config, UnitStub { description: Some(description), full_name_plural, full_name_singular, short_name, }, ) .await .context("Failed to register unit")?; println!("Registered new unit with id: {new_id}"); } UnitCommand::List {} => { let all = units(config).await.context("Failed to get all products")?; for unit in all { print!("{}: {}", unit.full_name_singular, unit.id); if let Some(description) = unit.description.expect("Superflous Option wrapping in api") { println!(" ({description})"); } else { println!(); } } } UnitCommand::GetById { id } => { let unit = unit_by_id(config, id.to_string().as_str()) .await .context("Failed to find unit")?; println!( "Unit: {} ({},{},{})", unit.id, unit.full_name_singular, unit.full_name_plural, unit.short_name ); } } Ok(()) }