Put edit in a sub struct to split it

This commit is contained in:
Quentin Boyer 2023-11-13 21:58:22 +01:00
parent 140e70616a
commit c5267cc192

View file

@ -623,34 +623,6 @@ where
} }
} }
#[derive(Clone, Debug)]
enum Message {
Event(Event),
AddRecurring(String, f64),
AddSaving(String, f64),
FontLoaded(Result<(), font::Error>),
AddVariable(String),
EditVariable(String, String),
EditEarings1(f64),
EditEarings2(f64),
SetDate(ReportDate),
Load(ReportDate),
InitFrom(ReportDate),
}
struct Glaurung {
config: Config,
recurring: BTreeMap<String, f64>,
variable: BTreeMap<String, (String, Option<f64>)>,
savings: BTreeMap<String, f64>,
save_file: PathBuf,
earnings_1: f64,
earnings_2: f64,
archive: BTreeMap<ReportDate, Report>,
date: Option<ReportDate>,
}
#[derive(Serialize, Deserialize, Default, Clone)] #[derive(Serialize, Deserialize, Default, Clone)]
struct Report { struct Report {
#[serde(default)] #[serde(default)]
@ -757,7 +729,40 @@ struct AppConfig {
config: Config, config: Config,
} }
impl Glaurung { #[derive(Clone, Debug)]
enum Message {
Event(Event),
AddRecurring(String, f64),
AddSaving(String, f64),
FontLoaded(Result<(), font::Error>),
AddVariable(String),
EditVariable(String, String),
EditEarings1(f64),
EditEarings2(f64),
SetDate(ReportDate),
Load(ReportDate),
InitFrom(ReportDate),
}
struct Glaurung {
config: Config,
edit: EditState,
archive: BTreeMap<ReportDate, Report>,
}
struct EditState {
recurring: BTreeMap<String, f64>,
variable: BTreeMap<String, (String, Option<f64>)>,
savings: BTreeMap<String, f64>,
save_file: PathBuf,
earnings_1: f64,
earnings_2: f64,
date: Option<ReportDate>,
}
impl EditState {
fn load(&mut self, report: Report) { fn load(&mut self, report: Report) {
self.recurring = report.recurring; self.recurring = report.recurring;
self.savings = report.savings; self.savings = report.savings;
@ -800,10 +805,10 @@ impl Glaurung {
} }
} }
fn save(&self) { fn save(&self, archive: BTreeMap<ReportDate, Report>) {
let mut save = SaveFile { let mut save = SaveFile {
current: Default::default(), current: Default::default(),
archive: self.archive.clone(), archive,
}; };
match self.date { match self.date {
@ -835,17 +840,19 @@ impl Application for Glaurung {
fn new(config: Self::Flags) -> (Self, Command<Message>) { fn new(config: Self::Flags) -> (Self, Command<Message>) {
let mut this = Self { let mut this = Self {
config: config.config, config: config.config,
edit: EditState {
recurring: Default::default(), recurring: Default::default(),
savings: Default::default(), savings: Default::default(),
archive: config.save.archive,
variable: Default::default(), variable: Default::default(),
earnings_1: Default::default(), earnings_1: Default::default(),
earnings_2: Default::default(), earnings_2: Default::default(),
save_file: config.save_file, save_file: config.save_file,
date: None, date: None,
},
archive: config.save.archive,
}; };
this.load(config.save.current); this.edit.load(config.save.current);
( (
this, this,
@ -857,7 +864,7 @@ impl Application for Glaurung {
fn title(&self) -> String { fn title(&self) -> String {
let mut title = "Glaurung - Account Manager".to_string(); let mut title = "Glaurung - Account Manager".to_string();
if let Some(d) = &self.date { if let Some(d) = &self.edit.date {
title += &format!(" ({d})"); title += &format!(" ({d})");
} }
title title
@ -870,42 +877,43 @@ impl Application for Glaurung {
fn update(&mut self, message: Self::Message) -> Command<Message> { fn update(&mut self, message: Self::Message) -> Command<Message> {
match message { match message {
Message::AddRecurring(name, value) => { Message::AddRecurring(name, value) => {
self.recurring.insert(name, value); self.edit.recurring.insert(name, value);
} }
Message::AddSaving(name, value) => { Message::AddSaving(name, value) => {
self.savings.insert(name, value); self.edit.savings.insert(name, value);
} }
Message::FontLoaded(r) => r.expect("could not load font"), Message::FontLoaded(r) => r.expect("could not load font"),
Message::Event(ev) => { Message::Event(ev) => {
if let Event::Window(window::Event::CloseRequested) = ev { if let Event::Window(window::Event::CloseRequested) = ev {
self.save(); self.edit.save(self.archive.clone());
return window::close(); return window::close();
} }
} }
Message::AddVariable(name) => { Message::AddVariable(name) => {
self.variable.insert(name, ("0".into(), Some(0.))); self.edit.variable.insert(name, ("0".into(), Some(0.)));
} }
Message::EditVariable(v, expr) => { Message::EditVariable(v, expr) => {
if let Some(entry) = self.variable.get_mut(&v) { if let Some(entry) = self.edit.variable.get_mut(&v) {
entry.1 = calc::calc_parser::calc(&expr).ok(); entry.1 = calc::calc_parser::calc(&expr).ok();
entry.0 = expr; entry.0 = expr;
} }
} }
Message::EditEarings1(v) => { Message::EditEarings1(v) => {
self.earnings_1 = v; self.edit.earnings_1 = v;
} }
Message::EditEarings2(v) => { Message::EditEarings2(v) => {
self.earnings_2 = v; self.edit.earnings_2 = v;
} }
Message::SetDate(d) => self.date = Some(d), Message::SetDate(d) => self.edit.date = Some(d),
Message::Load(d) => { Message::Load(d) => {
self.save(); self.edit.save(self.archive.clone());
self.date = Some(d); self.edit.date = Some(d);
self.load(self.archive.get(&d).cloned().unwrap_or_default()); self.edit
.load(self.archive.get(&d).cloned().unwrap_or_default());
} }
Message::InitFrom(d) => { Message::InitFrom(d) => {
if let Some(report) = self.archive.get(&d) { if let Some(report) = self.archive.get(&d) {
self.init_from(report.clone()) self.edit.init_from(report.clone())
} }
} }
} }
@ -915,17 +923,18 @@ impl Application for Glaurung {
fn view(&self) -> Element { fn view(&self) -> Element {
let total_spendings = self let total_spendings = self
.edit
.recurring .recurring
.values() .values()
.chain(self.variable.values().flat_map(|(_, f)| f)) .chain(self.edit.variable.values().flat_map(|(_, f)| f))
.sum::<f64>(); .sum::<f64>();
let total_earnings = self.earnings_1 + self.earnings_2; let total_earnings = self.edit.earnings_1 + self.edit.earnings_2;
let main_account = total_spendings; let main_account = total_spendings;
let main_factor = main_account / total_earnings; let main_factor = main_account / total_earnings;
let mut remaining_1 = self.earnings_1; let mut remaining_1 = self.edit.earnings_1;
let mut remaining_2 = self.earnings_2; let mut remaining_2 = self.edit.earnings_2;
let mut same_percent = column![ let mut same_percent = column![
text("Same percent").size(TEXT_H2), text("Same percent").size(TEXT_H2),
@ -933,37 +942,37 @@ impl Application for Glaurung {
text(format!( text(format!(
"{}: {:.2} €", "{}: {:.2} €",
self.config.person_1, self.config.person_1,
self.earnings_1 * main_factor self.edit.earnings_1 * main_factor
)), )),
text(format!( text(format!(
"{}: {:.2} €", "{}: {:.2} €",
self.config.person_2, self.config.person_2,
self.earnings_2 * main_factor self.edit.earnings_2 * main_factor
)), )),
]; ];
remaining_1 -= self.earnings_1 * main_factor; remaining_1 -= self.edit.earnings_1 * main_factor;
remaining_2 -= self.earnings_2 * main_factor; remaining_2 -= self.edit.earnings_2 * main_factor;
let mut total_depositing = main_account; let mut total_depositing = main_account;
for (account, amount) in &self.savings { for (account, amount) in &self.edit.savings {
let factor = amount / total_earnings; let factor = amount / total_earnings;
same_percent = same_percent same_percent = same_percent
.push(text(account).size(TEXT_EMPH2)) .push(text(account).size(TEXT_EMPH2))
.push(text(format!( .push(text(format!(
"{}: {:.2} €", "{}: {:.2} €",
self.config.person_1, self.config.person_1,
self.earnings_1 * factor self.edit.earnings_1 * factor
))) )))
.push(text(format!( .push(text(format!(
"{}: {:.2} €", "{}: {:.2} €",
self.config.person_2, self.config.person_2,
self.earnings_2 * factor self.edit.earnings_2 * factor
))); )));
remaining_1 -= self.earnings_1 * factor; remaining_1 -= self.edit.earnings_1 * factor;
remaining_2 -= self.earnings_2 * factor; remaining_2 -= self.edit.earnings_2 * factor;
total_depositing += amount; total_depositing += amount;
} }
@ -975,16 +984,16 @@ impl Application for Glaurung {
text(format!( text(format!(
"{}: {:.2} €", "{}: {:.2} €",
self.config.person_1, self.config.person_1,
self.earnings_1 - remaining_per_person self.edit.earnings_1 - remaining_per_person
)), )),
text(format!( text(format!(
"{}: {:.2} €", "{}: {:.2} €",
self.config.person_2, self.config.person_2,
self.earnings_2 - remaining_per_person self.edit.earnings_2 - remaining_per_person
)), )),
]; ];
for (account, amount) in &self.savings { for (account, amount) in &self.edit.savings {
same_remaining = same_remaining same_remaining = same_remaining
.push(text(account).size(TEXT_EMPH2)) .push(text(account).size(TEXT_EMPH2))
.push(text(format!( .push(text(format!(
@ -1017,7 +1026,7 @@ impl Application for Glaurung {
] ]
.align_items(Alignment::Start); .align_items(Alignment::Start);
let date = match self.date { let date = match self.edit.date {
Some(d) => d.to_string(), Some(d) => d.to_string(),
None => "No month set".to_string(), None => "No month set".to_string(),
}; };
@ -1056,7 +1065,7 @@ impl Application for Glaurung {
text(date).size(TEXT_H1), text(date).size(TEXT_H1),
text("Spendings").size(TEXT_H1), text("Spendings").size(TEXT_H1),
component(FixedAmounts { component(FixedAmounts {
items: &self.recurring, items: &self.edit.recurring,
title: "Recurring", title: "Recurring",
add_label: "Add a recurring spending", add_label: "Add a recurring spending",
on_add: Message::AddRecurring, on_add: Message::AddRecurring,
@ -1066,7 +1075,7 @@ impl Application for Glaurung {
rule::Appearance { width: 3, ..def } rule::Appearance { width: 3, ..def }
}), }),
component(VariableSpendings { component(VariableSpendings {
items: &self.variable, items: &self.edit.variable,
on_add: Message::AddVariable, on_add: Message::AddVariable,
on_expr_edit: Message::EditVariable, on_expr_edit: Message::EditVariable,
}), }),
@ -1079,7 +1088,7 @@ impl Application for Glaurung {
row![ row![
text(&self.config.person_1).size(TEXT_EMPH1), text(&self.config.person_1).size(TEXT_EMPH1),
component(ErrorEdit { component(ErrorEdit {
v: self.earnings_1.to_string(), v: self.edit.earnings_1.to_string(),
parse: |s: &str| -> Result<f64, _> { s.parse() }, parse: |s: &str| -> Result<f64, _> { s.parse() },
on_submit: Message::EditEarings1, on_submit: Message::EditEarings1,
}) })
@ -1088,7 +1097,7 @@ impl Application for Glaurung {
row![ row![
text(&self.config.person_2).size(TEXT_EMPH1), text(&self.config.person_2).size(TEXT_EMPH1),
component(ErrorEdit { component(ErrorEdit {
v: self.earnings_2.to_string(), v: self.edit.earnings_2.to_string(),
parse: |s: &str| -> Result<f64, _> { s.parse() }, parse: |s: &str| -> Result<f64, _> { s.parse() },
on_submit: Message::EditEarings2, on_submit: Message::EditEarings2,
}) })
@ -1098,7 +1107,7 @@ impl Application for Glaurung {
text("Outputs").size(TEXT_H1), text("Outputs").size(TEXT_H1),
text(&format!("Main account: {main_account}")).size(TEXT_EMPH2), text(&format!("Main account: {main_account}")).size(TEXT_EMPH2),
component(FixedAmounts { component(FixedAmounts {
items: &self.savings, items: &self.edit.savings,
title: "Savings", title: "Savings",
add_label: "Add a saving output", add_label: "Add a saving output",
on_add: Message::AddSaving, on_add: Message::AddSaving,