Newer
Older
# © 2021 Le Filament (<http://www.le-filament.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from datetime import timedelta
import pytz
from odoo import models, fields, api
from odoo.fields import Date
from odoo.tools import pycompat
from odoo.exceptions import UserError, ValidationError
from odoo.addons.calendar.models.calendar import calendar_id2real_id
class CalendarAttendee(models.Model):
_inherit = 'calendar.attendee'
timesheet_ids = fields.One2many(
comodel_name='account.analytic.line',
inverse_name='attendee_id',
string='Timesheet linked',
copy=False)
class CalendarEvent(models.Model):
_inherit = 'calendar.event'
partner_ids = fields.Many2many(domain=[
('user_ids', '!=', False)])
project_id = fields.Many2one(
comodel_name="project.project",
string="Projet lié",
domain=[('allow_timesheets', '=', True)])
task_id = fields.Many2one(
comodel_name="project.task",
compute='_compute_is_transfered')
compute='_compute_is_attendee')
# ------------------------------------------------------
# Compute
# ------------------------------------------------------
def _compute_is_transfered(self):
for event in self:
event_id = event.get_metadata()[0].get('id')
attendee = self.env['calendar.attendee'].search([
('event_id', '=', event_id),
('partner_id', '=', self.env.user.partner_id.id)])
# l'attendee a des feuilles de temps liées à la même date
if (attendee.timesheet_ids
and attendee.timesheet_ids.filtered(
lambda t: t.date == event.start.date())):
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def _compute_is_attendee(self):
for event in self:
if self.env.user.partner_id in event.partner_ids:
event.is_attendee = True
else:
event.is_attendee = False
# ------------------------------------------------------
# Onchange
# ------------------------------------------------------
@api.onchange('project_id')
def onchange_project_id(self):
# force domain on task when project is set
if self.project_id:
return {'domain': {
'task_id': [('project_id', '=', self.project_id.id)]
}}
else:
return {'domain': {
'task_id': []
}}
# ------------------------------------------------------
# Contrains
# ------------------------------------------------------
# ------------------------------------------------------
# Fonction boutons
# ------------------------------------------------------
@api.multi
def create_timesheet(self):
""" Crée une ligne de temps à partir de l'entrée d'agenda
"""
partner = self.env.user.partner_id
for event in self:
event_id = event.get_metadata()[0].get('id')
if partner not in event.partner_ids:
raise UserError("Vous ne faites pas partie des participants, \
vous ne pouvez donc pas transformer cette entrée d'agenda \
en ligne de temps.")
if not event.project_id:
raise UserError("Un projet doit être \
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
renseigné sur chaque entrée d'agenda")
else:
attendee = self.env['calendar.attendee'].search([
('event_id', '=', event_id),
('partner_id', '=', partner.id)])
# l'attendee a des feuilles de temps liées à la même date
if (attendee.timesheet_ids
and attendee.timesheet_ids.filtered(
lambda t: t.date == event.start.date())):
raise UserError("Vous avez déjà transféré cette entrée \
d'agenda : %s" % event.name)
else:
values = {
'user_id': self.env.user.id,
'project_id': event.project_id.id,
'task_id': event.task_id.id or False,
'account_id': event.project_id.analytic_account_id.id,
'name': event.name,
'company_id': self.env.user.company_id.id,
'event_id': event_id,
'attendee_id': attendee.id,
}
# Gestion des évènements sur toute la journée
if event.allday:
# Création d'une ligne de 8h pour chaque jour
for i in range((event.stop - event.start).days + 1):
values['date'] = event.start + timedelta(days=i)
values['unit_amount'] = 8.0
ts = self.env['account.analytic.line'].create(
values)
attendee.write({'timesheet_id': ts.id})
# Gestion des évènements sur plusieurs jours non flagués
# allday
elif (event.stop - event.start).days > 0:
user_tz = self.env.user.tz
local = pytz.timezone(user_tz)
# Pour chaque jour
for i in range((event.stop - event.start).days + 1):
day = event.start + timedelta(days=i)
# si premier jour calcul heures
if i == 0:
end_day_tz = local.localize(
day.replace(hour=18))
start_tz = fields.Datetime.context_timestamp(
record=self.env.user,
timestamp=event.start)
hours_cal = ((end_day_tz - start_tz).seconds
// 3600)
hours = hours_cal if hours_cal <= 8 else 8.0
# si dernier jour
elif i == (event.stop - event.start).days:
start_day_tz = local.localize(
day.replace(hour=8))
stop_tz = fields.Datetime.context_timestamp(
record=self.env.user,
timestamp=event.stop)
hours_cal = ((stop_tz - start_day_tz).seconds
// 3600)
hours = hours_cal if hours_cal <= 8 else 8.0
else:
hours = 8.0
values['date'] = day
values['unit_amount'] = hours
ts = self.env['account.analytic.line'].create(
values)
attendee.write({'timesheet_id': ts.id})
# Gestion des évènements classiques
else:
values['date'] = event.start
values['unit_amount'] = event.duration
ts = self.env['account.analytic.line'].create(values)
attendee.write({'timesheet_id': ts.id})
# ------------------------------------------------------
# Override ORM
# ------------------------------------------------------
@api.multi
def read(self, fields=None, load='_classic_read'):
""" Surcharge la fonction read de calendar pour gérer le transfert des
lignes de temps sur les virtual events.
Ajoute le calcul de la valeur du champs 'is_transfered' dans la
boucle 'for calendar_id, real_id in select'
"""
if not fields:
fields = list(self._fields)
fields2 = fields and fields[:]
EXTRAFIELDS = ('privacy', 'user_id', 'duration', 'allday', 'start',
'rrule')
for f in EXTRAFIELDS:
if fields and (f not in fields):
fields2.append(f)
select = [(x, calendar_id2real_id(x)) for x in self.ids]
real_events = self.browse([real_id for calendar_id, real_id in select])
real_data = super(CalendarEvent, real_events).read(fields=fields2,
load=load)
real_data = dict((d['id'], d) for d in real_data)
result = []
for calendar_id, real_id in select:
if not real_data.get(real_id):
continue
res = real_data[real_id].copy()
ls = calendar_id2real_id(calendar_id, with_date=res
and res.get('duration', 0) > 0
and res.get('duration') or 1)
if not isinstance(ls, (pycompat.string_types,
pycompat.integer_types)) and len(ls) >= 2:
res['start'] = ls[1]
res['stop'] = ls[2]
if res['allday']:
res['start_date'] = ls[1]
res['stop_date'] = ls[2]
else:
res['start_datetime'] = ls[1]
res['stop_datetime'] = ls[2]
if 'display_time' in fields:
res['display_time'] = self._get_display_time(
ls[1], ls[2], res['duration'], res['allday'])
attendee = self.env['calendar.attendee'].search([
('event_id', '=', ls[0]),
('partner_id', '=', self.env.user.partner_id.id)])
# l'attendee a des feuilles de temps liées à la même date
if (attendee.timesheet_ids
and attendee.timesheet_ids.filtered(
lambda t: t.date == Date.to_date(ls[1]))):
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
res['id'] = calendar_id
result.append(res)
for r in result:
if r['user_id']:
user_id = (type(r['user_id']) in (tuple, list)
and r['user_id'][0] or r['user_id'])
partner_id = self.env.user.partner_id.id
if user_id == (self.env.user.id
or partner_id in r.get("partner_ids", [])):
continue
if r['privacy'] == 'private':
for f in r:
recurrent_fields = self._get_recurrent_fields()
public_fields = list(set(recurrent_fields
+ ['id', 'allday', 'start',
'stop', 'display_start',
'display_stop', 'duration',
'user_id', 'state', 'interval',
'count', 'recurrent_id_date',
'rrule']))
if f not in public_fields:
if isinstance(r[f], list):
r[f] = []
else:
r[f] = False
if f == 'name':
r[f] = ('Busy')
for r in result:
for k in EXTRAFIELDS:
if (k in r) and (fields and (k not in fields)):
del r[k]
return result
@api.model
def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
if 'date' in groupby:
raise UserError(_('Group by date is not supported, use the calendar view instead.'))
if self._context.get("mymeetings"):
domain.append(('partner_ids', 'in', self.env.user.partner_id.ids))
return super(CalendarEvent, self.with_context(virtual_id=False)).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)