Skip to content

Commit

Permalink
feat(generator): add generator command
Browse files Browse the repository at this point in the history
- Add generate invoice command
- Add generate all invoice command
  • Loading branch information
tibs245 committed May 23, 2024
1 parent f4b8599 commit 28ff77c
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 36 deletions.
6 changes: 0 additions & 6 deletions src/cli/cli_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,9 @@ use thiserror::Error;

#[derive(Error, Debug)]
pub enum CliError {
#[error("Invoice ref {0} not found")]
InvoiceRefNotFound(String),

#[error("Customer {0} not found")]
CustomerNotFound(String),

#[error("Invoice to load invoice folder : {0}")]
UnableLoadInvoiceFolder(String),

#[error("Not implemented yet")]
NotImplementedYet(),

Expand Down
30 changes: 30 additions & 0 deletions src/cli/generate_all_invoice.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use std::error::Error;

use log::trace;

use crate::file_manager::context_parameters::ContextParameters;
use crate::file_manager::file_manager::FileManager;
use crate::invoice_manager::invoice_manager::InvoiceManager;

pub fn generate_all_invoice(context_parameters: ContextParameters) -> Result<(), Box<dyn Error + Sync + Send + 'static>> {
trace!("=== Get invoice");

let file_manager = FileManager::new(context_parameters.clone())?;

let all_invoice = file_manager.get_all_invoices()?;


all_invoice.iter().for_each(|invoice| {
let mut invoice_input_path = file_manager.get_invoice_path().to_owned().join(invoice.get_ref().unwrap());

invoice_input_path.set_extension("yaml");

let invoice_output_name = invoice.get_ref().unwrap() + ".pdf";

let output_path = file_manager.generate_invoice(&(invoice_input_path.as_path()), &invoice_output_name);

println!("Invoice generated in : {}", output_path.unwrap().to_string_lossy());
});

return Ok(());
}
28 changes: 28 additions & 0 deletions src/cli/generate_invoice.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use std::error::Error;

use log::trace;

use crate::cli::utils::select_invoice_or_use_default::select_invoice_or_use_default;
use crate::entities::invoice::Invoice;
use crate::file_manager::context_parameters::ContextParameters;
use crate::file_manager::file_manager::FileManager;
use crate::invoice_manager::invoice_manager::InvoiceManager;

pub fn generate_invoice(context_parameters: ContextParameters, invoice_ref: &Option<String>) -> Result<(), Box<dyn Error + Sync + Send + 'static>> {
trace!("=== Get invoice");

let file_manager = FileManager::new(context_parameters.clone())?;

let invoice_selected: Invoice = select_invoice_or_use_default(&file_manager, invoice_ref)?;

let mut invoice_input_path = file_manager.get_invoice_path().to_owned().join(invoice_selected.get_ref().unwrap());

invoice_input_path.set_extension("yaml");

let invoice_output_name = invoice_selected.get_ref().unwrap() + ".pdf";

let output_path = file_manager.generate_invoice(&(invoice_input_path.as_path()), &invoice_output_name)?;

println!("Invoice generated in : {}", output_path.to_string_lossy());
return Ok(());
}
22 changes: 2 additions & 20 deletions src/cli/get_invoice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,17 @@ use std::error::Error;

use log::trace;

use crate::cli::cli_error::CliError;
use crate::cli::cli_error::CliError::InvoiceRefNotFound;
use crate::cli::utils::select_invoice::select_invoice;
use crate::cli::utils::select_invoice_or_use_default::select_invoice_or_use_default;
use crate::entities::invoice::Invoice;
use crate::file_manager::context_parameters::ContextParameters;
use crate::file_manager::file_manager::FileManager;
use crate::invoice_manager::invoice_manager::InvoiceManager;

pub fn get_invoice(context_parameters: ContextParameters, invoice_ref: &Option<String>) -> Result<(), Box<dyn Error + Sync + Send + 'static>> {
trace!("=== Get invoice");

let file_manager = FileManager::new(context_parameters.clone())?;

let invoice_selected: Invoice = if let Some(invoice_preselected) = invoice_ref {
match file_manager.get_invoice_by_ref(&invoice_preselected) {
Ok(invoice) => Ok(invoice),
Err(_) => {
Err(Box::new(InvoiceRefNotFound(invoice_preselected.to_string())))
}
}
} else {
match select_invoice(&file_manager) {
Ok(invoice) => Ok(invoice),
Err(_) => {
Err(Box::new(CliError::UnableLoadInvoiceFolder(context_parameters.invoice_path.unwrap().to_string_lossy().to_string())))
}
}
}?;

let invoice_selected: Invoice = select_invoice_or_use_default(&file_manager, invoice_ref)?;

println!("Your invoice : {}", invoice_selected.get_ref().unwrap().to_string());
println!("{}\n", invoice_selected.title);
Expand Down
2 changes: 2 additions & 0 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ pub mod year_stats;
pub mod day_stats;
pub mod get_settings;
pub mod edit_settings;
pub mod generate_invoice;
pub mod generate_all_invoice;
8 changes: 6 additions & 2 deletions src/file_manager/file_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,10 @@ impl FileManager {

Ok(file_manager)
}

pub fn get_invoice_path(&self) -> &Path {
&self.invoice_path
}
}

impl InvoiceManager for FileManager {
Expand Down Expand Up @@ -341,8 +345,8 @@ impl InvoiceManager for FileManager {
.map_err(|e| Box::new(e) as Box<dyn Error + Sync + Send + 'static>)
}

fn generate_invoice(&self, invoice_path: &Path, filename: &str) -> Result<(), Box<dyn Error + Sync + Send + 'static>> {
generate_invoice(&self.build_path, &self.settings_file_path, &self.customer_file_path, &invoice_path, &self.target_path.to_owned().join(filename))
fn generate_invoice<'a>(&self, invoice_path: &Path, filename: &str) -> Result<PathBuf, Box<dyn Error + Sync + Send + 'static>> {
Ok(generate_invoice(&self.build_path, &self.settings_file_path, &self.customer_file_path, &invoice_path, &self.target_path.to_owned().join(filename))?.to_owned())
}
}

Expand Down
11 changes: 6 additions & 5 deletions src/generator/generate_invoice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,13 @@ fn generate_default_template() -> String {
fn generate_main_template(settings_path: &Path, customer_path: &Path, invoice_path: &Path, template_path: &Path) -> String {
let main_template = include_str!("assets/main_template.typ");

println!("{}", template_path.file_name().unwrap().to_str().unwrap());

let main_template = main_template.replace("{{ TEMPLATE_PATH }}", template_path.to_str().unwrap());
let main_template = main_template.replace("{{ SETTINGS_PATH }}", settings_path.to_str().unwrap());
let main_template = main_template.replace("{{ CUSTOMERS_PATH }}", customer_path.to_str().unwrap());
main_template.replace("{{ INVOICE_PATH }}", invoice_path.to_str().unwrap())
}

pub fn generate_invoice(build_path: &Path, settings_path: &Path, customer_path: &Path, invoice_path: &Path, target_path: &Path) -> Result<(), Box<dyn Error + Sync + Send + 'static>> {
pub fn generate_invoice<'a>(build_path: &Path, settings_path: &Path, customer_path: &Path, invoice_path: &Path, target_path: &'a Path) -> Result<&'a Path, Box<dyn Error + Sync + Send + 'static>> {
if !build_path.exists() && build_path.parent().unwrap().exists() {
info!("Create build directory in {}", build_path.to_string_lossy());
if let Err(error) = fs::create_dir(build_path) {
Expand Down Expand Up @@ -55,14 +53,17 @@ pub fn generate_invoice(build_path: &Path, settings_path: &Path, customer_path:
}
}

let mut main_file_type_name = target_path.to_owned();
main_file_type_name.set_extension("typ");

let default_template_path = build_path.to_owned().join("default_invoice_template.typ");
let main_template_path = build_path.to_owned().join("main_template.typ");
let main_template_path = build_path.to_owned().join(main_file_type_name.file_name().unwrap());

fs::write(&default_template_path, generate_default_template())?;
fs::write(&main_template_path, generate_main_template(settings_path, customer_path, invoice_path, &default_template_path))?;


Command::new("typst").arg("compile").arg("--root").arg("/").arg(main_template_path).arg(target_path).spawn()?;

Ok(())
Ok(target_path)
}
4 changes: 3 additions & 1 deletion src/invoice_manager/invoice_manager.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use std::collections::HashMap;
use std::error::Error;
use std::path::{Path, PathBuf};

use chrono::NaiveDate;

use crate::entities::customer::Customer;
use crate::entities::invoice::Invoice;
use crate::entities::settings::Settings;
Expand Down Expand Up @@ -57,5 +59,5 @@ pub trait InvoiceManager {
) -> Result<(), Box<dyn Error + Sync + Send + 'static>>;
fn get_settings(&self) -> Result<Settings, Box<dyn Error + Sync + Send + 'static>>;

fn generate_invoice<'a>(&self, invoice_path: &Path, output: &'a str) -> Result<(), Box<dyn Error + Sync + Send + 'static>>;
fn generate_invoice<'a>(&self, invoice_path: &Path, output: &str) -> Result<PathBuf, Box<dyn Error + Sync + Send + 'static>>;
}
12 changes: 10 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ use clap::{Parser, Subcommand};
use log::LevelFilter;

use crate::cli::cli_error::CliError;
use crate::file_manager::context_parameters::ContextParameters;
use crate::cli::create_customer::create_customer;
use crate::cli::create_invoice::create_invoice;
use crate::cli::day_stats::day_stats;
use crate::cli::delete_customer::delete_customer;
use crate::cli::delete_invoice::cancel_invoice;
use crate::cli::edit_customer::edit_customer;
use crate::cli::edit_settings::edit_settings;
use crate::cli::generate_all_invoice::generate_all_invoice;
use crate::cli::generate_invoice::generate_invoice;
use crate::cli::get_customer::get_customer;
use crate::cli::get_invoice::get_invoice;
use crate::cli::get_settings::get_settings;
Expand All @@ -22,6 +23,7 @@ use crate::cli::list_customers::list_customers;
use crate::cli::list_invoices::list_invoices;
use crate::cli::month_stats::month_stats;
use crate::cli::year_stats::year_stats;
use crate::file_manager::context_parameters::ContextParameters;

mod cli;
mod entities;
Expand Down Expand Up @@ -87,6 +89,10 @@ enum Commands {
#[command(subcommand)]
action: Option<CrudAction>,
},
Generate {
invoice: Option<String>
},
GenerateAll,
}

#[derive(Subcommand)]
Expand Down Expand Up @@ -183,9 +189,11 @@ fn main() {
initiate_invoice_directory(parameters)
}
Some(CrudAction::Edit { element: _element }) => { edit_settings(parameters) }
Some(CrudAction::Delete { element: _element }) => todo!("Not implemented, If you want delete the folder you can delete all files manually"),
Some(CrudAction::Delete { element: _element }) => Err(Box::new(CliError::CommandNotExists("Not implemented, If you want delete the folder you can delete all files manually".to_string()))),
None => { Err(Box::new(CliError::NotImplementedYet())) }
},
Some(Commands::Generate { invoice }) => generate_invoice(parameters, invoice),
Some(Commands::GenerateAll) => generate_all_invoice(parameters),
None => Err(Box::new(CliError::CommandNotExists("The option is not correct. Try to get help".to_string())))
};

Expand Down

0 comments on commit 28ff77c

Please sign in to comment.