| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Part of Odoo. See LICENSE file for full copyright and licensing details. |
| 3 |
import re |
| 4 |
|
| 5 |
from collections import defaultdict |
| 6 |
|
| 7 |
from odoo import models, fields, api, _ |
| 8 |
from odoo.exceptions import UserError, RedirectWarning |
| 9 |
from odoo.tools import SQL |
| 10 |
from odoo.addons.rating.models.rating_data import OPERATOR_MAPPING |
| 11 |
|
| 12 |
|
| 13 |
PROJECT_TASK_READABLE_FIELDS = { |
| 14 |
'allow_timesheets', |
| 15 |
'analytic_account_active', |
| 16 |
'effective_hours', |
| 17 |
'encode_uom_in_days', |
| 18 |
'allocated_hours', |
| 19 |
'progress', |
| 20 |
'overtime', |
| 21 |
'remaining_hours', |
| 22 |
'subtask_effective_hours', |
| 23 |
'subtask_allocated_hours', |
| 24 |
'timesheet_ids', |
| 25 |
'total_hours_spent', |
| 26 |
} |
| 27 |
|
| 28 |
|
| 29 |
class ProjectTask(models.Model): |
| 30 |
_inherit = "project.task" |
| 31 |
|
| 32 |
project_id = fields.Many2one(domain="['|', ('company_id', '=', False), ('company_id', '=?', company_id), ('is_internal_project', '=', False), ('is_template', 'in', [is_template, False])]") |
| 33 |
analytic_account_active = fields.Boolean("Active Analytic Account", related='project_id.analytic_account_active', export_string_translation=False) |
| 34 |
allow_timesheets = fields.Boolean( |
| 35 |
"Allow timesheets", |
| 36 |
compute='_compute_allow_timesheets', search='_search_allow_timesheets', |
| 37 |
compute_sudo=True, readonly=True, export_string_translation=False) |
| 38 |
remaining_hours = fields.Float("Time Remaining", compute='_compute_remaining_hours', store=True, readonly=True, help="Number of allocated hours minus the number of hours spent.") |
| 39 |
remaining_hours_percentage = fields.Float(compute='_compute_remaining_hours_percentage', search='_search_remaining_hours_percentage', export_string_translation=False) |
| 40 |
effective_hours = fields.Float("Time Spent", compute='_compute_effective_hours', compute_sudo=True, store=True) |
| 41 |
total_hours_spent = fields.Float("Total Time Spent", compute='_compute_total_hours_spent', store=True, help="Time spent on this task and its sub-tasks (and their own sub-tasks).") |
| 42 |
progress = fields.Float("Progress", compute='_compute_progress_hours', store=True, aggregator="avg") |
| 43 |
overtime = fields.Float(compute='_compute_progress_hours', store=True) |
| 44 |
subtask_effective_hours = fields.Float("Time Spent on Sub-tasks", compute='_compute_subtask_effective_hours', recursive=True, store=True, help="Time spent on the sub-tasks (and their own sub-tasks) of this task.") |
| 45 |
timesheet_ids = fields.One2many('account.analytic.line', 'task_id', 'Timesheets', export_string_translation=False) |
| 46 |
encode_uom_in_days = fields.Boolean(compute='_compute_encode_uom_in_days', default=lambda self: self._uom_in_days(), export_string_translation=False) |
| 47 |
display_name = fields.Char(help="""Use these keywords in the title to set new tasks:\n |
| 48 |
30h Allocate 30 hours to the task |
| 49 |
#tags Set tags on the task |
| 50 |
@user Assign the task to a user |
| 51 |
! Set the task a medium priority |
| 52 |
!! Set the task a high priority |
| 53 |
!!! Set the task a urgent priority\n |
| 54 |
Make sure to use the right format and order e.g. Improve the configuration screen 5h #feature #v16 @Mitchell !""", |
| 55 |
) |
| 56 |
@property |
| 57 |
def TASK_PORTAL_READABLE_FIELDS(self): |
| 58 |
return super().TASK_PORTAL_READABLE_FIELDS | PROJECT_TASK_READABLE_FIELDS |
| 59 |
|
| 60 |
@api.constrains('project_id') |
| 61 |
def _check_project_root(self): |
| 62 |
private_tasks = self.filtered(lambda t: not t.project_id) |
| 63 |
if private_tasks and self.env['account.analytic.line'].sudo().search_count([('task_id', 'in', private_tasks.ids)], limit=1): |
| 64 |
raise UserError(_("This task cannot be private because there are some timesheets linked to it.")) |
| 65 |
|
| 66 |
def _uom_in_days(self): |
| 67 |
return self.env.company.timesheet_encode_uom_id == self.env.ref('uom.product_uom_day') |
| 68 |
|
| 69 |
def _compute_encode_uom_in_days(self): |
| 70 |
self.encode_uom_in_days = self._uom_in_days() |
| 71 |
|
| 72 |
@api.depends('project_id.allow_timesheets') |
| 73 |
def _compute_allow_timesheets(self): |
| 74 |
for task in self: |
| 75 |
task.allow_timesheets = task.project_id.allow_timesheets |
| 76 |
|
| 77 |
def _search_allow_timesheets(self, operator, value): |
| 78 |
query = self.env['project.project'].sudo()._search([ |
| 79 |
('allow_timesheets', operator, value), |
| 80 |
]) |
| 81 |
return [('project_id', 'in', query)] |
| 82 |
|
| 83 |
@api.depends('timesheet_ids.unit_amount') |
| 84 |
def _compute_effective_hours(self): |
| 85 |
if not any(self._ids): |
| 86 |
for task in self: |
| 87 |
task.effective_hours = sum(task.timesheet_ids.mapped('unit_amount')) |
| 88 |
return |
| 89 |
timesheet_read_group = self.env['account.analytic.line']._read_group([('task_id', 'in', self.ids)], ['task_id'], ['unit_amount:sum']) |
| 90 |
timesheets_per_task = {task.id: amount for task, amount in timesheet_read_group} |
| 91 |
for task in self: |
| 92 |
task.effective_hours = timesheets_per_task.get(task.id, 0.0) |
| 93 |
|
| 94 |
@api.depends('effective_hours', 'subtask_effective_hours', 'allocated_hours') |
| 95 |
def _compute_progress_hours(self): |
| 96 |
for task in self: |
| 97 |
if (task.allocated_hours > 0.0): |
| 98 |
task_total_hours = task.effective_hours + task.subtask_effective_hours |
| 99 |
task.overtime = max(task_total_hours - task.allocated_hours, 0) |
| 100 |
task.progress = round(task_total_hours / task.allocated_hours, 2) |
| 101 |
else: |
| 102 |
task.progress = 0.0 |
| 103 |
task.overtime = 0 |
| 104 |
|
| 105 |
@api.depends('allocated_hours', 'remaining_hours') |
| 106 |
def _compute_remaining_hours_percentage(self): |
| 107 |
for task in self: |
| 108 |
if task.allocated_hours > 0.0: |
| 109 |
task.remaining_hours_percentage = task.remaining_hours / task.allocated_hours |
| 110 |
else: |
| 111 |
task.remaining_hours_percentage = 0.0 |
| 112 |
|
| 113 |
def _search_remaining_hours_percentage(self, operator, value): |
| 114 |
if operator not in OPERATOR_MAPPING: |
| 115 |
return NotImplemented |
| 116 |
if operator in ('in', 'not in'): |
| 117 |
value = tuple(value) |
| 118 |
sql = SQL("""( |
| 119 |
SELECT id |
| 120 |
FROM %s |
| 121 |
WHERE remaining_hours > 0 |
| 122 |
AND allocated_hours > 0 |
| 123 |
AND remaining_hours / allocated_hours %s %s |
| 124 |
)""", SQL.identifier(self._table), SQL(operator), value) |
| 125 |
return [('id', 'in', sql)] |
| 126 |
|
| 127 |
@api.depends('effective_hours', 'subtask_effective_hours', 'allocated_hours') |
| 128 |
def _compute_remaining_hours(self): |
| 129 |
for task in self: |
| 130 |
if not task.allocated_hours: |
| 131 |
task.remaining_hours = 0.0 |
| 132 |
else: |
| 133 |
task.remaining_hours = task.allocated_hours - task.effective_hours - task.subtask_effective_hours |
| 134 |
|
| 135 |
@api.depends('effective_hours', 'subtask_effective_hours') |
| 136 |
def _compute_total_hours_spent(self): |
| 137 |
for task in self: |
| 138 |
task.total_hours_spent = task.effective_hours + task.subtask_effective_hours |
| 139 |
|
| 140 |
@api.depends('child_ids.effective_hours', 'child_ids.subtask_effective_hours') |
| 141 |
def _compute_subtask_effective_hours(self): |
| 142 |
for task in self.with_context(active_test=False): |
| 143 |
task.subtask_effective_hours = sum(child_task.effective_hours + child_task.subtask_effective_hours for child_task in task.child_ids) |
| 144 |
|
| 145 |
def _get_group_pattern(self): |
| 146 |
return { |
| 147 |
**super()._get_group_pattern(), |
| 148 |
'allocated_hours': r'\s(\d+(?:\.\d+)?)[hH]', |
| 149 |
} |
| 150 |
|
| 151 |
def _prepare_pattern_groups(self): |
| 152 |
return [self._get_group_pattern()['allocated_hours']] + super()._prepare_pattern_groups() |
| 153 |
|
| 154 |
def _get_cannot_start_with_patterns(self): |
| 155 |
return super()._get_cannot_start_with_patterns() + [r'(?!\d+(?:\.\d+)?(?:h|H))'] |
| 156 |
|
| 157 |
def _extract_allocated_hours(self): |
| 158 |
allocated_hours_group = self._get_group_pattern()['allocated_hours'] |
| 159 |
if self.allow_timesheets: |
| 160 |
self.allocated_hours = sum(float(num) for num in re.findall(allocated_hours_group, self.display_name)) |
| 161 |
self.display_name, dummy = re.subn(allocated_hours_group, '', self.display_name) |
| 162 |
|
| 163 |
def _get_groups(self): |
| 164 |
return [lambda task: task._extract_allocated_hours()] + super()._get_groups() |
| 165 |
|
| 166 |
def action_view_subtask_timesheet(self): |
| 167 |
self.ensure_one() |
| 168 |
is_internal_user = self.env.user.has_group('base.group_user') |
| 169 |
task_ids = self.with_context(active_test=False)._get_subtask_ids_per_task_id().get(self.id, []) |
| 170 |
action = self.env["ir.actions.actions"]._for_xml_id("hr_timesheet.timesheet_action_all") |
| 171 |
graph_view_id = self.env.ref("hr_timesheet.view_hr_timesheet_line_graph_by_employee").id |
| 172 |
new_views = [] |
| 173 |
for view in action['views']: |
| 174 |
if (not is_internal_user or self.env.context.get('is_project_sharing')) and view[1] not in ['tree', 'kanban', 'form']: |
| 175 |
continue |
| 176 |
if not is_internal_user: |
| 177 |
if view[1] == 'list': |
| 178 |
tree_view_id = self.env['ir.model.data']._xmlid_to_res_id('hr_timesheet.hr_timesheet_line_portal_tree') |
| 179 |
if tree_view_id: |
| 180 |
new_views.insert(0, (tree_view_id, 'list')) |
| 181 |
continue |
| 182 |
elif view[1] == 'form': |
| 183 |
form_view_id = self.env['ir.model.data']._xmlid_to_res_id('hr_timesheet.timesheet_view_form_portal_user') |
| 184 |
if form_view_id: |
| 185 |
new_views.append((form_view_id, 'form')) |
| 186 |
continue |
| 187 |
elif view[1] == 'kanban': |
| 188 |
kanban_view_id = self.env['ir.model.data']._xmlid_to_res_id('hr_timesheet.view_kanban_account_analytic_line_portal_user') |
| 189 |
if kanban_view_id: |
| 190 |
new_views.append((kanban_view_id, 'kanban')) |
| 191 |
continue |
| 192 |
if view[1] == 'graph': |
| 193 |
view = (graph_view_id, 'graph') |
| 194 |
new_views.insert(0, view) if view[1] == 'list' else new_views.append(view) |
| 195 |
|
| 196 |
action.update({ |
| 197 |
'display_name': _('Timesheets'), |
| 198 |
'context': {'default_project_id': self.project_id.id}, |
| 199 |
'domain': [('project_id', '!=', False), ('task_id', 'in', task_ids)], |
| 200 |
'views': new_views, |
| 201 |
}) |
| 202 |
return action |
| 203 |
|
| 204 |
def _get_timesheet(self): |
| 205 |
# Is override in sale_timesheet |
| 206 |
return self.timesheet_ids |
| 207 |
|
| 208 |
def _get_timesheet_report_data(self): |
| 209 |
subtasks = self._get_all_subtasks() |
| 210 |
timesheets_read_group = self.env['account.analytic.line']._read_group( |
| 211 |
[('task_id', 'in', (self | subtasks).ids)], |
| 212 |
['task_id'], |
| 213 |
['id:recordset'], |
| 214 |
) |
| 215 |
timesheets_per_task = dict(timesheets_read_group) |
| 216 |
subtask_ids_per_task_id = defaultdict(list) |
| 217 |
for subtask in subtasks: |
| 218 |
subtask_ids_per_task_id[subtask.parent_id.id].append(subtask.id) |
| 219 |
return { |
| 220 |
'subtask_ids_per_task_id': subtask_ids_per_task_id, |
| 221 |
'timesheets_per_task': timesheets_per_task, |
| 222 |
} |
| 223 |
|
| 224 |
@api.depends_context('hr_timesheet_display_remaining_hours') |
| 225 |
def _compute_display_name(self): |
| 226 |
super()._compute_display_name() |
| 227 |
if self.env.context.get('hr_timesheet_display_remaining_hours'): |
| 228 |
for task in self: |
| 229 |
if task.allow_timesheets and task.allocated_hours > 0 and task.encode_uom_in_days: |
| 230 |
days_left = _("(%s days remaining)", task._convert_hours_to_days(task.remaining_hours)) |
| 231 |
task.display_name = task.display_name + "\u00A0" + days_left |
| 232 |
elif task.allow_timesheets and task.allocated_hours > 0: |
| 233 |
hours, mins = (str(int(duration)).rjust(2, '0') for duration in divmod(abs(task.remaining_hours) * 60, 60)) |
| 234 |
hours_left = _( |
| 235 |
"(%(sign)s%(hours)s:%(minutes)s remaining)", |
| 236 |
sign='-' if task.remaining_hours < 0 else '', |
| 237 |
hours=hours, |
| 238 |
minutes=mins, |
| 239 |
) |
| 240 |
task.display_name = task.display_name + "\u00A0" + hours_left |
| 241 |
|
| 242 |
@api.ondelete(at_uninstall=False) |
| 243 |
def _unlink_except_contains_entries(self): |
| 244 |
""" |
| 245 |
If some tasks to unlink have some timesheets entries, these |
| 246 |
timesheets entries must be unlinked first. |
| 247 |
In this case, a warning message is displayed through a RedirectWarning |
| 248 |
and allows the user to see timesheets entries to unlink. |
| 249 |
""" |
| 250 |
timesheet_data = self.env['account.analytic.line'].sudo()._read_group( |
| 251 |
[('task_id', 'in', self.ids)], |
| 252 |
['task_id'], |
| 253 |
) |
| 254 |
task_with_timesheets_ids = [task.id for task, in timesheet_data] |
| 255 |
if not task_with_timesheets_ids: |
| 256 |
return |
| 257 |
# Fetch task IDs with timesheets that the user has read access. |
| 258 |
inaccessible_task_ids = set(task_with_timesheets_ids) - set( |
| 259 |
self.env['account.analytic.line'].search([ |
| 260 |
('task_id', 'in', task_with_timesheets_ids) |
| 261 |
]).mapped('task_id.id') |
| 262 |
) |
| 263 |
if inaccessible_task_ids: |
| 264 |
raise UserError( |
| 265 |
_("This task can’t be deleted because it’s linked to timesheets. Please contact someone with higher access to remove the timesheets first, " |
| 266 |
"and then you’ll be able to delete the task.") |
| 267 |
) |
| 268 |
if len(task_with_timesheets_ids) > 1: |
| 269 |
warning_msg = _("Some timesheet entries are weighing down these tasks! Remove them first, then you’ll be able to delete the tasks!") |
| 270 |
else: |
| 271 |
warning_msg = _("Some timesheet entries are weighing down these tasks! Remove them first, then you’ll be able to delete the tasks!") |
| 272 |
raise RedirectWarning( |
| 273 |
warning_msg, self.env.ref('hr_timesheet.timesheet_action_task').id, |
| 274 |
_('See timesheet entries'), {'active_ids': task_with_timesheets_ids}) |
| 275 |
|
| 276 |
@api.model |
| 277 |
def _convert_hours_to_days(self, time): |
| 278 |
uom_hour = self.env.ref('uom.product_uom_hour') |
| 279 |
uom_day = self.env.ref('uom.product_uom_day') |
| 280 |
return round(uom_hour._compute_quantity(time, uom_day, raise_if_failure=False), 2) |
| 281 |
|
| 282 |
def _get_portal_total_hours_dict(self): |
| 283 |
if not (timesheetable_tasks := self.filtered('allow_timesheets')): |
| 284 |
return {} |
| 285 |
return { |
| 286 |
'allocated_hours': sum(timesheetable_tasks.mapped('allocated_hours')), |
| 287 |
'effective_hours': sum(timesheetable_tasks.mapped('effective_hours')), |
| 288 |
} |