| 1 |
# Part of Odoo. See LICENSE file for full copyright and licensing details. |
| 2 |
|
| 3 |
from collections import defaultdict |
| 4 |
from datetime import datetime, time |
| 5 |
from statistics import mode |
| 6 |
import re |
| 7 |
|
| 8 |
import pytz |
| 9 |
|
| 10 |
from odoo import api, fields, models |
| 11 |
from odoo.exceptions import UserError, AccessError, ValidationError |
| 12 |
from odoo.fields import Domain |
| 13 |
from odoo.tools.translate import _ |
| 14 |
|
| 15 |
|
| 16 |
class AccountAnalyticLine(models.Model): |
| 17 |
_inherit = 'account.analytic.line' |
| 18 |
|
| 19 |
def _get_favorite_project_id_domain(self, employee_id=False): |
| 20 |
employee_id = employee_id or self.env.user.employee_id.id |
| 21 |
return [ |
| 22 |
('employee_id', '=', employee_id), |
| 23 |
('project_id', '!=', False), |
| 24 |
('project_id.active', '=', True), |
| 25 |
('project_id.allow_timesheets', '=', True) |
| 26 |
] |
| 27 |
|
| 28 |
@api.model |
| 29 |
def _get_favorite_project_id(self, employee_id=False): |
| 30 |
last_timesheets = self.search_fetch( |
| 31 |
self._get_favorite_project_id_domain(employee_id), ['project_id'], limit=5 |
| 32 |
) |
| 33 |
if not last_timesheets: |
| 34 |
internal_project = self.env.company.internal_project_id |
| 35 |
return internal_project.has_access('read') and internal_project.active and internal_project.allow_timesheets and internal_project.id |
| 36 |
return mode([t.project_id.id for t in last_timesheets]) |
| 37 |
|
| 38 |
@api.model |
| 39 |
def default_get(self, fields): |
| 40 |
result = super().default_get(fields) |
| 41 |
if not self.env.context.get('default_employee_id') and 'employee_id' in fields and result.get('user_id'): |
| 42 |
result['employee_id'] = self.env['hr.employee'].search([('user_id', '=', result['user_id']), ('company_id', '=', result.get('company_id', self.env.company.id))], limit=1).id |
| 43 |
if not self.env.context.get('default_project_id') and self.env.context.get('is_timesheet'): |
| 44 |
employee_id = result.get('employee_id', self.env.context.get('default_employee_id', False)) |
| 45 |
favorite_project_id = self._get_favorite_project_id(employee_id) |
| 46 |
if favorite_project_id: |
| 47 |
result['project_id'] = favorite_project_id |
| 48 |
return result |
| 49 |
|
| 50 |
def _domain_project_id(self): |
| 51 |
domain = Domain([('allow_timesheets', '=', True), ('is_template', '=', False)]) |
| 52 |
if not self.env.user.has_group('hr_timesheet.group_timesheet_manager'): |
| 53 |
domain &= Domain('privacy_visibility', 'in', ['employees', 'portal']) | Domain('message_partner_ids', 'in', [self.env.user.partner_id.id]) |
| 54 |
return domain |
| 55 |
|
| 56 |
def _domain_employee_id(self): |
| 57 |
domain = Domain('company_id', 'in', self.env.context.get('allowed_company_ids')) |
| 58 |
if not self.env.user.has_group('hr_timesheet.group_hr_timesheet_approver'): |
| 59 |
domain &= Domain('user_id', '=', self.env.user.id) |
| 60 |
return domain |
| 61 |
|
| 62 |
task_id = fields.Many2one( |
| 63 |
'project.task', 'Task', index='btree_not_null', |
| 64 |
compute='_compute_task_id', store=True, readonly=False, |
| 65 |
domain="[('allow_timesheets', '=', True), ('project_id', '=?', project_id), ('has_template_ancestor', '=', False)]") |
| 66 |
parent_task_id = fields.Many2one('project.task', related='task_id.parent_id', store=True, index='btree_not_null') |
| 67 |
project_id = fields.Many2one( |
| 68 |
'project.project', 'Project', domain=_domain_project_id, index=True, |
| 69 |
compute='_compute_project_id', store=True, readonly=False) |
| 70 |
user_id = fields.Many2one(compute='_compute_user_id', store=True, readonly=False) |
| 71 |
employee_id = fields.Many2one('hr.employee', "Employee", domain=_domain_employee_id, context={'active_test': False}, |
| 72 |
index=True, help="Define an 'hourly cost' on the employee to track the cost of their time.") |
| 73 |
job_title = fields.Char(related='employee_id.job_title', export_string_translation=False) |
| 74 |
department_id = fields.Many2one('hr.department', "Department", compute='_compute_department_id', store=True, compute_sudo=True) |
| 75 |
manager_id = fields.Many2one('hr.employee', "Manager", related='employee_id.parent_id', store=True) |
| 76 |
encoding_uom_id = fields.Many2one('uom.uom', compute='_compute_encoding_uom_id', export_string_translation=False) |
| 77 |
partner_id = fields.Many2one(compute='_compute_partner_id', store=True, readonly=False) |
| 78 |
readonly_timesheet = fields.Boolean(compute="_compute_readonly_timesheet", compute_sudo=True, export_string_translation=False) |
| 79 |
milestone_id = fields.Many2one('project.milestone', related='task_id.milestone_id') |
| 80 |
message_partner_ids = fields.Many2many('res.partner', compute='_compute_message_partner_ids', search='_search_message_partner_ids') |
| 81 |
calendar_display_name = fields.Char(compute="_compute_calendar_display_name", export_string_translation=False) |
| 82 |
|
| 83 |
def _search_message_partner_ids(self, operator, value): |
| 84 |
followed_ids_by_model = dict(self.env['mail.followers']._read_group([ |
| 85 |
('partner_id', operator, value), |
| 86 |
('res_model', 'in', ('project.project', 'project.task')), |
| 87 |
], ['res_model'], ['res_id:array_agg'])) |
| 88 |
if not followed_ids_by_model: |
| 89 |
return Domain.FALSE |
| 90 |
domain = Domain.FALSE |
| 91 |
if project_ids := followed_ids_by_model.get('project.project'): |
| 92 |
domain |= Domain('project_id', 'in', project_ids) |
| 93 |
if task_ids := followed_ids_by_model.get('project.task'): |
| 94 |
domain |= Domain('task_id', 'in', task_ids) |
| 95 |
return domain |
| 96 |
|
| 97 |
@api.depends('project_id.message_partner_ids', 'task_id.message_partner_ids') |
| 98 |
def _compute_message_partner_ids(self): |
| 99 |
for line in self: |
| 100 |
line.message_partner_ids = line.task_id.message_partner_ids | line.project_id.message_partner_ids |
| 101 |
|
| 102 |
@api.depends('project_id', 'task_id') |
| 103 |
def _compute_display_name(self): |
| 104 |
analytic_line_with_project = self.filtered('project_id') |
| 105 |
super(AccountAnalyticLine, self - analytic_line_with_project)._compute_display_name() |
| 106 |
for analytic_line in analytic_line_with_project: |
| 107 |
if analytic_line.task_id: |
| 108 |
analytic_line.display_name = f"{analytic_line.project_id.sudo().display_name} - {analytic_line.task_id.sudo().display_name}" |
| 109 |
else: |
| 110 |
analytic_line.display_name = analytic_line.project_id.display_name |
| 111 |
|
| 112 |
def _is_readonly(self): |
| 113 |
self.ensure_one() |
| 114 |
# is overridden in other timesheet related modules |
| 115 |
return False |
| 116 |
|
| 117 |
def _compute_readonly_timesheet(self): |
| 118 |
# Since the mrp_module gives write access to portal user on timesheet, we check that the user is an internal one before giving the write access. |
| 119 |
# It is not supposed to be needed, since portal user are not supposed to have access to the views using this field, but better be safe than sorry |
| 120 |
if not self.env.user.has_group('base.group_user'): |
| 121 |
self.readonly_timesheet = True |
| 122 |
else: |
| 123 |
readonly_timesheets = self.filtered(lambda timesheet: timesheet._is_readonly()) |
| 124 |
readonly_timesheets.readonly_timesheet = True |
| 125 |
(self - readonly_timesheets).readonly_timesheet = False |
| 126 |
|
| 127 |
def _compute_encoding_uom_id(self): |
| 128 |
for analytic_line in self: |
| 129 |
analytic_line.encoding_uom_id = analytic_line.company_id.timesheet_encode_uom_id |
| 130 |
|
| 131 |
@api.depends('task_id.partner_id', 'project_id.partner_id') |
| 132 |
def _compute_partner_id(self): |
| 133 |
super()._compute_partner_id() |
| 134 |
for timesheet in self: |
| 135 |
if timesheet.project_id: |
| 136 |
timesheet.partner_id = timesheet.task_id.partner_id or timesheet.project_id.partner_id |
| 137 |
|
| 138 |
@api.depends('task_id.project_id') |
| 139 |
def _compute_project_id(self): |
| 140 |
for line in self: |
| 141 |
if not line.task_id.project_id or line.project_id == line.task_id.project_id: |
| 142 |
continue |
| 143 |
line.project_id = line.task_id.project_id |
| 144 |
|
| 145 |
@api.depends('project_id') |
| 146 |
def _compute_task_id(self): |
| 147 |
self.filtered(lambda t: not t.project_id).task_id = False |
| 148 |
|
| 149 |
@api.onchange('project_id') |
| 150 |
def _onchange_project_id(self): |
| 151 |
# TODO KBA in master - check to do it "properly", currently: |
| 152 |
# This onchange is used to reset the task_id when the project changes. |
| 153 |
# Doing it in the compute will remove the task_id when the project of a task changes. |
| 154 |
if self.project_id != self.task_id.project_id: |
| 155 |
self.task_id = False |
| 156 |
|
| 157 |
@api.depends('employee_id.user_id') |
| 158 |
def _compute_user_id(self): |
| 159 |
for line in self: |
| 160 |
line.user_id = line.employee_id.user_id if line.employee_id else self._default_user() |
| 161 |
|
| 162 |
@api.depends('employee_id') |
| 163 |
def _compute_department_id(self): |
| 164 |
for line in self: |
| 165 |
line.department_id = line.employee_id.department_id |
| 166 |
|
| 167 |
def _compute_calendar_display_name(self): |
| 168 |
companies = self.company_id |
| 169 |
encoding_in_days_per_company = dict(zip(companies, [company.timesheet_encode_uom_id == self.env.ref('uom.product_uom_day') for company in companies])) |
| 170 |
for line in self: |
| 171 |
if not line.project_id: |
| 172 |
line.calendar_display_name = "" |
| 173 |
continue |
| 174 |
if encoding_in_days_per_company[line.company_id]: |
| 175 |
days = line._get_timesheet_time_day() |
| 176 |
if days == int(days): |
| 177 |
days = int(days) |
| 178 |
line.calendar_display_name = self.env._( |
| 179 |
"%(project_name)s (%(days)sd)", |
| 180 |
project_name=line.project_id.display_name, |
| 181 |
days=days, |
| 182 |
) |
| 183 |
else: |
| 184 |
minutes = round(line.unit_amount * 60) |
| 185 |
hours, minutes = divmod(minutes, 60) |
| 186 |
if minutes: |
| 187 |
line.calendar_display_name = self.env._( |
| 188 |
"%(project_name)s (%(hours)sh%(minutes)s)", |
| 189 |
project_name=line.project_id.display_name, |
| 190 |
hours=hours, |
| 191 |
minutes=minutes, |
| 192 |
) |
| 193 |
else: |
| 194 |
line.calendar_display_name = self.env._( |
| 195 |
"%(project_name)s (%(hours)sh)", |
| 196 |
project_name=line.project_id.display_name, |
| 197 |
hours=hours, |
| 198 |
) |
| 199 |
|
| 200 |
def _check_can_write(self, values): |
| 201 |
# If it's a basic user then check if the timesheet is his own. |
| 202 |
if ( |
| 203 |
not (self.env.user.has_group('hr_timesheet.group_hr_timesheet_approver') or self.env.su) |
| 204 |
and any(analytic_line.user_id != self.env.user for analytic_line in self) |
| 205 |
): |
| 206 |
raise AccessError(_("You cannot access timesheets that are not yours.")) |
| 207 |
|
| 208 |
def _check_can_create(self): |
| 209 |
# override in other modules to check current user has create access |
| 210 |
pass |
| 211 |
|
| 212 |
@api.model_create_multi |
| 213 |
def create(self, vals_list): |
| 214 |
user_timezone = self.env.tz |
| 215 |
# Before creating a timesheet, we need to put a valid employee_id in the vals |
| 216 |
default_user_id = self._default_user() |
| 217 |
user_ids = [] |
| 218 |
employee_ids = [] |
| 219 |
# If batch creating from the calendar view, prefetch all employees to avoid fetching them one by one in the loop |
| 220 |
if self.env.context.get('timesheet_calendar'): |
| 221 |
self.env['hr.employee'].browse([vals.get('employee_id') for vals in vals_list]) |
| 222 |
# 1/ Collect the user_ids and employee_ids from each timesheet vals |
| 223 |
skipped_vals = 0 |
| 224 |
valid_vals = 0 |
| 225 |
for vals in vals_list[:]: |
| 226 |
if self.env.context.get('timesheet_calendar'): |
| 227 |
if not 'employee_id' in vals: |
| 228 |
vals['employee_id'] = self.env.user.employee_id.id |
| 229 |
employee = self.env['hr.employee'].browse(vals['employee_id']) |
| 230 |
date = fields.Date.from_string(vals.get('date', fields.Date.to_string(fields.Date.context_today(self)))) |
| 231 |
if not any(employee.resource_id._get_valid_work_intervals( |
| 232 |
datetime.combine(date, time.min, tzinfo=user_timezone), |
| 233 |
datetime.combine(date, time.max, tzinfo=user_timezone), |
| 234 |
)[0][employee.resource_id.id]): |
| 235 |
vals_list.remove(vals) |
| 236 |
skipped_vals += 1 |
| 237 |
continue |
| 238 |
task = self.env['project.task'].sudo().browse(vals.get('task_id')) |
| 239 |
project = self.env['project.project'].sudo().browse(vals.get('project_id')) |
| 240 |
if not (task or project): |
| 241 |
# It is not a timesheet |
| 242 |
continue |
| 243 |
elif task: |
| 244 |
if not task.project_id: |
| 245 |
raise ValidationError(_('Timesheets cannot be created on a private task.')) |
| 246 |
if not project: |
| 247 |
vals['project_id'] = task.project_id.id |
| 248 |
|
| 249 |
company = task.company_id or project.company_id or self.env['res.company'].browse(vals.get('company_id')) |
| 250 |
vals['company_id'] = company.id |
| 251 |
vals.update({ |
| 252 |
fname: account_id |
| 253 |
for fname, account_id in self._timesheet_preprocess_get_accounts(vals).items() |
| 254 |
if fname not in vals |
| 255 |
}) |
| 256 |
|
| 257 |
if not vals.get('product_uom_id'): |
| 258 |
vals['product_uom_id'] = company.project_time_mode_id.id |
| 259 |
|
| 260 |
if not vals.get('name'): |
| 261 |
vals['name'] = '/' |
| 262 |
employee_id = vals.get('employee_id', self.env.context.get('default_employee_id', False)) |
| 263 |
if employee_id and employee_id not in employee_ids: |
| 264 |
employee_ids.append(employee_id) |
| 265 |
else: |
| 266 |
user_id = vals.get('user_id', default_user_id) |
| 267 |
if user_id not in user_ids: |
| 268 |
user_ids.append(user_id) |
| 269 |
valid_vals += 1 |
| 270 |
|
| 271 |
# 2/ Search all employees related to user_ids and employee_ids, in the selected companies |
| 272 |
HrEmployee_sudo = self.env['hr.employee'].sudo() |
| 273 |
employees = HrEmployee_sudo.search([ |
| 274 |
'&', '|', ('user_id', 'in', user_ids), ('id', 'in', employee_ids), ('company_id', 'in', self.env.companies.ids) |
| 275 |
]) |
| 276 |
|
| 277 |
# ┌───── in search results = active/in companies ────────> was found with... ─── employee_id ───> (A) There is nothing to do, we will use this employee_id |
| 278 |
# 3/ Each employee └──── user_id ──────> (B)** We'll need to select the right employee for this user |
| 279 |
# └─ not in search results = archived/not in companies ──> (C) We raise an error as we can't create a timesheet for an archived employee |
| 280 |
# ** We can rely on the user to get the employee_id if |
| 281 |
# he has an active employee in the company of the timesheet |
| 282 |
# or he has only one active employee for all selected companies |
| 283 |
valid_employee_per_id = {} |
| 284 |
employee_id_per_company_per_user = defaultdict(dict) |
| 285 |
for employee in employees: |
| 286 |
if employee.id in employee_ids: |
| 287 |
valid_employee_per_id[employee.id] = employee |
| 288 |
else: |
| 289 |
employee_id_per_company_per_user[employee.user_id.id][employee.company_id.id] = employee.id |
| 290 |
|
| 291 |
# 4/ Put valid employee_id in each vals |
| 292 |
error_msg = _('Timesheets must be created with an active employee in the selected companies.') |
| 293 |
for vals in vals_list: |
| 294 |
if not vals.get('project_id'): |
| 295 |
continue |
| 296 |
employee_in_id = vals.get('employee_id', self.env.context.get('default_employee_id', False)) |
| 297 |
if employee_in_id: |
| 298 |
company = False |
| 299 |
if not vals.get('company_id'): |
| 300 |
company = HrEmployee_sudo.browse(employee_in_id).company_id |
| 301 |
vals['company_id'] = company.id |
| 302 |
if not vals.get('product_uom_id'): |
| 303 |
vals['product_uom_id'] = company.project_time_mode_id.id if company else self.env['res.company'].browse(vals.get('company_id', self.env.company.id)).project_time_mode_id.id |
| 304 |
if employee_in_id in valid_employee_per_id: |
| 305 |
vals['user_id'] = valid_employee_per_id[employee_in_id].sudo().user_id.id # (A) OK |
| 306 |
continue |
| 307 |
else: |
| 308 |
raise ValidationError(error_msg) # (C) KO |
| 309 |
else: |
| 310 |
user_id = vals.get('user_id', default_user_id) # (B)... |
| 311 |
|
| 312 |
# ...Look for an employee, with ** conditions |
| 313 |
employee_per_company = employee_id_per_company_per_user.get(user_id) |
| 314 |
employee_out_id = False |
| 315 |
if employee_per_company: |
| 316 |
company_id = list(employee_per_company)[0] if len(employee_per_company) == 1\ |
| 317 |
else vals.get('company_id') or self.env.company.id |
| 318 |
employee_out_id = employee_per_company.get(company_id, False) |
| 319 |
|
| 320 |
if employee_out_id: |
| 321 |
vals['employee_id'] = employee_out_id |
| 322 |
vals['user_id'] = user_id |
| 323 |
company = False |
| 324 |
if not vals.get('company_id'): |
| 325 |
company = HrEmployee_sudo.browse(employee_out_id).company_id |
| 326 |
vals['company_id'] = company.id |
| 327 |
if not vals.get('product_uom_id'): |
| 328 |
vals['product_uom_id'] = company.project_time_mode_id.id if company else self.env['res.company'].browse(vals.get('company_id', self.env.company.id)).project_time_mode_id.id |
| 329 |
else: # ...and raise an error if they fail |
| 330 |
raise ValidationError(error_msg) |
| 331 |
|
| 332 |
# 5/ Finally, create the timesheets |
| 333 |
lines = super().create(vals_list) |
| 334 |
lines._check_can_create() |
| 335 |
for line, values in zip(lines, vals_list): |
| 336 |
if line.project_id: # applied only for timesheet |
| 337 |
line._timesheet_postprocess(values) |
| 338 |
|
| 339 |
if self.env.context.get('timesheet_calendar'): |
| 340 |
if skipped_vals: |
| 341 |
type = "danger" |
| 342 |
if valid_vals: |
| 343 |
message = self.env._("Some timesheets were not created: employees aren’t working on the selected days") |
| 344 |
else: |
| 345 |
message = self.env._("No timesheets created: employees aren’t working on the selected days") |
| 346 |
else: |
| 347 |
type = "success" |
| 348 |
message = self.env._("Timesheets successfully created") |
| 349 |
|
| 350 |
self.env.user._bus_send('simple_notification', { |
| 351 |
"type": type, |
| 352 |
"message": message, |
| 353 |
}) |
| 354 |
|
| 355 |
return lines |
| 356 |
|
| 357 |
def write(self, vals): |
| 358 |
values = vals |
| 359 |
self._check_can_write(values) |
| 360 |
|
| 361 |
task = self.env['project.task'].sudo().browse(values.get('task_id')) |
| 362 |
project = self.env['project.project'].sudo().browse(values.get('project_id')) |
| 363 |
if task and not task.project_id: |
| 364 |
raise ValidationError(_('Timesheets cannot be created on a private task.')) |
| 365 |
if project or task: |
| 366 |
values['company_id'] = task.company_id.id or project.company_id.id |
| 367 |
values.update({ |
| 368 |
fname: account_id |
| 369 |
for fname, account_id in self._timesheet_preprocess_get_accounts(values).items() |
| 370 |
if fname not in values |
| 371 |
}) |
| 372 |
|
| 373 |
if values.get('employee_id'): |
| 374 |
employee = self.env['hr.employee'].browse(values['employee_id']) |
| 375 |
if not employee.active: |
| 376 |
raise UserError(_('You cannot set an archived employee on existing timesheets.')) |
| 377 |
if 'name' in values and not values.get('name'): |
| 378 |
values['name'] = '/' |
| 379 |
if 'company_id' in values and not values.get('company_id'): |
| 380 |
del values['company_id'] |
| 381 |
result = super().write(values) |
| 382 |
# applied only for timesheet |
| 383 |
self.filtered(lambda t: t.project_id)._timesheet_postprocess(values) |
| 384 |
return result |
| 385 |
|
| 386 |
@api.model |
| 387 |
def get_views(self, views, options=None): |
| 388 |
res = super().get_views(views, options) |
| 389 |
if options and options.get('toolbar'): |
| 390 |
wip_report_id = None |
| 391 |
|
| 392 |
def get_wip_report_id(): |
| 393 |
return self.env['ir.model.data']._xmlid_to_res_id("mrp_account.wip_report", raise_if_not_found=False) |
| 394 |
|
| 395 |
for view_data in res['views'].values(): |
| 396 |
print_data_list = view_data.get('toolbar', {}).get('print') |
| 397 |
if print_data_list: |
| 398 |
if wip_report_id is None and re.search(r'widget="timesheet_uom(\w)*"', view_data['arch']): |
| 399 |
wip_report_id = get_wip_report_id() |
| 400 |
if wip_report_id: |
| 401 |
view_data['toolbar']['print'] = [print_data for print_data in print_data_list if print_data['id'] != wip_report_id] |
| 402 |
return res |
| 403 |
|
| 404 |
def _timesheet_get_portal_domain(self): |
| 405 |
if self.env.user.has_group('hr_timesheet.group_hr_timesheet_user'): |
| 406 |
# Then, he is internal user, and we take the domain for this current user |
| 407 |
return self.env['ir.rule']._compute_domain(self._name) |
| 408 |
return ( |
| 409 |
( |
| 410 |
Domain('message_partner_ids', 'child_of', [self.env.user.partner_id.commercial_partner_id.id]) |
| 411 |
| Domain('partner_id', 'child_of', [self.env.user.partner_id.commercial_partner_id.id]) |
| 412 |
) |
| 413 |
& Domain('project_id.privacy_visibility', 'in', ['invited_users', 'portal']) |
| 414 |
) |
| 415 |
|
| 416 |
def _timesheet_preprocess_get_accounts(self, vals): |
| 417 |
project = self.env['project.project'].sudo().browse(vals.get('project_id')) |
| 418 |
if not project: |
| 419 |
return {} |
| 420 |
company = self.env['res.company'].browse(vals.get('company_id')) |
| 421 |
mandatory_plans = [plan for plan in self._get_mandatory_plans(company, business_domain='timesheet') if plan['column_name'] != 'account_id'] |
| 422 |
missing_plan_names = [plan['name'] for plan in mandatory_plans if not project[plan['column_name']]] |
| 423 |
if missing_plan_names: |
| 424 |
raise ValidationError(_( |
| 425 |
"'%(missing_plan_names)s' analytic plan(s) required on the project '%(project_name)s' linked to the timesheet.", |
| 426 |
missing_plan_names=missing_plan_names, |
| 427 |
project_name=project.name, |
| 428 |
)) |
| 429 |
return { |
| 430 |
fname: project[fname].id |
| 431 |
for fname in self._get_plan_fnames() |
| 432 |
} |
| 433 |
|
| 434 |
def _timesheet_postprocess(self, values): |
| 435 |
""" Hook to update record one by one according to the values of a `write` or a `create`. """ |
| 436 |
sudo_self = self.sudo() # this creates only one env for all operation that required sudo() in `_timesheet_postprocess_values`override |
| 437 |
values_to_write = self._timesheet_postprocess_values(values) |
| 438 |
for timesheet in sudo_self: |
| 439 |
if values_to_write[timesheet.id]: |
| 440 |
timesheet.write(values_to_write[timesheet.id]) |
| 441 |
return values |
| 442 |
|
| 443 |
def _timesheet_postprocess_values(self, values): |
| 444 |
""" Get the addionnal values to write on record |
| 445 |
:param dict values: values for the model's fields, as a dictionary:: |
| 446 |
{'field_name': field_value, ...} |
| 447 |
:return: a dictionary mapping each record id to its corresponding |
| 448 |
dictionary values to write (may be empty). |
| 449 |
""" |
| 450 |
result = {id_: {} for id_ in self.ids} |
| 451 |
sudo_self = self.sudo() # this creates only one env for all operation that required sudo() |
| 452 |
# (re)compute the amount (depending on unit_amount, employee_id for the cost, and account_id for currency) |
| 453 |
if any(field_name in values for field_name in ['unit_amount', 'employee_id', 'account_id']): |
| 454 |
for timesheet in sudo_self: |
| 455 |
if not timesheet.account_id.active: |
| 456 |
project_plan, _other_plans = self.env['account.analytic.plan']._get_all_plans() |
| 457 |
raise ValidationError(_( |
| 458 |
"Timesheets must be created with at least an active analytic account defined in the plan '%(plan_name)s'.", |
| 459 |
plan_name=project_plan.name |
| 460 |
)) |
| 461 |
accounts = timesheet._get_analytic_accounts() |
| 462 |
companies = timesheet.company_id | accounts.company_id | timesheet.task_id.company_id | timesheet.project_id.company_id |
| 463 |
if len(companies) > 1: |
| 464 |
raise ValidationError(_('The project, the task and the analytic accounts of the timesheet must belong to the same company.')) |
| 465 |
|
| 466 |
cost = timesheet._hourly_cost() |
| 467 |
amount = -timesheet.unit_amount * cost |
| 468 |
amount_converted = timesheet.employee_id.currency_id._convert( |
| 469 |
amount, timesheet.account_id.currency_id or timesheet.currency_id, self.env.company, timesheet.date) |
| 470 |
result[timesheet.id].update({ |
| 471 |
'amount': amount_converted, |
| 472 |
}) |
| 473 |
return result |
| 474 |
|
| 475 |
def _split_amount_fname(self): |
| 476 |
# split the quantity instead of the amount, since the amount is postprocessed |
| 477 |
# based on the quantity |
| 478 |
return 'unit_amount' if self.project_id else super()._split_amount_fname() |
| 479 |
|
| 480 |
def _is_timesheet_encode_uom_day(self): |
| 481 |
company_uom = self.env.company.timesheet_encode_uom_id |
| 482 |
return company_uom == self.env.ref('uom.product_uom_day') |
| 483 |
|
| 484 |
def _is_updatable_timesheet(self): |
| 485 |
return True |
| 486 |
|
| 487 |
@api.model |
| 488 |
def _convert_hours_to_days(self, time): |
| 489 |
uom_hour = self.env.ref('uom.product_uom_hour') |
| 490 |
uom_day = self.env.ref('uom.product_uom_day') |
| 491 |
return round(uom_hour._compute_quantity(time, uom_day, raise_if_failure=False), 2) |
| 492 |
|
| 493 |
def _get_timesheet_time_day(self): |
| 494 |
return self._convert_hours_to_days(self.unit_amount) |
| 495 |
|
| 496 |
def _hourly_cost(self): |
| 497 |
self.ensure_one() |
| 498 |
return self.employee_id.hourly_cost or 0.0 |
| 499 |
|
| 500 |
def _get_report_base_filename(self): |
| 501 |
task_ids = self.task_id |
| 502 |
if len(task_ids) == 1: |
| 503 |
return _('Timesheets - %s', task_ids.name) |
| 504 |
return _('Timesheets') |
| 505 |
|
| 506 |
def _default_user(self): |
| 507 |
return self.env.context.get('user_id', self.env.user.id) |
| 508 |
|
| 509 |
@api.model |
| 510 |
def _ensure_uom_hours(self): |
| 511 |
uom_hours = self.env.ref('uom.product_uom_hour', raise_if_not_found=False) |
| 512 |
if not uom_hours: |
| 513 |
uom_hours = self.env['uom.uom'].create({ |
| 514 |
'name': "Hours", |
| 515 |
'relative_factor': 1, |
| 516 |
}) |
| 517 |
self.env['ir.model.data'].create({ |
| 518 |
'name': 'product_uom_hour', |
| 519 |
'model': 'uom.uom', |
| 520 |
'module': 'uom', |
| 521 |
'res_id': uom_hours.id, |
| 522 |
'noupdate': True, |
| 523 |
}) |
| 524 |
|
| 525 |
@api.model |
| 526 |
def _show_portal_timesheets(self): |
| 527 |
""" |
| 528 |
Determine if we show timesheet information in the portal. Meant to be overriden in website_timesheet. |
| 529 |
""" |
| 530 |
return True |
| 531 |
|
| 532 |
def action_open_timesheet_view_portal(self): |
| 533 |
self.ensure_one() |
| 534 |
return { |
| 535 |
'type': 'ir.actions.act_window', |
| 536 |
'res_id': self.id, |
| 537 |
'res_model': 'account.analytic.line', |
| 538 |
'views': [(self.env.ref('hr_timesheet.timesheet_view_form_portal_user').id, 'form')], |
| 539 |
'context': self.env.context, |
| 540 |
} |
| 541 |
|
| 542 |
@api.model |
| 543 |
def get_unusual_days(self, date_from, date_to=None): |
| 544 |
return self.env.user.employee_id._get_unusual_days(date_from, date_to) |
| 545 |
|
| 546 |
@api.model |
| 547 |
def get_import_templates(self): |
| 548 |
if self.env.context.get('is_timesheet'): |
| 549 |
return [{ |
| 550 |
'label': _('Import Template for Timesheets'), |
| 551 |
'template': '/hr_timesheet/static/xls/timesheets_import_template.xlsx', |
| 552 |
}] |
| 553 |
return [] |