# Fusion Accounting - Digest KPI Extensions
# Adds bank & cash movement KPIs to the periodic digest emails

from odoo import fields, models, _
from odoo.exceptions import AccessError


class FusionDigest(models.Model):
    """Extends the digest framework with an accounting KPI that
    summarises bank and cash journal movements."""

    _inherit = 'digest.digest'

    kpi_account_bank_cash = fields.Boolean(string='Bank & Cash Moves')
    kpi_account_bank_cash_value = fields.Monetary(
        compute='_compute_bank_cash_kpi_total',
    )

    def _compute_bank_cash_kpi_total(self):
        """Aggregate the total amount of moves posted in bank and cash
        journals during the digest period."""
        if not self.env.user.has_group('account.group_account_user'):
            raise AccessError(
                _("Insufficient permissions to compute accounting KPIs.")
            )

        period_start, period_end, target_companies = self._get_kpi_compute_parameters()
        aggregated = self.env['account.move']._read_group(
            domain=[
                ('date', '>=', period_start),
                ('date', '<', period_end),
                ('journal_id.type', 'in', ('cash', 'bank')),
                ('company_id', 'in', target_companies.ids),
            ],
            groupby=['company_id'],
            aggregates=['amount_total:sum'],
        )
        totals_by_company = dict(aggregated)

        for rec in self:
            co = rec.company_id or self.env.company
            rec.kpi_account_bank_cash_value = totals_by_company.get(co)

    def _compute_kpis_actions(self, company, user):
        """Map the bank/cash KPI to the journal dashboard action."""
        actions = super(FusionDigest, self)._compute_kpis_actions(company, user)
        finance_menu_id = self.env.ref('account.menu_finance').id
        actions['kpi_account_bank_cash'] = (
            f'account.open_account_journal_dashboard_kanban&menu_id={finance_menu_id}'
        )
        return actions
