-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathodoocli.py
executable file
·1137 lines (958 loc) · 37.2 KB
/
odoocli.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
#!/usr/bin/env python3
import argparse
import calendar
import codecs
import csv
import getpass
import io
import os
import smtplib
import sys
import time
import xmlrpc.client
from configparser import ConfigParser
from datetime import datetime, date, timedelta
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
from pathlib import Path
from string import Template
from dotenv import load_dotenv
def memoize(func):
func_name = func.__name__
data = {}
def wrappeada(login, month=None, year=None):
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
if 'user_email' in login:
user = login['user_email']
else:
user = login['username']
dict_key = "{}-{}-{}-{}".format(func_name, user, month, year)
if dict_key in data:
return data[dict_key]
else:
data[dict_key] = list(func(login, month, year))
return data[dict_key]
return wrappeada
def show_resume_now(login, month=None, year=None):
"""
Informe del mes corriente:
"""
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
working_hours_to_today = get_mountly_hours_from_calendar_name(login)
if working_hours_to_today:
# En lugar de horario, lo que tiene es un número de horas mensuales
working_days_total = "--"
working_hours_total = working_hours_to_today
w_hours = count_worked_hours(login)
else:
working_hours_to_today = get_total_hours_from_calendar_name(login)
# En este if haría falta un walrus
if working_hours_to_today:
# En lugar de horario, lo que tiene es un número de horas totales
working_days_total = "--"
working_hours_total = working_hours_to_today
w_hours = count_worked_hours_on_life(login)
if not working_hours_to_today:
w_hours = count_worked_hours(login)
dict_labor_hours_this_month = labor_hours_by_month_day(login, month, year)
today = datetime.now().strftime('%Y-%m-%d')
working_days_total = 0
working_hours_total = 0
working_days_to_today = 0
working_hours_to_today = 0
for day, hours in dict_labor_hours_this_month.items():
if hours > 0:
working_days_total += 1
working_hours_total += hours
if day <= today:
working_days_to_today += 1
working_hours_to_today += hours
print("Resumen {} {}:".format(mes(month), year))
print("Días laborables de este mes:\t{}".format(
working_days_total))
print("Horas laborables de este mes:\t{}".format(
format_hours(working_hours_total)))
print('Horas laborables hasta hoy:\t{}'.format(
format_hours(working_hours_to_today)))
print('Horas trabajadas hasta ahora:\t{}'.format(
format_hours(w_hours)))
print('Horas de diferencia:\t\t{}'.format(
format_hours(w_hours - working_hours_to_today)))
def show_resume(login, month=None, year=None):
"""
Informe del mes pasado como argumento:
"""
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
print("{} {}\n".format(mes(month), year))
print(resume_to_string(login, month, year))
def resume_to_string(login, month=None, year=None):
"""
Informe del mes pasado como argumento:
"""
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
working_hours_total = get_mountly_hours_from_calendar_name(login)
if working_hours_total:
w_hours = count_worked_hours(login, month, year)
working_days_total = "--"
else:
working_hours_total = get_total_hours_from_calendar_name(login)
# En este if haría falta un walrus
if working_hours_total:
# En lugar de horario, lo que tiene es un número de horas totales
working_days_total = "--"
w_hours = count_worked_hours_on_life(login, month, year)
if not working_hours_total:
w_hours = count_worked_hours(login, month, year)
dict_labor_hours_this_month = labor_hours_by_month_day(login, month, year)
working_hours_total = 0
working_days_total = 0
for day, hours in dict_labor_hours_this_month.items():
if hours > 0:
working_hours_total += hours
working_days_total += 1
response = "Resumen {} {}:\n".format(mes(month), year)
response += "Días laborables:\t{}\n".format(working_days_total)
response += "Horas laborables:\t{}\n".format(format_hours(working_hours_total))
response += "Horas trabajadas:\t{}\n".format(format_hours(w_hours))
response += "Horas de diferencia:\t{}\n".format(
format_hours(w_hours - working_hours_total))
return response
def year_summary(login, month=None, year=None):
"""
resumen desde enero hasta el mes indicado
"""
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
prev_mont = month - 1
prev_year = year
if prev_mont == 0:
prev_mont = 12
prev_year -= 1
show_resume_now(login, month, year)
print('\n')
print(accumulated_summary(login, prev_mont, prev_year))
def accumulated_summary(login, month=None, year=None):
"""
resumen desde enero hasta el mes indicado
"""
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
labor_hours = 0
worked_hours = 0
for m in range(1, month + 1):
labor_hours += sum(labor_hours_by_month_day(login, m, year).values())
worked_hours += count_worked_hours(login, m, year)
response = 'Acumulado {} - {} {}:\n'.format(mes(1), mes(month), year)
response += "Horas laborables:\t{}\n".format(format_hours(labor_hours))
response += "Horas trabajadas:\t{}\n".format(format_hours(worked_hours))
response += "Horas de diferencia:\t{}\n".format(
format_hours(worked_hours - labor_hours))
return response
def show_today_summary(login):
l_hours = count_worked_hours_today(login)
print("Horas trabajadas hoy:\t{}\n".format(format_hours(l_hours)))
def accumulated_list_to_csv(login, file_name, month=None, year=None):
file_path = filename(login, file_name)
summary = resume_to_string(login, month, year)
csv_string = accumulated_list_to_csv_string(login, month, year)
with codecs.open(file_path, 'w', 'utf-8') as out:
print(summary, file=out)
print(csv_string, file=out)
def accumulated_list_to_csv_string(login, month=None, year=None):
"""
listado desde enero hasta el mes indicado
"""
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
mem_file = io.StringIO()
csv_writer = csv.writer(mem_file, delimiter=',', quotechar='"')
csv_writer.writerow(('entrada', 'salida', 'horas'))
for m in range(1, month + 1):
for line in get_user_attendance_by_month(login, m, year):
tentry = tlocal(line[0], 'DT')
texit = tlocal(line[1], 'DT')
if line[1]:
hours = line[2]
else:
hours = open_session_worked_hours(login)
csv_writer.writerow(
(tentry, texit, '{}'.format(format_hours(hours))))
return mem_file.getvalue()
def list_to_csv(login, file_name, month=None, year=None):
file_path = filename(login, file_name)
summary = resume_to_string(login, month, year)
csv_string = list_to_csv_string(login, month, year)
with codecs.open(file_path, 'w', 'utf-8') as out:
print(summary, file=out)
print(csv_string, file=out)
def list_to_csv_string(login, month=None, year=None):
mem_file = io.StringIO()
csv_writer = csv.writer(mem_file, delimiter=',', quotechar='"')
csv_writer.writerow(('entrada', 'salida', 'horas'))
for line in get_user_attendance_by_month(login, month, year):
tentry = tlocal(line[0], 'DT')
texit = tlocal(line[1], 'DT')
if line[1]:
hours = line[2]
else:
hours = open_session_worked_hours(login)
csv_writer.writerow((tentry, texit, '{}'.format(format_hours(hours))))
return mem_file.getvalue()
def filename(login, path):
file_path = Path(path)
if 'user_email' in login:
user_name = login['user_email'].split('@')[0]
file_path = Path(file_path.parents[0],
user_name + '-' + file_path.name)
return file_path
def mail_report_accumulated(login, month=None, year=None):
mail_report(login, 'accumulated', month, year)
def mail_report_list(login, month=None, year=None):
mail_report(login, 'list', month, year)
def mail_report(login, mode='list', month=None, year=None):
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
if 'user_email' in login:
mail_to = login['user_email']
else:
mail_to = tuple(get_mail_users(login, login['uid']))[0]
user_name = tuple(get_name_users(login, get_user_by_email(login)))[0]
name = "asistencia{}-{}.csv".format(year, month)
file_name = filename(login, name)
if mode == 'accumulated':
prev_mont = month - 1
prev_year = year
if prev_mont == 0:
prev_mont = 12
prev_year -= 1
past_summary = accumulated_summary(login, prev_mont, prev_year)
current_summary = resume_to_string(login, month, year)
summary = '{}\n\n{}'.format(current_summary, past_summary)
csv_table = accumulated_list_to_csv_string(login, month, year)
else:
summary = resume_to_string(login, month, year)
csv_table = list_to_csv_string(login, month, year)
file_content = summary + csv_table
subject_tpt = "Informe asistencia {} {}".format(mes(month), year)
mail_tpt = ''
mail_tpt_file = os.path.dirname(
os.path.realpath(__file__)) + '/mail_tpt.txt'
if Path(mail_tpt_file).is_file():
with open(mail_tpt_file) as f:
mail_lines = f.readlines()
if mail_lines[0][0:9] == "SUBJECT: ":
subject_tpt = mail_lines[0][9:].rstrip()
mail_lines.remove(mail_lines[0])
mail_tpt = ''.join(mail_lines)
terms = {
'user_name': user_name,
'user_email': mail_to,
'year': year,
'month': month,
'month_name': mes(month),
'filename': file_name,
'summary': summary,
'csv_table': csv_table
}
body_text = Template(mail_tpt).safe_substitute(terms)
subject = Template(subject_tpt).safe_substitute(terms)
send_mail(mail_to, subject, body_text, file_name, file_content)
def list_to_screen(login, month=None, year=None):
print("Fecha | Entrada | Salida | Horas")
for line in get_user_attendance_by_month(login, month, year):
if line[1]:
print('{} | {} | {} | {}'.format(
tlocal(line[0], 'D'),
tlocal(line[0], 'T'),
tlocal(line[1], 'T'),
format_hours(line[2])))
else:
print('{} | {} | {} | {}'.format(
tlocal(line[0], 'D'),
tlocal(line[0], 'T'),
tlocal(line[1], 'T'),
format_hours(open_session_worked_hours(login))))
########################################################################
#
# Holidays, weekends and vacations
#
########################################################################
def public_holidays(login, year):
"""
Festivos de un año nacionales y provinciales
"""
user_city = get_state_by_address(login, get_address_id_employee(login))
holidays = login['conn'].execute_kw(
login['db'],
login['uid'],
login['password'],
'hr.holidays.public',
'search_read',
[[('year', '=', year)]],
{'fields': ['line_ids']})
for i in holidays[0]['line_ids']:
hly = get_holiday(login, i)
if not hly["state_ids"] or user_city in hly["state_ids"]:
yield get_holiday(login, i)
def get_holiday(login, id_holiday):
holidays = login['conn'].execute_kw(
login['db'],
login['uid'],
login['password'],
'hr.holidays.public.line',
'search_read',
[[('id', '=', id_holiday)]],
{})
return holidays[0]
@memoize
def holidays_by_month(login, month=None, year=None):
"""
Listado de festivos
"""
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
for day in public_holidays(login, year):
if int(day['date'].split('-')[1]) == month:
yield day['date']
@memoize
def get_vacances_by_month(login, month=None, year=None):
"""
Listado de días de vacaciones
"""
user_id = get_user_id(login)
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
vacances = login['conn'].execute_kw(
login['db'],
login['uid'],
login['password'],
'hr.holidays',
'search_read',
[[]],
{})
for i in vacances:
if i['employee_id'] and i['employee_id'][0] == user_id:
if i['date_from'] and i['date_to'] and i['state'] != 'refuse':
d_init = str_to_localtime(i['date_from'])
d_end = str_to_localtime(i['date_to'])
if d_init.tm_year == year or d_end.tm_year == year:
sdate = date(*d_init[:3])
edate = date(*d_end[:3])
delta = edate - sdate
for inc in range(delta.days + 1):
day = sdate + timedelta(days=inc)
if day.year == year and day.month == month:
yield "{}-{:02d}-{:02d}".format(day.year,
day.month,
day.day)
########################################################################
#
# Work
#
########################################################################
@memoize
def get_user_attendance_by_month(login, month=None, year=None):
user_id = get_user_id(login)
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
date_filter = "{}-{:02d}-%".format(year, month)
try:
attendance = login['conn'].execute_kw(
login['db'],
login['uid'],
login['password'],
'hr.attendance',
'search_read',
[[('employee_id', '=', user_id),
('check_in', '=like', date_filter)]],
{'fields': ['employee_id', 'check_in', 'check_out',
'worked_hours']})
except TypeError:
return None
else:
for e in attendance:
yield e['check_in'], e['check_out'], e['worked_hours']
def count_worked_hours(login, month=None, year=None):
"""
Horas trabajadas hasta el momento (se cuentan las de las sesión abierta)
"""
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
total = 0
if month == int(datetime.now().month) and year == int(datetime.now().year):
total = open_session_worked_hours(login)
for e in get_user_attendance_by_month(login, month, year):
total += e[2]
return total
def count_worked_hours_today(login):
"""
Horas trabajadas hoy (se cuentan las de las sesión abierta)
"""
today = datetime.now().strftime('%Y-%m-%d')
total = open_session_worked_hours(login)
for e in get_user_attendance_by_month(login):
if e[1] and e[1][0:10] == today:
total += e[2]
return total
def open_session_worked_hours(login):
"""
Horas trasncurridas desde la última sesión abierta y no cerrada
"""
today = int(datetime.now().day)
year = int(datetime.now().year)
month = int(datetime.now().month)
for e in get_user_attendance_by_month(login, month, year):
if not e[1] and str_to_localtime(e[0]).tm_mday == today:
delta = datetime.now() - datetime(*str_to_localtime(e[0])[:6])
return delta.total_seconds() / 3600
return 0
########################################################################
#
# Utilities
#
########################################################################
def txt_date(idatetime, mode='DT'):
if mode == 'T':
date_format = "%H:%M:%S"
elif mode == 'D':
date_format = "%Y-%m-%d"
else:
date_format = "%Y-%m-%d %H:%M:%S"
try:
txt = time.strftime(date_format, idatetime)
except TypeError:
txt = '--------'
return txt
def str_to_localtime(datetime_str):
try:
time_tuple = time.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
gm = calendar.timegm(time_tuple)
except TypeError:
return False
else:
return time.localtime(gm)
def tlocal(datetime_str, mode='DT'):
return txt_date(str_to_localtime(datetime_str), mode)
def mes(month):
"""
Retorna el nombre del mes pasado como argumento
"""
return ('Enero',
'Febrero',
'Marzo',
'Abril',
'Mayo',
'Junio',
'Julio',
'Agosto',
'Septiembre',
'Octubre',
'Noviembre',
'Diciembre')[month - 1]
def format_hours(time_decimal):
sign = '-' if float(time_decimal) < 0 else ' '
h = int(abs(time_decimal))
m = int((abs(time_decimal) * 60) % 60)
s = int((abs(time_decimal) * 3600) % 60)
return "{}{:02}:{:02}:{:02}".format(sign, h, m, s)
def get_args_date(month, year):
if month:
new_month, new_year = month, year
if not year:
year = datetime.now().year
if month < 0:
current = int(datetime.now().month)
result = divmod(current - 1 + month, 12)
new_month = result[1] + 1
new_year = year + result[0]
elif month == 0:
new_month = None
new_year = None
elif 0 < month < 13:
new_month = month
new_year = year
elif args.month > 12:
sys.exit("Mes fuera de rango")
return new_month, new_year
else:
return month, year
def get_user_id(login):
"""
Retorna el id en hr.employee del usuario logeado.
Es un poco ñapa mientras vemos cómo filtrar la query
"""
user_to_find = get_user_by_email(login) if 'user_email' in login else \
login['uid']
if not user_to_find:
sys.exit('El usuario no existe')
users = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'hr.employee',
'search_read',
[],
{'fields': ['user_id', 'id']})
for user in users:
if user['user_id'][0] == user_to_find:
return user['id']
def get_user_by_email(login):
"""
Retorna el id del usaurio (en res.user)
a partir del email contenido en el campo 'user_email' de login (si lo hay).
"""
if 'user_email' in login:
users = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'res.users',
'search_read',
[[('email', '=',
login['user_email'])]],
{'fields': ['email']})
for user in users:
return user['id']
return None
def get_state_by_address(login, address_id):
"""
Obtiene el código de provicia (state_id) a partir de un address_id
"""
states = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'res.partner',
'search_read',
[[('id', '=',
address_id)]],
{'fields': ["state_id"]})
return states[0]["state_id"][0]
def get_address_id_employee(login):
"""
Obtiene el address_id de un empleado
"""
user_id = get_user_id(login)
addresses = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'hr.employee',
'search_read',
[[('id', '=',
user_id)]],
{'fields': ["address_id"]})
return addresses[0]['address_id'][0]
def get_mail_users(login, user_id=None):
"""
Retorna los emails de todos los usuarios
o el de la ID que se le pase
"""
if user_id:
users = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'res.users',
'search_read',
[[('id', '=',
user_id)]],
{'fields': ['email']})
else:
users = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'res.users',
'search_read',
[],
{'fields': ['email']})
for user in users:
yield user['email']
def get_name_users(login, user_id=None):
"""
Retorna los nombres de todos los usuarios
o el de la ID que se le pase
"""
if user_id:
users = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'res.users',
'search_read',
[[('id', '=',
user_id)]],
{'fields': ['display_name']})
else:
users = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'res.users',
'search_read',
[],
{'fields': ['display_name']})
for user in users:
yield user['display_name']
def send_mail(mail_to, subject, message, file_name, file_data):
mail_server = os.environ.get('ODOOCLI_MAIL_SERVER')
mail_port = os.environ.get('ODOOCLI_MAIL_PORT')
mail_tls = os.environ.get('ODOOCLI_MAIL_TLS')
mail_user = os.environ.get('ODOOCLI_MAIL_USER')
mail_from = os.environ.get('ODOOCLI_MAIL_FROM') or mail_user
mail_password = os.environ.get('ODOOCLI_MAIL_PASSWORD')
mail_reply_to = os.environ.get('ODOOCLI_MAIL_REPLY_TO')
mail_cc = os.environ.get('ODOOCLI_MAIL_CC')
mail_bcc = os.environ.get('ODOOCLI_MAIL_BCC')
mail_to_list = [mail_to]
msg = MIMEMultipart()
msg['From'] = mail_from
msg['To'] = mail_to
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
if mail_cc:
msg['Cc'] = mail_cc
mail_to_list.append(mail_cc)
if mail_bcc:
mail_to_list.append(mail_bcc)
if mail_reply_to:
msg.add_header('reply-to', mail_reply_to)
msg.attach(MIMEText(message))
part = MIMEBase('application', "octet-stream")
part.set_payload(file_data)
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="{}"'.format(file_name))
msg.attach(part)
smtp = smtplib.SMTP(mail_server, mail_port)
if mail_tls:
smtp.starttls()
smtp.login(mail_user, mail_password)
smtp.sendmail(mail_from, mail_to_list, msg.as_string())
smtp.quit()
def bulk(login, mails, function, *argus):
if not mails:
mails = get_mail_users(login)
for user in mails:
new_login_data = dict(login)
new_login_data['user_email'] = user
if count_worked_hours(new_login_data, argus[-2], argus[-1]) or count_worked_hours_on_life(new_login_data, argus[-2], argus[-1]):
print('Procesando', user)
function(new_login_data, *argus)
else:
print('Se omite', user)
##################################################
#
# Todas estas funciones son para sacar el horario semanal
#
##################################################
def get_horario_id_employee(login):
"""
Retrona la ID del horario del trabajador
"""
user_id = get_user_id(login)
calendar = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'hr.employee',
'search_read',
[[('id', '=',
user_id)]],
{'fields': ['calendar_id']})
if calendar[0]['calendar_id']:
return calendar[0]['calendar_id'][0]
else:
return None
def get_mountly_hours_from_calendar_name(login):
"""
Retorna las horas mensuales, si el nombre delo horario las menciona
"""
user_id = get_user_id(login)
hours = None
calendar = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'hr.employee',
'search_read',
[[('id', '=',
user_id)]],
{'fields': ['calendar_id']})
if calendar[0]['calendar_id']:
calendar_name = calendar[0]['calendar_id'][-1]
cachos = calendar_name.split()
if len(cachos) > 1 and (cachos[1].lower() == "mensual" or cachos[1].lower() == "mensuales"):
try:
hours = float(cachos[0])
except ValueError:
pass
return hours
def get_total_hours_from_calendar_name(login):
"""
Retorna las horas totales, si el nombre delo horario las menciona
"""
user_id = get_user_id(login)
hours = None
calendar = login['conn'].execute_kw(login['db'],
login['uid'],
login['password'],
'hr.employee',
'search_read',
[[('id', '=',
user_id)]],
{'fields': ['calendar_id']})
if calendar[0]['calendar_id']:
calendar_name = calendar[0]['calendar_id'][-1]
cachos = calendar_name.split()
if len(cachos) > 1 and (cachos[1].lower() == "total" or cachos[1].lower() == "totales"):
try:
hours = float(cachos[0])
except ValueError:
pass
return hours
def get_jornada(login):
"""
Retorna una lista con las IDs de las horas diarias del horario del trabajador
Necesita permisos
"""
horario_id = get_horario_id_employee(login)
if horario_id:
resp = login['conn'].execute_kw(
login['db'],
login['uid'],
login['password'],
'resource.calendar',
'search_read',
[[('id', '=',
horario_id)]],
{'fields': ['attendance_ids']})
return resp[0]['attendance_ids']
return None
def get_week_labor_hours(login):
"""
Retorna una lista con las horas laborables de cada día de la semana.
Lunes es el cero, domingo el seis
Necesita permisos
"""
lista_ids = get_jornada(login)
horario_semana = [0] * 7
if lista_ids:
resp = login['conn'].execute_kw(
login['db'],
login['uid'],
login['password'],
'resource.calendar.attendance',
'search_read',
[[('id', 'in',
lista_ids)]],
{'fields': ['dayofweek', 'hour_from', 'hour_to']})
for day in resp:
horario_semana[int(day['dayofweek'])] = float(day['hour_to']) - float(day['hour_from'])
return horario_semana
def labor_hours_by_month_day(login, month=None, year=None):
"""
Retorna un diccionario con las horas laborables de cada día del mes.
{"2022-02-01": 8.0, ...}
Necesita permisos
"""
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
week_labor_hours = get_week_labor_hours(login)
holidays = tuple(holidays_by_month(login, month, year))
vacations = tuple(get_vacances_by_month(login, month, year))
labor_hours_by_day = {}
cal = calendar.Calendar()
weekday = 0
for day in cal.itermonthdays(year, month):
if day != 0:
key = "{}-{:02d}-{:02d}".format(year, month, day)
if key not in holidays and key not in vacations:
labor_hours_by_day["{}-{:02d}-{:02d}".format(year, month, day)] = week_labor_hours[weekday]
weekday += 1
if weekday == 7:
weekday = 0
return labor_hours_by_day
def count_worked_hours_on_life(login, month=None, year=None):
total = 0
if month == int(datetime.now().month) and year == int(datetime.now().year):
total = open_session_worked_hours(login)
for e in get_user_attendance_on_life(login, month, year):
total += e[2]
return total
@memoize
def get_user_attendance_on_life(login, month=None, year=None):
user_id = get_user_id(login)
if year is None:
year = int(datetime.now().year)
if month is None:
month = int(datetime.now().month)
month += 1
if month == 13:
month = 1
year += 1
date_filter = "{}-{:02d}-01 00:00:00".format(year, month)
try:
attendance = login['conn'].execute_kw(
login['db'],
login['uid'],
login['password'],
'hr.attendance',
'search_read',
[[('employee_id', '=', user_id),
('check_in', '<', date_filter)
]],
{'fields': ['employee_id', 'check_in', 'check_out',
'worked_hours']})
except TypeError:
return None
else:
for e in attendance:
yield e['check_in'], e['check_out'], e['worked_hours']
########################################################################
#
# Main
#
########################################################################