use std::fs;
use std::path::{Path, PathBuf};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use crate::aggregate::translation::translate::TranslatedTb;
use crate::errors::{GroupError, GroupResult};
pub const CONSOLIDATED_SUBDIR: &str = "consolidated";
pub const CTA_ROLLFORWARD_FILENAME: &str = "cta_rollforward.json";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CtaRollforward {
pub entity_code: String,
pub functional_currency: String,
pub presentation_currency: String,
pub opening_cta: Decimal,
pub period_cta: Decimal,
pub closing_cta: Decimal,
}
pub fn compute_cta(translated: &TranslatedTb) -> Decimal {
translated.total_translated_debits - translated.total_translated_credits
}
pub fn cta_rollforward(
entity_code: &str,
functional_currency: &str,
presentation_currency: &str,
opening_cta: Decimal,
period_cta: Decimal,
) -> CtaRollforward {
CtaRollforward {
entity_code: entity_code.to_string(),
functional_currency: functional_currency.to_string(),
presentation_currency: presentation_currency.to_string(),
opening_cta,
period_cta,
closing_cta: opening_cta + period_cta,
}
}
pub fn write_cta_rollforward(
rollforwards: &[CtaRollforward],
out_dir: &Path,
) -> GroupResult<PathBuf> {
let dir = out_dir.join(CONSOLIDATED_SUBDIR);
fs::create_dir_all(&dir).map_err(GroupError::Io)?;
let path = dir.join(CTA_ROLLFORWARD_FILENAME);
let mut json = serde_json::to_string_pretty(rollforwards)?;
json.push('\n');
fs::write(&path, json).map_err(GroupError::Io)?;
Ok(path)
}