use crate::state::State;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountingState {
pub last_settlement_day: u32,
}
impl State for AccountingState {}
impl AccountingState {
pub fn new() -> Self {
Self {
last_settlement_day: 0,
}
}
pub fn should_run_settlement(&self, current_day: u32, period: u32) -> bool {
if !current_day.is_multiple_of(period) {
return false;
}
self.last_settlement_day != current_day
}
pub fn record_settlement(&mut self, day: u32) {
self.last_settlement_day = day;
}
pub fn clear(&mut self) {
self.last_settlement_day = 0;
}
}
impl Default for AccountingState {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_state_new() {
let state = AccountingState::new();
assert_eq!(state.last_settlement_day, 0);
}
#[test]
fn test_should_run_settlement() {
let state = AccountingState::new();
assert!(state.should_run_settlement(7, 7));
assert!(state.should_run_settlement(14, 7));
assert!(!state.should_run_settlement(5, 7));
}
#[test]
fn test_prevent_duplicate_settlement() {
let mut state = AccountingState::new();
assert!(state.should_run_settlement(7, 7));
state.record_settlement(7);
assert!(!state.should_run_settlement(7, 7));
assert!(state.should_run_settlement(14, 7));
}
#[test]
fn test_clear() {
let mut state = AccountingState::new();
state.record_settlement(7);
state.clear();
assert_eq!(state.last_settlement_day, 0);
}
}