Debian Codegraph @

addons/hr_timesheet/models/project_project.py

raw
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 from collections import defaultdict
3
4 from odoo import api, fields, models
5 from odoo.exceptions import RedirectWarning, ValidationError
6 from odoo.tools import SQL, float_round
7 from odoo.tools.translate import _
8
9
10 class ProjectProject(models.Model):
11 _inherit = "project.project"
12
13 allow_timesheets = fields.Boolean(
14 "Timesheets", compute='_compute_allow_timesheets', store=True, readonly=False,
15 default=True)
16 account_id = fields.Many2one(
17 # note: replaces ['|', ('company_id', '=', False), ('company_id', '=', company_id)]
18 domain="""[
19 '|', ('company_id', '=', False), ('company_id', '=?', company_id),
20 ('partner_id', '=?', partner_id),
21 ]"""
22 )
23 analytic_account_active = fields.Boolean("Active Account", related="account_id.active", export_string_translation=False)
24
25 timesheet_ids = fields.One2many('account.analytic.line', 'project_id', 'Associated Timesheets', export_string_translation=False)
26 timesheet_encode_uom_id = fields.Many2one('uom.uom', compute='_compute_timesheet_encode_uom_id', export_string_translation=False)
27 total_timesheet_time = fields.Float(
28 compute='_compute_total_timesheet_time', groups='hr_timesheet.group_hr_timesheet_user',
29 string="Total amount of time (in the proper unit) recorded in the project, rounded to the unit.", export_string_translation=False)
30 encode_uom_in_days = fields.Boolean(compute='_compute_encode_uom_in_days', export_string_translation=False)
31 is_internal_project = fields.Boolean(compute='_compute_is_internal_project', search='_search_is_internal_project', export_string_translation=False)
32 remaining_hours = fields.Float(compute='_compute_remaining_hours', string='Time Remaining', compute_sudo=True)
33 is_project_overtime = fields.Boolean('Project in Overtime', compute='_compute_remaining_hours', search='_search_is_project_overtime', compute_sudo=True, export_string_translation=False)
34 allocated_hours = fields.Float(string='Allocated Time', tracking=True)
35 effective_hours = fields.Float(string='Time Spent', compute='_compute_remaining_hours', compute_sudo=True)
36
37 def _compute_encode_uom_in_days(self):
38 self.encode_uom_in_days = self.env.company.timesheet_encode_uom_id == self.env.ref('uom.product_uom_day')
39
40 @api.depends('company_id', 'company_id.timesheet_encode_uom_id')
41 @api.depends_context('company')
42 def _compute_timesheet_encode_uom_id(self):
43 for project in self:
44 project.timesheet_encode_uom_id = project.company_id.timesheet_encode_uom_id or self.env.company.timesheet_encode_uom_id
45
46 @api.depends('account_id')
47 def _compute_allow_timesheets(self):
48 without_account = self.filtered(lambda t: t._origin and not t.account_id)
49 without_account.update({'allow_timesheets': False})
50
51 @api.depends('company_id')
52 def _compute_is_internal_project(self):
53 for project in self:
54 project.is_internal_project = project == project.company_id.internal_project_id
55
56 @api.model
57 def _search_is_internal_project(self, operator, value):
58 if operator not in ('in', 'not in'):
59 return NotImplemented
60
61 Company = self.env['res.company']
62 sql = Company._search(
63 [('internal_project_id', '!=', False)],
64 active_test=False, bypass_access=True,
65 ).subselect("internal_project_id")
66 return [('id', operator, sql)]
67
68 @api.depends('allow_timesheets', 'timesheet_ids.unit_amount', 'allocated_hours')
69 def _compute_remaining_hours(self):
70 timesheets_read_group = self.env['account.analytic.line']._read_group(
71 [('project_id', 'in', self.ids)],
72 ['project_id'],
73 ['unit_amount:sum'],
74 )
75 timesheet_time_dict = {project.id: unit_amount_sum for project, unit_amount_sum in timesheets_read_group}
76 for project in self:
77 project.effective_hours = round(timesheet_time_dict.get(project.id, 0.0), 2)
78 project.remaining_hours = project.allocated_hours - project.effective_hours
79 project.is_project_overtime = project.remaining_hours < 0
80
81 @api.model
82 def _search_is_project_overtime(self, operator, value):
83 if operator not in ('in', 'not in'):
84 return NotImplemented
85
86 sql = SQL("""(
87 SELECT Project.id
88 FROM project_project AS Project
89 JOIN project_task AS Task
90 ON Project.id = Task.project_id
91 WHERE Project.allocated_hours > 0
92 AND Project.allow_timesheets = TRUE
93 AND Task.parent_id IS NULL
94 AND Task.state IN ('01_in_progress', '02_changes_requested', '03_approved', '04_waiting_normal')
95 GROUP BY Project.id
96 HAVING Project.allocated_hours - SUM(Task.effective_hours) < 0
97 )""")
98 return [('id', operator, sql)]
99
100 @api.constrains('allow_timesheets', 'account_id')
101 def _check_allow_timesheet(self):
102 for project in self:
103 if project.allow_timesheets and not project.account_id and not project.is_template:
104 project_plan, _other_plans = self.env['account.analytic.plan']._get_all_plans()
105 raise ValidationError(_(
106 "To use the timesheets feature, you need an analytic account for your project. Please set one up in the plan '%(plan_name)s' or turn off the timesheets feature.",
107 plan_name=project_plan.name
108 ))
109
110 @api.depends('timesheet_ids', 'timesheet_encode_uom_id')
111 def _compute_total_timesheet_time(self):
112 timesheets_read_group = self.env['account.analytic.line']._read_group(
113 [('project_id', 'in', self.ids)],
114 ['project_id', 'product_uom_id'],
115 ['unit_amount:sum'],
116 )
117 timesheet_time_dict = defaultdict(list)
118 for project, product_uom, unit_amount_sum in timesheets_read_group:
119 timesheet_time_dict[project.id].append((product_uom, unit_amount_sum))
120
121 for project in self:
122 # Timesheets may be stored in a different unit of measure, so first
123 # we convert all of them to the reference unit
124 # if the timesheet has no product_uom_id then we take the one of the project
125 total_time = 0.0
126 for product_uom, unit_amount in timesheet_time_dict[project.id]:
127 factor = (product_uom or project.timesheet_encode_uom_id).factor
128 total_time += unit_amount * (1.0 if project.encode_uom_in_days else factor)
129 # Now convert to the proper unit of measure set in the settings
130 total_time /= project.timesheet_encode_uom_id.factor
131 project.total_timesheet_time = float_round(total_time, precision_digits=2)
132
133 @api.model_create_multi
134 def create(self, vals_list):
135 """ Create an analytic account if project allow timesheet and don't provide one
136 Note: create it before calling super() to avoid raising the ValidationError from _check_allow_timesheet
137 """
138 defaults = self.default_get(['allow_timesheets', 'account_id', 'is_template'])
139 analytic_accounts_vals = [
140 vals for vals in vals_list
141 if (
142 vals.get('allow_timesheets', defaults.get('allow_timesheets')) and
143 not vals.get('account_id', defaults.get('account_id')) and not vals.get('is_template', defaults.get('is_template'))
144 )
145 ]
146
147 if analytic_accounts_vals:
148 analytic_accounts = self.env['account.analytic.account'].create(self._get_values_analytic_account_batch(analytic_accounts_vals))
149 for vals, analytic_account in zip(analytic_accounts_vals, analytic_accounts):
150 vals['account_id'] = analytic_account.id
151 return super().create(vals_list)
152
153 def write(self, vals):
154 # create the AA for project still allowing timesheet
155 if vals.get('allow_timesheets') and not vals.get('account_id'):
156 project_wo_account = self.filtered(lambda project: not project.account_id and not project.is_template)
157 if project_wo_account:
158 project_wo_account._create_analytic_account()
159 return super().write(vals)
160
161 @api.depends('is_internal_project', 'company_id')
162 @api.depends_context('allowed_company_ids')
163 def _compute_display_name(self):
164 super()._compute_display_name()
165 if len(self.env.context.get('allowed_company_ids') or []) <= 1:
166 return
167
168 for project in self:
169 if project.is_internal_project:
170 project.display_name = f'{project.display_name} - {project.company_id.name}'
171
172 @api.model
173 def _init_data_analytic_account(self):
174 self.search([('account_id', '=', False), ('allow_timesheets', '=', True), ('is_template', '=', False)])._create_analytic_account()
175
176 @api.ondelete(at_uninstall=False)
177 def _unlink_except_contains_entries(self):
178 """
179 If some projects to unlink have some timesheets entries, these
180 timesheets entries must be unlinked first.
181 In this case, a warning message is displayed through a RedirectWarning
182 and allows the user to see timesheets entries to unlink.
183 """
184 projects_with_timesheets = self.filtered(lambda p: p.timesheet_ids)
185 if projects_with_timesheets:
186 if len(projects_with_timesheets) > 1:
187 warning_msg = _("These projects have some timesheet entries referencing them. Before removing these projects, you have to remove these timesheet entries.")
188 else:
189 warning_msg = _("This project has some timesheet entries referencing it. Before removing this project, you have to remove these timesheet entries.")
190 raise RedirectWarning(
191 warning_msg, self.env.ref('hr_timesheet.timesheet_action_project').id,
192 _('See timesheet entries'), {'active_ids': projects_with_timesheets.ids})
193
194 @api.model
195 def get_create_edit_project_ids(self):
196 return []
197
198 def _convert_project_uom_to_timesheet_encode_uom(self, time):
199 uom_from = self.company_id.project_time_mode_id
200 uom_to = self.env.company.timesheet_encode_uom_id
201 return round(uom_from._compute_quantity(time, uom_to, raise_if_failure=False), 2)
202
203 def action_project_timesheets(self):
204 action = self.env['ir.actions.act_window']._for_xml_id('hr_timesheet.act_hr_timesheet_line_by_project')
205 if not self.env.context.get('from_embedded_action'):
206 action['display_name'] = _("%(name)s's Timesheets", name=self.name)
207 return action
208
209 # ----------------------------
210 # Project Updates
211 # ----------------------------
212
213 def _get_stat_buttons(self):
214 buttons = super()._get_stat_buttons()
215 if not self.allow_timesheets or not self.env.user.has_group("hr_timesheet.group_hr_timesheet_user"):
216 return buttons
217
218 encode_uom = self.env.company.timesheet_encode_uom_id
219 uom_ratio = self.env.ref('uom.product_uom_hour').factor / encode_uom.factor
220
221 allocated = self.allocated_hours * uom_ratio
222 effective = self.total_timesheet_time
223 color = ""
224 if allocated:
225 number = f"{round(effective)} / {round(allocated)} {encode_uom.name}"
226 success_rate = round(100 * effective / allocated)
227 if success_rate > 100:
228 number = self.env._(
229 "%(effective)s / %(allocated)s %(uom_name)s",
230 effective=round(effective),
231 allocated=round(allocated),
232 uom_name=encode_uom.name,
233 )
234 color = "text-danger"
235 else:
236 number = self.env._(
237 "%(effective)s / %(allocated)s %(uom_name)s (%(success_rate)s%%)",
238 effective=round(effective),
239 allocated=round(allocated),
240 uom_name=encode_uom.name,
241 success_rate=success_rate,
242 )
243 if success_rate >= 80:
244 color = "text-warning"
245 else:
246 color = "text-success"
247 else:
248 number = self.env._(
249 "%(effective)s %(uom_name)s",
250 effective=round(effective),
251 uom_name=encode_uom.name,
252 )
253
254 buttons.append({
255 "icon": f"clock-o {color}",
256 "text": self.env._("Timesheets"),
257 "number": number,
258 "action_type": "object",
259 "action": "action_project_timesheets",
260 "show": True,
261 "sequence": 2,
262 })
263 if allocated and success_rate > 100:
264 buttons.append({
265 "icon": f"warning {color}",
266 "text": self.env._("Extra Time"),
267 "number": self.env._(
268 "%(exceeding_hours)s %(uom_name)s (+%(exceeding_rate)s%%)",
269 exceeding_hours=round(effective - allocated),
270 uom_name=encode_uom.name,
271 exceeding_rate=round(100 * (effective - allocated) / allocated),
272 ),
273 "action_type": "object",
274 "action": "action_project_timesheets",
275 "show": True,
276 "sequence": 3,
277 })
278
279 return buttons
280
281 def action_view_tasks(self):
282 # Using the timesheet filter hide context
283 action = super().action_view_tasks()
284 action['context']['allow_timesheets'] = self.allow_timesheets
285 return action
286
287 def _toggle_template_mode(self, is_template):
288 if not is_template and self.allow_timesheets and not self.account_id:
289 self._create_analytic_account()
290 super()._toggle_template_mode(is_template)