1# -*- coding: utf-8 -*-
2# Part of Odoo. See LICENSE file for full copyright and licensing details.
3
4from odoo import api, fields, models, _
5from odoo.exceptions import UserError
6
7
8class AccountAnalyticAccount(models.Model):
9    _inherit = 'account.analytic.account'
10    _description = 'Analytic Account'
11
12    project_ids = fields.One2many('project.project', 'analytic_account_id', string='Projects')
13    project_count = fields.Integer("Project Count", compute='_compute_project_count')
14
15    @api.depends('project_ids')
16    def _compute_project_count(self):
17        project_data = self.env['project.project'].read_group([('analytic_account_id', 'in', self.ids)], ['analytic_account_id'], ['analytic_account_id'])
18        mapping = {m['analytic_account_id'][0]: m['analytic_account_id_count'] for m in project_data}
19        for account in self:
20            account.project_count = mapping.get(account.id, 0)
21
22    @api.constrains('company_id')
23    def _check_company_id(self):
24        for record in self:
25            if record.company_id and not all(record.company_id == c for c in record.project_ids.mapped('company_id')):
26                raise UserError(_('You cannot change the company of an analytical account if it is related to a project.'))
27
28    def unlink(self):
29        projects = self.env['project.project'].search([('analytic_account_id', 'in', self.ids)])
30        has_tasks = self.env['project.task'].search_count([('project_id', 'in', projects.ids)])
31        if has_tasks:
32            raise UserError(_('Please remove existing tasks in the project linked to the accounts you want to delete.'))
33        return super(AccountAnalyticAccount, self).unlink()
34
35    def action_view_projects(self):
36        kanban_view_id = self.env.ref('project.view_project_kanban').id
37        result = {
38            "type": "ir.actions.act_window",
39            "res_model": "project.project",
40            "views": [[kanban_view_id, "kanban"], [False, "form"]],
41            "domain": [['analytic_account_id', '=', self.id]],
42            "context": {"create": False},
43            "name": "Projects",
44        }
45        if len(self.project_ids) == 1:
46            result['views'] = [(False, "form")]
47            result['res_id'] = self.project_ids.id
48        return result
49