-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhr_payroll.py
1674 lines (1469 loc) · 67.1 KB
/
hr_payroll.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
99
100
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
231
232
233
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding:utf-8 -*-
#
#
# Copyright (C) 2013 Michael Telahun Makonnen <[email protected]>.
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from pytz import timezone, utc
from datetime import datetime, timedelta
import openerp.addons.decimal_precision as dp
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as OE_DATEFORMAT
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT as OE_DATETIMEFORMAT
from openerp.tools.translate import _
from openerp.osv import fields, orm
class last_X_days:
"""Last X Days
Keeps track of the days an employee worked/didn't work in the last
X days.
"""
def __init__(self, days=6):
self.limit = days
self.arr = []
def push(self, worked=False):
if len(self.arr) == self.limit:
self.arr.pop(0)
self.arr.append(worked)
return [v for v in self.arr]
def days_worked(self):
res = 0
for d in self.arr:
if d is True:
res += 1
return res
class hr_payslip(orm.Model):
_name = 'hr.payslip'
_inherit = 'hr.payslip'
def _get_policy(self, policy_group, policy_ids, dDay):
"""Return a policy with an effective date before dDay but
greater than all others
"""
if not policy_group or not policy_ids:
return None
res = None
for policy in policy_ids:
dPolicy = datetime.strptime(policy.date, OE_DATEFORMAT).date()
if dPolicy <= dDay and (
res is None
or dPolicy > datetime.strptime(res.date,
OE_DATEFORMAT).date()):
res = policy
return res
def _get_ot_policy(self, policy_group, dDay):
"""Return an OT policy with an effective date before dDay but
greater than all others
"""
return self._get_policy(policy_group, policy_group.ot_policy_ids, dDay)
def _get_absence_policy(self, policy_group, dDay):
"""Return an Absence policy with an effective date before dDay
but greater than all others
"""
return self._get_policy(
policy_group, policy_group.absence_policy_ids, dDay
)
def _get_presence_policy(self, policy_group, dDay):
"""Return a Presence Policy with an effective date before dDay
but greater than all others
"""
return self._get_policy(
policy_group, policy_group.presence_policy_ids, dDay
)
def _get_applied_time(
self, worked_hours, pol_active_after, pol_duration=None):
"""Returns worked time in hours according to pol_active_after
and pol_duration.
"""
applied_min = (worked_hours * 60) - pol_active_after
if applied_min > 0.01:
applied_min = (pol_duration is not None and applied_min >
pol_duration) and pol_duration or applied_min
else:
applied_min = 0
applied_hours = float(applied_min) / 60.0
return applied_hours
def _book_holiday_hours(
self, cr, uid, contract, presence_policy, ot_policy, attendances,
holiday_obj, dtDay, rest_days, lsd, worked_hours, context=None):
done = False
push_lsd = True
hours = worked_hours
# Process normal working hours
for line in presence_policy.line_ids:
if line.type == 'holiday':
holiday_hours = self._get_applied_time(
worked_hours, line.active_after,
line.duration)
attendances[line.code]['number_of_hours'] += holiday_hours
attendances[line.code]['number_of_days'] += 1.0
hours -= holiday_hours
done = True
# Process OT hours
for line in ot_policy.line_ids:
if line.type == 'holiday':
ot_hours = self._get_applied_time(
worked_hours, line.active_after)
attendances[line.code]['number_of_hours'] += ot_hours
attendances[line.code]['number_of_days'] += 1.0
hours -= ot_hours
done = True
if done and (dtDay.weekday() in rest_days or lsd.days_worked == 6):
# Mark this day as *not* worked so that subsequent days
# are not treated as over-time.
lsd.push(False)
push_lsd = False
if -0.01 < hours < 0.01:
hours = 0
return hours, push_lsd
def _book_restday_hours(
self, cr, uid, contract, presence_policy, ot_policy, attendances,
dtDay, rest_days, lsd, worked_hours, context=None):
done = False
push_lsd = True
hours = worked_hours
# Process normal working hours
for line in presence_policy.line_ids:
if line.type == 'restday' and dtDay.weekday() in rest_days:
rd_hours = self._get_applied_time(
worked_hours, line.active_after, line.duration)
attendances[line.code]['number_of_hours'] += rd_hours
attendances[line.code]['number_of_days'] += 1.0
hours -= rd_hours
done = True
# Process OT hours
for line in ot_policy.line_ids:
if line.type == 'restday' and dtDay.weekday() in rest_days:
ot_hours = self._get_applied_time(
worked_hours, line.active_after)
attendances[line.code]['number_of_hours'] += ot_hours
attendances[line.code]['number_of_days'] += 1.0
hours -= ot_hours
done = True
if done and (dtDay.weekday() in rest_days or lsd.days_worked == 6):
# Mark this day as *not* worked so that subsequent days
# are not treated as over-time.
lsd.push(False)
push_lsd = False
if -0.01 < hours < 0.01:
hours = 0
return hours, push_lsd
def _book_weekly_restday_hours(
self, cr, uid, contract, presence_policy, ot_policy, attendances,
dtDay, rest_days, lsd, worked_hours, context=None):
done = False
push_lsd = True
hours = worked_hours
# Process normal working hours
for line in presence_policy.line_ids:
if line.type == 'restday':
if lsd.days_worked() == line.active_after:
rd_hours = self._get_applied_time(
worked_hours, line.active_after, line.duration)
attendances[line.code]['number_of_hours'] += rd_hours
attendances[line.code]['number_of_days'] += 1.0
hours -= rd_hours
done = True
# Process OT hours
for line in ot_policy.line_ids:
if (line.type == 'weekly' and line.weekly_working_days
and line.weekly_working_days > 0
and lsd.days_worked() == line.weekly_working_days):
ot_hours = self._get_applied_time(
worked_hours, line.active_after)
attendances[line.code]['number_of_hours'] += ot_hours
attendances[line.code]['number_of_days'] += 1.0
hours -= ot_hours
done = True
if done and (dtDay.weekday() in rest_days or lsd.days_worked == 6):
# Mark this day as *not* worked so that subsequent days
# are not treated as over-time.
lsd.push(False)
push_lsd = False
if -0.01 < hours < 0.01:
hours = 0
return hours, push_lsd
def holidays_list_init(self, cr, uid, dFrom, dTo, context=None):
holiday_obj = self.pool.get('hr.holidays.public')
res = holiday_obj.get_holidays_list(
cr, uid, dFrom.year, context=context)
if dTo.year != dFrom.year:
res += holiday_obj.get_holidays_list(
cr, uid, dTo.year, context=context)
return res
def holidays_list_contains(self, d, holidays_list):
if d.strftime(OE_DATEFORMAT) in holidays_list:
return True
return False
def attendance_dict_init(
self, cr, uid, contract, dFrom, dTo, context=None):
att_obj = self.pool.get('hr.attendance')
res = {}
att_list = att_obj.punches_list_init(
cr, uid, contract.employee_id.id, contract.pps_id,
dFrom, dTo, context=context)
res.update({'raw_list': att_list})
d = dFrom
while d <= dTo:
res[d.strftime(
OE_DATEFORMAT)] = att_obj.total_hours_on_day(
cr, uid, contract, d,
punches_list=att_list,
context=context)
d += timedelta(days=+1)
return res
def attendance_dict_hours_on_day(self, d, attendance_dict):
return attendance_dict[d.strftime(OE_DATEFORMAT)]
def attendance_dict_list(self, att_dict):
return att_dict['raw_list']
def leaves_list_init(
self, cr, uid, employee_id, dFrom, dTo, tz, context=None):
"""Returns a list of tuples containing start, end dates for
leaves within the specified period.
"""
leave_obj = self.pool.get('hr.holidays')
dtS = datetime.strptime(
dFrom.strftime(OE_DATEFORMAT) + ' 00:00:00', OE_DATETIMEFORMAT)
dtE = datetime.strptime(
dTo.strftime(OE_DATEFORMAT) + ' 23:59:59', OE_DATETIMEFORMAT)
utcdt_dayS = timezone(tz).localize(dtS).astimezone(utc)
utcdt_dayE = timezone(tz).localize(dtE).astimezone(utc)
utc_dayS = utcdt_dayS.strftime(OE_DATETIMEFORMAT)
utc_dayE = utcdt_dayE.strftime(OE_DATETIMEFORMAT)
leave_ids = leave_obj.search(
cr, uid, [('state', 'in', ['validate', 'validate1']),
('employee_id', '=', employee_id),
('type', '=', 'remove'),
('date_from', '<=', utc_dayE),
('date_to', '>=', utc_dayS)],
context=context)
res = []
if len(leave_ids) == 0:
return res
for leave in leave_obj.browse(cr, uid, leave_ids, context=context):
res.append({
'code': leave.holiday_status_id.code,
'tz': tz,
'start': utc.localize(datetime.strptime(leave.date_from,
OE_DATETIMEFORMAT)),
'end': utc.localize(datetime.strptime(leave.date_to,
OE_DATETIMEFORMAT))
})
return res
def leaves_list_get_hours(
self, cr, uid, employee_id, contract_id, sched_tpl_id, d,
leaves_list, context=None):
"""Return the number of hours of leave on a given date, d."""
detail_pool = self.pool['hr.schedule.detail']
code = False
hours = 0
if len(leaves_list) == 0:
return code, hours
dtS = datetime.strptime(
d.strftime(OE_DATEFORMAT) + ' 00:00:00', OE_DATETIMEFORMAT)
dtE = datetime.strptime(
d.strftime(OE_DATEFORMAT) + ' 23:59:59', OE_DATETIMEFORMAT)
for l in leaves_list:
utcBegin = l['start']
utcEnd = l['end']
dtLvBegin = datetime.strptime(
utcBegin.strftime(OE_DATETIMEFORMAT), OE_DATETIMEFORMAT)
dtLvEnd = datetime.strptime(
utcEnd.strftime(OE_DATETIMEFORMAT), OE_DATETIMEFORMAT)
utcdt_dayS = timezone(l['tz']).localize(dtS).astimezone(utc)
utcdt_dayE = timezone(l['tz']).localize(dtE).astimezone(utc)
if utcdt_dayS <= utcEnd and utcdt_dayE >= utcBegin:
code = l['code']
sched_tpl_obj = self.pool.get('hr.schedule.template')
if utcBegin.date() < utcdt_dayS.date() < utcEnd.date():
hours = 24
elif utcBegin.date() == utcdt_dayE.date():
hours = float((utcdt_dayE - utcBegin).seconds / 60) / 60.0
elif utcBegin.date() == utcdt_dayS.date():
shift_times = detail_pool.scheduled_begin_end_times(
cr, uid, employee_id, contract_id, dtS, context=context
)
if len(shift_times) > 0:
for dtStart, dtEnd in shift_times:
if dtLvBegin < dtEnd:
dt = ((dtLvBegin < dtStart) and dtStart
or dtLvBegin)
hours += float(
(dtEnd - dt).seconds / 60) / 60.0
dtLvBegin = dtEnd
else:
hours = sched_tpl_obj.get_hours_by_weekday(
cr, uid, sched_tpl_id, d.weekday(),
context=context) or 8
else: # dtTo.date() == dToday
shift_times = detail_pool.scheduled_begin_end_times(
cr, uid, employee_id, contract_id, dtS, context=context
)
if len(shift_times) > 0:
for dtStart, dtEnd in shift_times:
if dtLvEnd > dtStart:
dt = (dtLvEnd > dtEnd) and dtEnd or dtLvEnd
hours += float(
(dt - dtStart).seconds / 60) / 60.0
else:
hours = sched_tpl_obj.get_hours_by_weekday(
cr, uid, sched_tpl_id, d.weekday(),
context=context) or 8
return code, hours
# Copied from addons/hr_payroll so that we can override worked days
# calculation to handle Overtime and absence
#
def get_worked_day_lines(
self, cr, uid, contract_ids, date_from, date_to, context=None):
"""
@param contract_ids: list of contract id
@return: returns a list of dict containing the input that should be
applied for the given contract between date_from and date_to
"""
sched_tpl_obj = self.pool.get('hr.schedule.template')
sched_obj = self.pool.get('hr.schedule')
detail_obj = self.pool.get('hr.schedule.detail')
ot_obj = self.pool.get('hr.policy.ot')
presence_obj = self.pool.get('hr.policy.presence')
absence_obj = self.pool.get('hr.policy.absence')
holiday_obj = self.pool.get('hr.holidays.public')
day_from = datetime.strptime(date_from, "%Y-%m-%d").date()
day_to = datetime.strptime(date_to, "%Y-%m-%d").date()
nb_of_days = (day_to - day_from).days + 1
# Initialize list of public holidays. We only need to calculate it once
# during the lifetime of this object so attach it directly to it.
#
try:
public_holidays_list = self._mtm_public_holidays_list
except AttributeError:
self._mtm_public_holidays_list = self.holidays_list_init(
cr, uid, day_from, day_to,
context=context)
public_holidays_list = self._mtm_public_holidays_list
def get_ot_policies(policy_group_id, day, data):
if data is None or not data['_reuse']:
data = {
'policy': None,
'daily': None,
'restday2': None,
'restday': None,
'weekly': None,
'holiday': None,
'_reuse': False,
}
elif data['_reuse']:
return data
ot_policy = self._get_ot_policy(policy_group_id, day)
daily_ot = ot_policy and len(
ot_obj.daily_codes(cr, uid, ot_policy.id, context=context)
) > 0 or None
restday2_ot = ot_policy and len(ot_obj.restday2_codes(
cr, uid, ot_policy.id, context=context)) > 0 or None
restday_ot = ot_policy and len(ot_obj.restday_codes(
cr, uid, ot_policy.id, context=context)) > 0 or None
weekly_ot = ot_policy and len(
ot_obj.weekly_codes(cr, uid, ot_policy.id, context=context)
) > 0 or None
holiday_ot = ot_policy and len(ot_obj.holiday_codes(
cr, uid, ot_policy.id, context=context)) > 0 or None
data['policy'] = ot_policy
data['daily'] = daily_ot
data['restday2'] = restday2_ot
data['restday'] = restday_ot
data['weekly'] = weekly_ot
data['holiday'] = holiday_ot
return data
def get_absence_policies(policy_group_id, day, data):
if data is None or not data.get('_reuse'):
data = {
'policy': None,
'_reuse': False,
}
elif data['_reuse']:
return data
absence_policy = self._get_absence_policy(policy_group_id, day)
data['policy'] = absence_policy
return data
def get_presence_policies(policy_group_id, day, data):
if data is None or not data.get('_reuse'):
data = {
'policy': None,
'_reuse': False,
}
elif data['_reuse']:
return data
policy = self._get_presence_policy(policy_group_id, day)
data['policy'] = policy
return data
res = []
for contract in self.pool.get('hr.contract').browse(
cr, uid, contract_ids, context=context):
wh_in_week = 0
# Initialize list of leaves taken by the employee during the month
leaves_list = self.leaves_list_init(
cr, uid, contract.employee_id.id,
day_from, day_to, contract.pps_id.tz, context=context)
# Get default set of rest days for this employee/contract
contract_rest_days = sched_tpl_obj.get_rest_days(
cr, uid, contract.schedule_template_id.id, context=context
)
# Initialize dictionary of dates in this payslip and the hours the
# employee was scheduled to work on each
sched_hours_dict = detail_obj.scheduled_begin_end_times_range(
cr, uid,
contract.employee_id.id,
contract.id,
day_from, day_to,
context=context)
# Initialize dictionary of hours worked per day
working_hours_dict = self.attendance_dict_init(
cr, uid, contract, day_from, day_to,
context=None)
# Short-circuit:
# If the policy for the first day is the same as the one for the
# last day assume that it will also be the same for the days in
# between, and reuse the same policy instead of checking for every
# day.
#
ot_data = None
data2 = None
ot_data = get_ot_policies(
contract.policy_group_id, day_from, ot_data)
data2 = get_ot_policies(contract.policy_group_id, day_to, data2)
if ((ot_data['policy'] and data2['policy'])
and ot_data['policy'].id == data2['policy'].id):
ot_data['_reuse'] = True
absence_data = None
data2 = None
absence_data = get_absence_policies(
contract.policy_group_id, day_from, absence_data)
data2 = get_absence_policies(
contract.policy_group_id, day_to, data2)
if (absence_data['policy'] and data2['policy']
and absence_data['policy'].id == data2['policy'].id):
absence_data['_reuse'] = True
presence_data = None
data2 = None
presence_data = get_presence_policies(
contract.policy_group_id, day_from, presence_data)
data2 = get_presence_policies(
contract.policy_group_id, day_to, data2)
if (presence_data['policy'] and data2['policy']
and presence_data['policy'].id == data2['policy'].id):
presence_data['_reuse'] = True
# Calculate the number of days worked in the last week of
# the previous month. Necessary to calculate Weekly Rest Day OT.
#
lsd = last_X_days()
att_obj = self.pool.get('hr.attendance')
att_ids = []
if len(lsd.arr) == 0:
d = day_from - timedelta(days=6)
while d < day_from:
att_ids = att_obj.search(cr, uid, [
('employee_id', '=', contract.employee_id.id),
('day', '=', d.strftime(
'%Y-%m-%d')),
],
order='name',
# XXX - necessary to keep
# order: in,out,in,out,...
context=context)
if len(att_ids) > 1:
lsd.push(True)
else:
lsd.push(False)
d += timedelta(days=1)
attendances = {
'MAX': {
'name': _("Maximum Possible Working Hours"),
'sequence': 1,
'code': 'MAX',
'number_of_days': 0.0,
'number_of_hours': 0.0,
'contract_id': contract.id,
},
}
leaves = {}
att_obj = self.pool.get('hr.attendance')
awol_code = False
import logging
_l = logging.getLogger(__name__)
for day in range(0, nb_of_days):
dtDateTime = datetime.strptime(
(day_from + timedelta(days=day)).strftime('%Y-%m-%d'),
'%Y-%m-%d'
)
rest_days = contract_rest_days
normal_working_hours = 0
# Get Presence data
#
presence_data = get_presence_policies(
contract.policy_group_id, dtDateTime.date(), presence_data)
presence_policy = presence_data['policy']
presence_codes = presence_policy and presence_obj.get_codes(
cr, uid, presence_policy.id, context=context) or []
presence_sequence = 2
for pcode, pname, ptype, prate, pduration in presence_codes:
if attendances.get(pcode, False):
continue
if ptype == 'normal':
normal_working_hours += float(pduration) / 60.0
attendances[pcode] = {
'name': pname,
'code': pcode,
'sequence': presence_sequence,
'number_of_days': 0.0,
'number_of_hours': 0.0,
'rate': prate,
'contract_id': contract.id,
}
presence_sequence += 1
# Get OT data
#
ot_data = get_ot_policies(
contract.policy_group_id, dtDateTime.date(), ot_data)
ot_policy = ot_data['policy']
daily_ot = ot_data['daily']
restday2_ot = ot_data['restday2']
restday_ot = ot_data['restday']
weekly_ot = ot_data['weekly']
ot_codes = ot_policy and ot_obj.get_codes(
cr, uid, ot_policy.id, context=context) or []
ot_sequence = 3
for otcode, otname, ottype, otrate in ot_codes:
if attendances.get(otcode, False):
continue
attendances[otcode] = {
'name': otname,
'code': otcode,
'sequence': ot_sequence,
'number_of_days': 0.0,
'number_of_hours': 0.0,
'rate': otrate,
'contract_id': contract.id,
}
ot_sequence += 1
# Get Absence data
#
absence_data = get_absence_policies(
contract.policy_group_id, dtDateTime.date(), absence_data)
absence_policy = absence_data['policy']
absence_codes = absence_policy and absence_obj.get_codes(
cr, uid, absence_policy.id, context=context) or []
absence_sequence = 50
for abcode, abname, abtype, abrate, use_awol in absence_codes:
if leaves.get(abcode, False):
continue
if use_awol:
awol_code = abcode
if abtype == 'unpaid':
abrate = 0
elif abtype == 'dock':
abrate = -abrate
leaves[abcode] = {
'name': abname,
'code': abcode,
'sequence': absence_sequence,
'number_of_days': 0.0,
'number_of_hours': 0.0,
'rate': abrate,
'contract_id': contract.id,
}
absence_sequence += 1
# For Leave related computations:
# actual_rest_days: days that are rest days in schedule that
# was actualy used
# scheduled_hours: nominal number of full-time hours for the
# working day. If the employee is scheduled
# for this day we use those hours. If not
# we try to determine the hours he/she
# would have worked based on the schedule
# template attached to the contract.
#
actual_rest_days = sched_obj.get_rest_days(
cr, uid, contract.employee_id.id,
dtDateTime, context=context)
scheduled_hours = detail_obj.scheduled_hours_on_day_from_range(
dtDateTime.date(),
sched_hours_dict)
# If the calculated rest days and actual rest days differ, use
# actual rest days
if actual_rest_days is None:
pass
elif len(rest_days) != len(actual_rest_days):
rest_days = actual_rest_days
else:
for d in actual_rest_days:
if d not in rest_days:
rest_days = actual_rest_days
break
if (scheduled_hours == 0
and dtDateTime.weekday() not in rest_days):
scheduled_hours = sched_tpl_obj.get_hours_by_weekday(
cr, uid, contract.schedule_template_id.id,
dtDateTime.weekday(
),
context=context)
# Actual number of hours worked on the day. Based on attendance
# records.
wh_on_day = self.attendance_dict_hours_on_day(
dtDateTime.date(), working_hours_dict)
# Is today a holiday?
public_holiday = self.holidays_list_contains(
dtDateTime.date(), public_holidays_list)
# Keep count of the number of hours worked during the week for
# weekly OT
if dtDateTime.weekday() == contract.pps_id.ot_week_startday:
wh_in_week = wh_on_day
else:
wh_in_week += wh_on_day
push_lsd = True
if wh_on_day:
done = False
if public_holiday:
_hours, push_lsd = self._book_holiday_hours(
cr, uid, contract, presence_policy, ot_policy,
attendances, holiday_obj, dtDateTime, rest_days,
lsd, wh_on_day, context=context
)
if _hours == 0:
done = True
else:
wh_on_day = _hours
if not done and restday2_ot:
_hours, push_lsd = self._book_restday_hours(
cr, uid, contract, presence_policy, ot_policy,
attendances, dtDateTime, rest_days, lsd,
wh_on_day, context=context)
if _hours == 0:
done = True
else:
wh_on_day = _hours
if not done and restday_ot:
_hours, push_lsd = self._book_weekly_restday_hours(
cr, uid, contract, presence_policy, ot_policy,
attendances, dtDateTime, rest_days, lsd,
wh_on_day, context=context)
if _hours == 0:
done = True
else:
wh_on_day = _hours
if not done and weekly_ot:
for line in ot_policy.line_ids:
if line.type == 'weekly' and (
not line.weekly_working_days
or line.weekly_working_days == 0):
_active_after = float(line.active_after) / 60.0
if wh_in_week > _active_after:
if wh_in_week - _active_after > wh_on_day:
attendances[line.code][
'number_of_hours'
] += wh_on_day
else:
attendances[line.code][
'number_of_hours'
] += wh_in_week - _active_after
attendances[line.code][
'number_of_days'] += 1.0
done = True
if not done and daily_ot:
# Do the OT between specified times (partial OT) first,
# so that it doesn't get double-counted in the regular
# OT.
#
partial_hr = 0
hours_after_ot = wh_on_day
for line in ot_policy.line_ids:
active_after_hrs = float(line.active_after) / 60.0
if (line.type == 'daily'
and wh_on_day > active_after_hrs
and line.active_start_time):
partial_hr = att_obj.partial_hours_on_day(
cr, uid, contract,
dtDateTime, active_after_hrs,
line.active_start_time,
line.active_end_time,
line.tz,
punches_list=self.attendance_dict_list(
working_hours_dict),
context=context)
if partial_hr > 0:
attendances[line.code][
'number_of_hours'] += partial_hr
attendances[line.code][
'number_of_days'] += 1.0
hours_after_ot -= partial_hr
for line in ot_policy.line_ids:
active_after_hrs = float(line.active_after) / 60.0
if (line.type == 'daily'
and hours_after_ot > active_after_hrs
and not line.active_start_time):
attendances[line.code][
'number_of_hours'
] += hours_after_ot - (float(line.active_after)
/ 60.0)
attendances[line.code]['number_of_days'] += 1.0
if not done:
for line in presence_policy.line_ids:
if line.type == 'normal':
normal_hours = self._get_applied_time(
wh_on_day,
line.active_after,
line.duration)
attendances[line.code][
'number_of_hours'] += normal_hours
attendances[line.code]['number_of_days'] += 1.0
done = True
_l.warning('nh: %s', normal_hours)
_l.warning('att: %s', attendances[line.code])
if push_lsd:
lsd.push(True)
else:
lsd.push(False)
leave_type, leave_hours = self.leaves_list_get_hours(
cr, uid, contract.employee_id.id,
contract.id, contract.schedule_template_id.id,
day_from +
timedelta(
days=day),
leaves_list, context=context)
if (leave_type
and (wh_on_day or scheduled_hours > 0
or dtDateTime.weekday() not in rest_days)):
if leave_type in leaves:
leaves[leave_type]['number_of_days'] += 1.0
leaves[leave_type]['number_of_hours'] += (
leave_hours > scheduled_hours
) and scheduled_hours or leave_hours
else:
leaves[leave_type] = {
'name': leave_type,
'sequence': 8,
'code': leave_type,
'number_of_days': 1.0,
'number_of_hours': (
(leave_hours > scheduled_hours)
and scheduled_hours or leave_hours
),
'contract_id': contract.id,
}
elif (awol_code
and (scheduled_hours > 0 and wh_on_day < scheduled_hours)
and not public_holiday):
hours_diff = scheduled_hours - wh_on_day
leaves[awol_code]['number_of_days'] += 1.0
leaves[awol_code]['number_of_hours'] += hours_diff
# Calculate total possible working hours in the month
if dtDateTime.weekday() not in rest_days:
attendances['MAX'][
'number_of_hours'] += normal_working_hours
attendances['MAX']['number_of_days'] += 1
leaves = [value for key, value in leaves.items()]
attendances = [value for key, value in attendances.items()]
res += attendances + leaves
return res
def _partial_period_factor(self, payslip, contract):
dpsFrom = datetime.strptime(payslip.date_from, OE_DATEFORMAT).date()
dpsTo = datetime.strptime(payslip.date_to, OE_DATEFORMAT).date()
dcStart = datetime.strptime(contract.date_start, OE_DATEFORMAT).date()
dcEnd = False
if contract.date_end:
dcEnd = datetime.strptime(contract.date_end, OE_DATEFORMAT).date()
# both start and end of contract are out of the bounds of the payslip
if dcStart <= dpsFrom and (not dcEnd or dcEnd >= dpsTo):
return 1
# One or both start and end of contract are within the bounds of the
# payslip
#
no_contract_days = 0
if dcStart > dpsFrom:
no_contract_days += (dcStart - dpsFrom).days
if dcEnd and dcEnd < dpsTo:
no_contract_days += (dpsTo - dcEnd).days
total_days = (dpsTo - dpsFrom).days + 1
contract_days = total_days - no_contract_days
return float(contract_days) / float(total_days)
def get_utilities_dict(self, cr, uid, contract, payslip, context=None):
res = {}
if not contract or not payslip:
return res
# Calculate percentage of pay period in which contract lies
res['PPF'] = {
'amount': self._partial_period_factor(payslip, contract),
}
# Calculate net amount of previous payslip
imd_obj = self.pool.get('ir.model.data')
ps_obj = self.pool.get('hr.payslip')
ps_ids = ps_obj.search(
cr, uid, [('employee_id', '=', contract.employee_id.id)],
order='date_from', context=context)
res.update({'PREVPS': {'exists': 0,
'net': 0}
})
if ps_ids > 0:
# Get database ID of Net salary category
res_model, net_id = imd_obj.get_object_reference(
cr, uid, 'hr_payroll', 'NET')
ps = ps_obj.browse(cr, uid, ps_ids[-1], context=context)
res['PREVPS']['exists'] = 1
total = 0
for line in ps.line_ids:
if line.salary_rule_id.category_id.id == net_id:
total += line.total
res['PREVPS']['net'] = total
return res
# XXX
# Copied (almost) verbatim from hr_payroll for the sole purpose of adding
# the 'utils' object to localdict.
#
def get_payslip_lines(self, cr, uid, contract_ids, payslip_id, context):
def _sum_salary_rule_category(localdict, category, amount):
if category.parent_id:
localdict = _sum_salary_rule_category(
localdict, category.parent_id, amount)
if category.code in localdict['categories'].dict:
localdict['categories'].dict[category.code] = localdict[
'categories'].dict[category.code] + amount
else:
localdict['categories'].dict[category.code] = amount
return localdict
class BrowsableObject(object):
def __init__(self, pool, cr, uid, employee_id, dict):
self.pool = pool
self.cr = cr
self.uid = uid
self.employee_id = employee_id
self.dict = dict
def __getattr__(self, attr):
return attr in self.dict and self.dict.__getitem__(attr) or 0.0
class InputLine(BrowsableObject):
"""a class that will be used into the python code, mainly
for usability purposes
"""
def sum(self, code, from_date, to_date=None):
if to_date is None:
to_date = datetime.now().strftime('%Y-%m-%d')
self.cr.execute("""\
SELECT sum(amount) as sum
FROM hr_payslip as hp, hr_payslip_input as pi
WHERE hp.employee_id = %s
AND hp.state = 'done'
AND hp.date_from >= %s
AND hp.date_to <= %s
AND hp.id = pi.payslip_id
AND pi.code = %s""", (self.employee_id, from_date, to_date, code))
res = self.cr.fetchone()[0]
return res or 0.0
class WorkedDays(BrowsableObject):
"""a class that will be used into the python code, mainly
for usability purposes
"""
def _sum(self, code, from_date, to_date=None):
if to_date is None:
to_date = datetime.now().strftime('%Y-%m-%d')
self.cr.execute("""\
SELECT sum(number_of_days) as number_of_days,