~inddiana/sisb/edgar_xml_islr_nomina_fecha_contable

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
#-*- coding:utf-8 -*-

import time
from datetime import date
from datetime import datetime
from datetime import timedelta
from dateutil import relativedelta
from time import strftime
import netsvc
from osv import fields, osv
import tools
from tools.translate import _
import decimal_precision as dp
import math
from tools.safe_eval import safe_eval as eval
import logging
import calendar

class hr_liquidacion(osv.osv):
    '''
        Cálculo de liquidaciones
    '''
    _name = 'hr.liquidacion'
    _description = 'Cálculo de liquidaciones'
    
    def _tiempo_servicio(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        liq_brw = self.browse(cr, uid, ids)
        
        for liq in liq_brw:
            desde = datetime.strptime(liq.start_rel_lab,"%Y-%m-%d")
            hasta = datetime.strptime(liq.date,"%Y-%m-%d")
            
            if hasta.month == desde.month:
                if hasta.day < desde.day:
                    anos = hasta.year - desde.year - 1
                    meses = 12 - desde.month + hasta.month - 1
                    if hasta.month == 1:
                        dias = calendar.monthrange(hasta.year-1,12)[1] - \
                          desde.day + hasta.day
                    else:
                        dias = calendar.monthrange(hasta.year,hasta.month-1)[1] - \
                          desde.day + hasta.day 
                else: 
                    anos = hasta.year - desde.year
                    meses = desde.month - hasta.month
                    dias =  hasta.day - desde.day
                    
            elif hasta.month < desde.month:
                anos = hasta.year - desde.year - 1
                if hasta.day < desde.day:
                    meses = 12 - desde.month + hasta.month - 1
                    if hasta.month == 1:
                        dias = calendar.monthrange(hasta.year-1,12)[1] - \
                          desde.day + hasta.day
                    else:
                        dias = calendar.monthrange(hasta.year,hasta.month-1)[1] - \
                          desde.day + hasta.day 
                else:
                    meses = 12 - desde.month + hasta.month
                    dias =  hasta.day - desde.day 
                    
            else:
                anos = hasta.year - desde.year
                meses = hasta.month - desde.month
                if hasta.day < desde.day:
                    meses = hasta.month - desde.month - 1
                    if hasta.month == 1:
                        dias = calendar.monthrange(hasta.year-1,12)[1] - \
                          desde.day + hasta.day
                    else:
                        dias = calendar.monthrange(hasta.year,hasta.month-1)[1] - \
                          desde.day + hasta.day
                else:
                    meses = hasta.month - desde.month
                    dias =  hasta.day - desde.day
            
            res[liq.id] = str(anos) + ' Año(s) ' + str(meses) + ' Mes(es) ' + \
              str(dias) + ' Día(s)'
            
        return res
        
    def _dias_antiguedad(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        liq_brw = self.browse(cr, uid, ids)
        
        #Busqueda del concepto que se definio como Fecha ultima Ley del Trabajo
        parameter_obj = self.pool.get('hr.parameters')
        param_fecha_ultima_ley_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'fecha_ultima_ley')])
        if not param_fecha_ultima_ley_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parámetro \
              definido para Fecha ultima Ley del Trabajo. Ir a \
              la pestaña Configuración -> Configuraciones de nómina -> \
              Parámetros de nómina y registrar un parámetro de tipo \
              Fecha ultima Ley del Trabajo'))

        fecha_ultima_ley = datetime.strptime(parameter_obj.browse(cr, 
          uid, param_fecha_ultima_ley_id)[0].date_prest,"%Y-%m-%d")
        
        for liq in liq_brw:
            desde = datetime.strptime(liq.start_rel_lab,"%Y-%m-%d")
            hasta = datetime.strptime(liq.date,"%Y-%m-%d")
            
            anos_antiguedad = hasta.year - desde.year 
            meses_antiguedad = hasta.month - desde.month
            if desde >= fecha_ultima_ley:
                meses_total = (anos_antiguedad*12 + meses_antiguedad)
            elif fecha_ultima_ley.year == desde.year and \
              fecha_ultima_ley.month == desde.month+1:
                meses_total = (anos_antiguedad*12 + meses_antiguedad)-1
            elif fecha_ultima_ley.year == desde.year and \
              fecha_ultima_ley.month == desde.month+2:
                meses_total = (anos_antiguedad*12 + meses_antiguedad)-2
            else:
                meses_total = (anos_antiguedad*12 + meses_antiguedad)-3
                            
            res[liq.id] = meses_total*5
            
        return res
        
    _columns = {
        'name': fields.char('Descripcion', size=256),
        'employee_id': fields.many2one('hr.employee', 'Trabajador', 
          required=True),
        'start_rel_lab': fields.related('employee_id', 'start_rel_lab', 
          type='date', relation='hr.employee', string='Fecha ingreso', 
          store=True),
        'date': fields.date('Fecha egreso', required=True),
        'tiempo_servicio': fields.function(_tiempo_servicio, method=True, 
          string='Tiempo de servicio', type='char', store=False),
        'dias_antiguedad': fields.function(_dias_antiguedad, method=True, 
          string='Dias de antiguedad', type='char', store=False),
        'state': fields.selection([
                ('borrador', 'Borrador'),
                ('calculado', 'Calculado'),
                ('aprobado', 'Aprobado'),
                ('cancelado', 'Cancelado'),
            ], 'Estado', select=True, readonly=True, size=256),
        'linea_liquidacion_ids': fields.one2many('hr.linea.liquidacion', 
          'liquidacion_id', 'Líneas de Liquidacion', ondelete='cascade'),
        'note': fields.text('Nota'),
    }
    
    _order = "date desc"
    
    _defaults = {
        'state': 'borrador',
    }
    
    def _check_prestaciones(self, cr, uid, ids, context=None):
        for liq in self.browse(cr, uid, ids, context=context):
            if liq.employee_id.state <> 'egresado':
                fecha_liquidacion = datetime.strptime(liq.date,"%Y-%m-%d")
                periodo = self.pool.get('hr.period').search(cr, uid, 
                  [('date_start','<=', fecha_liquidacion), 
                  ('date_end','>=', fecha_liquidacion), 
                  ('type','=',liq.employee_id.hr_payroll_id.hr_payment_calendar_id.type)])
                if not periodo:
                    raise osv.except_osv(_('ERROR!'), _('No hay un periodo\
                      asociado a la fecha de la linea de liquidación'))
                
                periodo = self.pool.get('hr.period').browse(cr, uid, periodo[0])
                
                last_period = False
                month = periodo.hr_month_id
                if month.month_year == 1: 
                    # Cunsultar el ultimo periodo del calendario anterior
                    year_old = self.pool.get('hr.year').search(cr, uid, 
                      [('year', '=', month.hr_year_id.year-1)])
                    if year_old: 
                        # Si no existe año anterior el sistema esta 
                        # comenzando y no hay año anterior generado
                        year_old = year_old[0]
                        calendar_old_id = self.pool.get('hr.payment.calendar').search(cr, 
                          uid, [('type', '=', periodo.hr_payment_calendar_id.type),
                          ('hr_year_id', '=', year_old),('active', '=', False)])
                        calendar_old_brw = self.pool.get('hr.payment.calendar').browse(cr, 
                          uid, calendar_old_id)
                        if not calendar_old_brw:
                            raise osv.except_osv(_('Error!'),_('No existe un \
                              calendario anterior para obtener el ultimo período'))

                        last_period = (calendar_old_brw[0].hr_period_ids[-1]).id

                else:
                    last_month = self.pool.get('hr.month').search(cr, uid,
                      [('month_year','=', month.month_year - 1),
                      ('hr_year_id','=', month.hr_year_id.id)])
                    last_period = self.pool.get('hr.period').search(cr, uid, 
                      [('hr_month_id','=', last_month),
                      ('last_period_month','=', True)])
                
                if last_period:
                    process_in_last_period_ids = self.pool.get('hr.process').search(cr, 
                      uid, [('hr_period_ids','=', last_period),
                      ('type','=','prestaciones'), ('state','=','done')])
                    payslip_prest = self.pool.get('hr.payslip').search(cr, 
                      uid, [('employee_id','=',liq.employee_id.id),
                      ('hr_process_id','in',process_in_last_period_ids)])
                    if not payslip_prest:
                        return False
            else:
                return True
                
        return payslip_prest
    
    def _check_dates(self, cr, uid, ids, context=None):
        for liq in self.browse(cr, uid, ids, context=context):
            if liq.date < liq.start_rel_lab:
                return False
        return True
                        
    _constraints = [
        (_check_prestaciones, "Para crear una Liquidación se dede haber \
          generado el proceso de Prestaciones Sociales del mes anterior", []),
        (_check_dates, "Fecha de egreso debe ser mayor a la Fecha de ingreso", 
          ['date', 'start_rel_lab'])
        ]
        
hr_liquidacion()

class hr_motivos_liquidacion(osv.osv):
    '''
        Motivos de Liquidacion
    '''
    _name = 'hr.motivos.liquidacion'
    _description = 'Motivos de Liquidacion'
    
    _columns = {
        'name': fields.char('Motivo liquidación', size=64, required=True),
        'description': fields.text('Description'),
    }

hr_motivos_liquidacion()

class hr_linea_liquidacion(osv.osv):
    '''
        Propuesta de liquidacion
    '''
    _name = 'hr.linea.liquidacion'
    _description = 'Propuesta de liquidacion'
    _logger = logging.getLogger('hr.linea.liquidacion')
    
    def _compute_sum(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        linea_liq_brw = self.browse(cr, uid, ids)
        
        for line in linea_liq_brw:
            total = 0.0
            asignaciones = 0.0
            deducciones = 0.0
            for l in line.payslip_line_ids:
                if l.appears_on_payslip:
                    if (l.salary_rule_id and l.salary_rule_id.concept_id.type_calc == \
                      'allocation') or (l.attribute_id and \
                      l.attribute_id.concept_id.type_calc == 'allocation'):
                        asignaciones += (l.quantity * l.amount)
                    else:
                        deducciones += (l.quantity * l.amount)

            total = round(asignaciones - deducciones, 2)
            res[line.id] = {
                'total_allocations': asignaciones,
                'total_deductions': deducciones,
                'total': total,
            }
            
        return res
    
    def _sueldo_prestaciones(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        liq_brw = self.browse(cr, uid, ids)
        sueldo = 0.0
        #Busqueda del concepto que se definió como Concepto sueldo prestaciones
        parameter_obj = self.pool.get('hr.parameters')
        param_sueldo_prest_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'concepto_dias_prest')])
        if not param_sueldo_prest_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parámetro \
              definido para Concepto calculo de prestaciones mensual. Ir a \
              la pestaña Configuración -> Configuraciones de nómina -> \
              Parámetros de nómina y registrar un parámetro de tipo \
              Concepto calculo de prestaciones mensual'))

        cpt_dias_prest = parameter_obj.browse(cr, uid, 
          param_sueldo_prest_id)[0].concept_prest_id
        value = parameter_obj.browse(cr, uid, 
          param_sueldo_prest_id)[0].value
        for liq in liq_brw:
            payslip_line_prest_id = self.pool.get('hr.payslip.line').search(cr, uid, 
              [('employee_id','=',liq.employee_id.id),
              ('slip_id.type_process','=','prestaciones'),
              ('concept_id','=',cpt_dias_prest.id)], order='slip_id desc')
            if payslip_line_prest_id:
                sueldo = self.pool.get('hr.payslip.line').browse(cr, uid, 
                  payslip_line_prest_id[0]).total
                res[liq.id] = sueldo/value
            else:
                res[liq.id] = liq.employee_id.salary \
                  if liq.employee_id.type_employee == 'obrero' else \
                  liq.employee_id.salary/30
        return res
        
    def _sueldo_vacaciones(self, cr, uid, ids, field_name, arg, context=None):
        res = {}
        linea_liq_brw = self.browse(cr, uid, ids)
        sueldo = 0.0
        
        for linea in linea_liq_brw:
            empleado = linea.employee_id
            fecha_liquidacion = datetime.strptime(linea.liquidacion_id.date,"%Y-%m-%d")
            periodo = self.pool.get('hr.period').search(cr, uid, 
              [('date_start','<=', fecha_liquidacion), 
              ('date_end','>=', fecha_liquidacion), 
              ('type','=',empleado.hr_payroll_id.hr_payment_calendar_id.type)])
            if not periodo:
                raise osv.except_osv(_('ERROR!'), _('No hay un periodo \
                  asociado a la fecha de la linea de liquidación'))
            
            periodo = self.pool.get('hr.period').browse(cr, uid, periodo[0])
        
            num_periodos = 2 if periodo.type == 'mensual' and \
              (empleado.type_employee == 'empleado' or \
              empleado.type_employee == 'obrero') else 0  
            num_periodos = 6 if periodo.type == 'mensual' and \
              empleado.type_employee == 'vendedor' else num_periodos  
            num_periodos = 4 if periodo.type == 'diario' and \
              (empleado.type_employee == 'empleado' or \
              empleado.type_employee == 'obrero') else num_periodos  
            num_periodos = 12 if periodo.type == 'diario' and \
              empleado.type_employee == 'vendedor' else num_periodos
            acumulado = self.get_cal_concept([cr, uid], empleado, ['SVC'], 
              ['nomina'], num_periodos, [])[0]
            if empleado.type_employee == 'empleado':
                sueldo_vac = acumulado
                sueldo = sueldo_vac/30 if sueldo_vac > empleado.salary \
                  else empleado.salary/30
            elif empleado.type_employee == 'obrero':
                sueldo = acumulado/4/7
            else:
                sueldo_vac = acumulado/3
                sueldo = sueldo_vac/30 if sueldo_vac > empleado.salary \
                  else empleado.salary/30
            
            res[linea.id] = sueldo
            
        return res
        
    _columns = {
        'name': fields.char('Descripcion', size=256),
        'liquidacion_id': fields.many2one('hr.liquidacion', 'Liquidación', 
          required=True, ondelete='cascade'),
        'employee_id': fields.related('liquidacion_id', 'employee_id', 
          type='many2one', relation='hr.employee', string='Empleado', store=True),
        'date': fields.date('Fecha', readonly=True),
        'type': fields.many2one('hr.motivos.liquidacion', 
          'Motivo Liquidacion Prestaciones Sociales', required=True),
        'state': fields.selection([
                ('borrador', 'Borrador'),
                ('calculado', 'Calculado'),
                ('aprobado', 'Aprobado'),
                ('cancelado', 'Cancelado'),
            ], 'Estado', select=True, size=256),
        'total_allocations': fields.function(_compute_sum, method=True, 
          string='Asignaciones', type='float', store=False, multi='totals'),
        'total_deductions': fields.function(_compute_sum, method=True, 
          string='Deducciones', type='float', store=False, multi='totals'),
        'total': fields.function(_compute_sum, method=True, string='Total',
          type='float', store=False, multi='totals'),
        'sueldo_prestaciones': fields.function(_sueldo_prestaciones, 
          method=True, string='Sueldo prestaciones', type='float', store=False),
        'sueldo_vacaciones': fields.function(_sueldo_vacaciones, method=True, 
          string='Sueldo vacaciones', type='float', store=False),
        'fecha_aprobacion': fields.date('Fecha aprobacion', readonly=True),
    }
    
    _order = "employee_id, id desc"
        
    _defaults = {
        'date': lambda *args: strftime('%Y-%m-%d'),
        'state': 'borrador',
    }

    def loan_update(self, cr, uid, linea_liq, aprobar_linea, context):
        ''' Esta funcion verifica las lineas de pago dentro de la linea 
            de liquidacion para que en caso de provenir
            de un pretamo, este sea acualizado dependiendo de si se 
            esta aprobando una linea de liquidacion
            o se esta devolviendo
        '''
        if aprobar_linea: # Se esta aprobando una linea de liquidacion
            for line_brw in linea_liq.payslip_line_ids:
                ''' Si la linea viene de un atributo y este a su vez 
                    proviene de un prestamo (hr.loan) el prestamo se debe 
                    sobreescribir para actualizar la deuda restante, 
                    el numero de cuotas pagadas por el empleado y desactivarlo. 
                    Ademas se debe pasar a inactivo el atributo de 
                    asignacion que se pudo haber creado con el prestamo 
                    en caso de que este activo
                 '''
                if line_brw.attribute_id.allocation_loan_ids:
                    for loan in line_brw.attribute_id.allocation_loan_ids:
                        attr = loan.attr_allocation_id
                        if attr:
                            self.pool.get('hr.attribute').write(cr, uid, 
                              attr.id, {'active':False}, context)
                                
                if line_brw.attribute_id.loan_ids:
                    vals_loan = {}
                    for loan in line_brw.attribute_id.loan_ids:
                        vals_loan['paid_amount'] = loan.amount
                        self.pool.get('hr.loan').write(cr, uid, loan.id, 
                          vals_loan, context)
                        
                        '''Se debe pasar a inactivo el atributo'''
                        vals_loan['date_end'] = datetime.now().strftime('%Y-%m-%d')
                        vals_loan['active'] = False 
                        self.pool.get('hr.loan').write(cr, uid, loan.id, 
                          vals_loan, context)
                        self.pool.get('hr.attribute').write(cr, uid, 
                          loan.created_attr_id.id, {'active':False, 
                          'date_end':datetime.now().strftime('%Y-%m-%d')}, context)
                                        
        else: # Se esta devolviendo una linea de liquidacion
            for line_brw in linea_liq.payslip_line_ids:
                ''' Si la linea viene de un atributo y este a su vez proviene 
                    de un prestamo (hr.loan) el prestamo se debe sobreescribir
                    para actualizar la deuda restante, el numero de 
                    cuotas pagadas por el empleado y activarlo. 
                    Ademas se debe pasar a activo el atributo de 
                    asignacion que se pudo haber creado con el prestamo 
                    en caso de que este 
                 '''
                
                loan_ids = self.pool.get('hr.loan').search(cr, uid, 
                  [('employee_id','=',linea_liq.employee_id.id),
                  ('created_attr_id','=', line_brw.attribute_id.id), 
                  ('active','=',False)]) + self.pool.get('hr.loan').search(cr, 
                  uid, [('employee_id','=',linea_liq.employee_id.id),
                  ('created_attr_id','=', line_brw.attribute_id.id)])

                if loan_ids:
                    vals_loan = {}
                    for loan in self.pool.get('hr.loan').browse(cr, uid, 
                      loan_ids, context):
                        vals_loan['paid_amount'] = loan.amount_quota * loan.paid_quotas
                        vals_loan['date_end'] = None
                        vals_loan['active'] = True
                        self.pool.get('hr.loan').write(cr, uid, loan.id, 
                          vals_loan, context)
                        '''Si el atributo de habia pasado a inactivo porque l
                        a deuda se habia cancelado conpleta,
                        el atributo debe ser pasado nuevamente a activo'''
                        if not loan.created_attr_id.active:
                            self.pool.get('hr.attribute').write(cr, uid, 
                              loan.created_attr_id.id, {'active':True, 
                              'date_end':None}, context)

    def creacion_asiento(self, cr, uid, linea_liq, payslip_line_ids, context=None):
        ''' 
        Metodo para la creacion de los asientos contables
        @param linea_liq: Propuesta de liquidacion que se esta aprobando 
        (objeto browse hr.linea.liquidacion)
        @param payslip_line_ids: Lineas de pago de la propuesta de liquidacion
        (lista de objetos browse hr.payslip.line)
        @return : Lista de ids de asientos creados
        '''
        obj_moves = self.pool.get('account.move')
        obj_acm = self.pool.get('account.move.line')
        obj_period = self.pool.get('account.period')
        obj_company = self.pool.get('res.company')
        obj_hr_acct = self.pool.get('hr.account')
        
        total_dict = {}
        contrapartida_dict = {}
        fecha = datetime.now()
        payrolls = []
        # Creamos las tuplas para totalizar los account.move.lines
        
        # Comprobar la existencia de la configuracion contable para todos 
        # los conceptos
        self._logger.info("Comprobar la existencia de la configuracion \
          contable para todos los conceptos")
        for line in payslip_line_ids:
            concept = line.salary_rule_id.concept_id if line.salary_rule_id \
              else line.attribute_id.concept_id
            department = line.employee_id.department_id
            payroll = line.employee_id.hr_payroll_id
            
            account_id = obj_hr_acct.search(cr, uid, 
              [('concept_id', '=', concept.id),
              ('analytic_account_id', '=', department.departament_analytic_account_id.id),
              ('payroll_id', '=', payroll.id)])

            if not account_id:
                raise osv.except_osv(_('Error!'), 
                  _('No existe una configuracion contable para el concepto\
                  %s, cuenta analitica %s y nomina %s. Para verificar ir a\
                  Talento Humano -> Configuracion -> Contabilidad nomina.')
                  % (concept.name, 
                  department.departament_analytic_account_id.complete_name, payroll.name))
                  
        for line in payslip_line_ids:
            concept = line.salary_rule_id.concept_id if line.salary_rule_id \
              else line.attribute_id.concept_id
            department = line.employee_id.department_id
            payroll = line.employee_id.hr_payroll_id
            payrolls.append(payroll.id)
            
            account_id = obj_hr_acct.search(cr, uid, 
              [('concept_id', '=', concept.id),
              ('analytic_account_id', '=', department.departament_analytic_account_id.id),
              ('payroll_id', '=', payroll.id)])

            account = obj_hr_acct.browse(cr, uid, account_id)[0]
            
            concept_id = account.concept_id
            payroll_id = account.payroll_id
            account_id = account.account_id
            type_calc = concept.type_calc
            partner_id = line.employee_id.company_id.partner_id
            
            if not account_id.user_type.code in ['expense']:
                analytic_account_id = line.employee_id.hr_sede_id.analytic_id
            else:
                analytic_account_id = account.analytic_account_id

            if (concept_id, analytic_account_id, payroll_id, account_id, 
              type_calc, partner_id) not in total_dict:
                total_dict[concept_id, analytic_account_id, payroll_id, 
                  account_id, type_calc, partner_id] = line.total
            else:
                total_dict[concept_id, analytic_account_id, payroll_id, 
                  account_id, type_calc, partner_id] = \
                total_dict[concept_id, analytic_account_id, payroll_id, 
                  account_id, type_calc, partner_id] + line.total

            # Lineas de contrapartidas
            if not account.account_payroll_id.user_type.code in ['expense']:
                analytic_account_id = line.employee_id.hr_sede_id.analytic_id
            else:
                analytic_account_id = account.analytic_account_id
                
            if (None, analytic_account_id, payroll_id, account.account_payroll_id, \
              None, partner_id) not in contrapartida_dict:
                if concept_id.type_calc == 'allocation':
                    contrapartida_dict[None, analytic_account_id, payroll_id, 
                      account.account_payroll_id, None, partner_id] = line.total * -1
                elif concept_id.type_calc == 'deduction':
                    contrapartida_dict[None, analytic_account_id, payroll_id, 
                      account.account_payroll_id, None, partner_id] = line.total
            else:
                if concept_id.type_calc == 'allocation':
                    contrapartida_dict[None, analytic_account_id, payroll_id, 
                      account.account_payroll_id, None, partner_id] = \
                      contrapartida_dict[None, analytic_account_id, 
                      payroll_id, account.account_payroll_id, None, 
                      partner_id] + (line.total * -1)
                elif concept_id.type_calc == 'deduction':
                    contrapartida_dict[None, analytic_account_id, payroll_id, 
                      account.account_payroll_id, None, partner_id] = \
                      contrapartida_dict[None, analytic_account_id, 
                      payroll_id, account.account_payroll_id, None, partner_id] \
                      + line.total
                    
        payrolls = list(set(payrolls))
        company_id = obj_company._company_default_get(cr, uid, 
          'account.move', context=context)
        
        cont = len(total_dict) + len(contrapartida_dict)
        linea = 0
        moves_dict = {}
        res = []
        
        period = self.pool.get('hr.period').search(cr, uid, 
          [('date_start','<=', fecha), ('date_end','>=', fecha), 
          ('type','=',linea_liq.employee_id.hr_payroll_id.hr_payment_calendar_id.type)])
        if not period:
            raise osv.except_osv(_('ERROR!'), _('No hay un periodo \
              asociado a la fecha de la linea de liquidación'))
        
        period = self.pool.get('hr.period').browse(cr, uid, period[0])
            
        # Creamos los asientos para cada nomina
        for pr in self.pool.get('hr.payroll').browse(cr, uid, payrolls):
            fecha = obj_period.browse(cr, uid, period.period_account_id.id).date_stop
            move = { 
                'ref' : 'Asiento ' + str(linea_liq.liquidacion_id.name),
                'to_check': 1,
                'journal_id': pr.journal_id.id,
                'period_id': period.period_account_id.id,
                'date': fecha,
                'state': 'draft',
                'company_id': int(company_id),
                'linea_liquidacion_id': linea_liq.id,
            }

            moves_dict[pr.id] = obj_moves.create(cr, uid, move, context=context)
        
        # Creamos los apuntes
        total_dict.update(contrapartida_dict)
        for key in total_dict.keys():
            concept, analytic_account, payroll, account, type_calc, partner = key
            fecha = obj_period.browse(cr, uid, period.period_account_id.id).date_stop
            if concept:
                debit = total_dict[key] if type_calc == 'allocation' else 0.0
                credit = total_dict[key] if type_calc == 'deduction' else 0.0
            else:
                debit = total_dict[key] if total_dict[key] > 0 else 0.0
                credit = total_dict[key]*-1 if total_dict[key] < 0 else 0.0
            
            moves_lines = {
                'journal_id': payroll.journal_id.id,
                'credit': round(credit, 2),
                'debit': round(debit, 2),
                'account_id': account.id,
                'period_id': period.period_account_id.id,
                'move_id': moves_dict[payroll.id],
                'name': concept.name if concept else account.code,
                'state': 'draft',
                'analytic_account_id': analytic_account.id,
                'partner_id': partner.id if account.type in \
                  ('payable', 'receivable') else 0,
                'fecha': fecha,
            }
            linea += 1
            
            if linea == cont:
                # Si es el ultimo apunte se crea nativamente para que 
                # tambien se valida el asiento.
                moves_lines_id = obj_acm.create(cr, uid, moves_lines, 
                  context=context)
            elif moves_lines['partner_id'] > 0:
                cr.execute("insert into account_move_line (account_id,name,\
                  centralisation,journal_id,company_id,currency_id,credit,state,\
                  period_id,debit,date,date_created,move_id,blocked,partner_id,\
                  create_uid,create_date,analytic_account_id) values \
                  (%s,'%s','normal',%s,%s,NULL,%s,'%s',%s,%s,'%s','%s',\
                  %s,False,%s,%s,now(),%s)"%(moves_lines['account_id'], 
                  moves_lines['name'],moves_lines['journal_id'],1,
                  moves_lines['credit'],moves_lines['state'],moves_lines['period_id'],
                  moves_lines['debit'],moves_lines['fecha'],moves_lines['fecha'],
                  moves_lines['move_id'],moves_lines['partner_id'],uid,
                  moves_lines['analytic_account_id']))
            else:
                cr.execute("insert into account_move_line (account_id,\
                  name,centralisation,journal_id,company_id,currency_id,\
                  credit,state,period_id,debit,date,date_created,move_id,\
                  blocked,create_uid,create_date,analytic_account_id) \
                  values (%s,'%s','normal',%s,%s,NULL,%s,'%s',%s,%s,'%s',\
                  '%s',%s,False,%s,now(),%s)"%(str(moves_lines['account_id']), 
                  str(moves_lines['name']),str(moves_lines['journal_id']),str(1),
                  str(moves_lines['credit']),str(moves_lines['state']),
                  str(moves_lines['period_id']),str(moves_lines['debit']),
                  str(moves_lines['fecha']),str(moves_lines['fecha']),
                  str(moves_lines['move_id']),str(uid),
                  moves_lines['analytic_account_id']))
                    
        #Colocar en estado asentado el asiento contable que se acaba de generar
        res = [moves_dict[x] for x in moves_dict]
        self.pool.get('account.move').button_validate(cr, uid, res) 
        for r in res:
            self._logger.info("Se validaron: %s.", 
              (self.pool.get('account.move').browse(cr, uid, r).ref))
        return res
        
    def aprobar_linea_liq(self, cr, uid, ids, context=None):
        if not context:
            context = {}
            
        linea_liq_brw = self.browse(cr, uid, ids, context=context)[0]
        
        if linea_liq_brw.employee_id.state <> 'egresado':
            raise osv.except_osv(_('ERROR!'),_('El empleado aun no ha sido \
              egresado. Debe asignar fecha de finalización de contrato\
              antes de aprobar la liquidación!'))
                                        
        payslip_review = self.pool.get('hr.payslip').search(cr, uid, 
          [('employee_id','=',linea_liq_brw.employee_id.id),
          ('hr_process_id.state','<>','done')])
        if payslip_review:
            raise osv.except_osv(_('ERROR!'),_('El empleado tiene una \
              hoja de pago en un proceso por aprobar, se debe verificar!'))
                                        
        lineas_in_liq = linea_liq_brw.liquidacion_id.linea_liquidacion_ids
        lineas_in_liq_ids = [x.id for x in lineas_in_liq if x.id not in ids] 
        
        aprobar_linea = True
        self.loan_update(cr, uid, linea_liq_brw, aprobar_linea, context)
         
        self.creacion_asiento(cr, uid, linea_liq_brw, linea_liq_brw.payslip_line_ids, 
          context=None)
            
        self.write(cr, uid, ids, {'state':'aprobado', 'fecha_aprobacion':datetime.now(),})
        self.write(cr, uid, lineas_in_liq_ids, {'state':'cancelado'})
        self.pool.get('hr.liquidacion').write(cr, uid, 
          linea_liq_brw.liquidacion_id.id, {'state':'aprobado'})
        return True

    def eliminar_asientos(self, cr, uid, move_ids, context=None):
        diarios = []
        for account_move in move_ids:
            analytic_lines = []
            diarios.append(account_move.journal_id.id)
            for move_line in account_move.line_id:
                analytic_lines = analytic_lines + \
                  self.pool.get('account.analytic.line').search(cr, uid, 
                  [('move_id', '=', move_line.id)])
            analytic_lines = str(analytic_lines).replace('[','(').replace(']',')')
            cr.execute("delete from account_analytic_line where id in %s"%(analytic_lines))
            cr.execute("delete from account_move where id = %s"%(account_move.id))
        return True
        
    def devolver_linea_liq(self, cr, uid, ids, context=None):
        if not context:
            context = {}
            
        linea_liq_brw = self.browse(cr, uid, ids, context=context)[0]
        lineas_in_liq = linea_liq_brw.liquidacion_id.linea_liquidacion_ids
        lineas_in_liq_ids = [x.id for x in lineas_in_liq] 
        
        aprobar_linea = False
        self.loan_update(cr, uid, linea_liq_brw, aprobar_linea, context)
        
        self.eliminar_asientos(cr, uid, linea_liq_brw.account_move_ids, context)
        
        self.write(cr, uid, lineas_in_liq_ids, {'state':'calculado', 
          'fecha_aprobacion':False,})
        self.pool.get('hr.liquidacion').write(cr, uid, linea_liq_brw.liquidacion_id.id, 
          {'state':'calculado'})
        return True
    
    def cancelar_linea_liq(self, cr, uid, ids, context=None):
        if not context:
            context = {}
        linea_liq_brw = self.browse(cr, uid, ids, context=context)[0]
        lineas_in_liq = linea_liq_brw.liquidacion_id.linea_liquidacion_ids
        
        lineas_in_liq_ids = [x.id for x in lineas_in_liq if x.id not in \
          ids and x.state <> 'cancelado']
        
        self.write(cr, uid, ids, {'state':'cancelado'})
        if not lineas_in_liq_ids:
            self.pool.get('hr.liquidacion').write(cr, uid, 
              linea_liq_brw.liquidacion_id.id, {'state':'cancelado'})
        
    def calcular_linea_liq(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        # Para que en la sobreescritura del unlink permita eliminar 
        # la linea para recalcularla
        context['procesar'] = True 
        linea_liq_brw = self.browse(cr, uid, ids)
        
        parameter_obj = self.pool.get('hr.parameters')
        param_struct_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'estructuras_liq')])
        if not param_struct_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parametro \
              definido para Estructuras de liquidaciones. Ir a \
              la pestaña Configuracion -> Configuraciones de nomina -> \
              Parametros de nomina y registrar un parametro de tipo \
              Estructuras para liquidaciones'))

        struct_list = parameter_obj.browse(cr, uid, param_struct_id)[0].estruc_liq_ids
        struct_brw = [x for x in struct_list if x.hr_payroll_id == \
          linea_liq_brw[0].employee_id.hr_payroll_id]

        if not struct_brw:
             raise osv.except_osv(_('ERROR!'), _('No hay una Estructuras \
             de Liquidaciones para la nómina %s')
             %(linea_liq_brw[0].employee_id.hr_payroll_id))
        
        old_slipline_ids = self.pool.get('hr.payslip.line').search(cr, 
          uid, [('linea_liq_id', '=', linea_liq_brw[0].id),
          ('variable', '=', False)], context=context)
        if old_slipline_ids:
            self.pool.get('hr.payslip.line').unlink(cr, uid, 
              old_slipline_ids, context=context)
                
        struct_brw = struct_brw[0]
        lines = self.get_payslip_lines(cr, uid, struct_brw, 
          linea_liq_brw[0], context=context)
        
        for line in lines:
            if line['amount'] > 0.0 and line['quantity'] > 0.0:
                save_on_database = False
                if 'salary_rule_id' in line:
                    rule = self.pool.get('hr.salary.rule').browse(cr, 
                      uid, line['salary_rule_id'])
                    save_on_database = rule.save_on_database
                else: #Es un attribute
                    attribute = self.pool.get('hr.attribute').browse(cr, 
                      uid, line['attribute_id'])
                    save_on_database = attribute.save_on_database
                if save_on_database: #Se debe guardar en BD
                    line_ids = self.pool.get('hr.payslip.line').create(cr, 
                      uid, line, context)
        
        self.write(cr, uid, ids, {'state':'calculado'})
        return True
    
    def get_all_attributes(self, cr, uid, structure_brw, employee_id, 
      period_id, context=None):
        """
        @param structure_brw: list of structure
        @return: returns a list of tuple (id, sequence) of attribute 
          that are maybe to apply
        """
        all_attributes = []
        period_brw = self.pool.get('hr.period').browse(cr, uid, period_id)
        structure_ids = [x.id for x in structure_brw]
        cr.execute(
          """
            select attr.id from hr_attribute attr
            join hr_concept hc on hc.id = attr.concept_id
            join hr_payroll_structure_concept_rel rel on rel.concept_id = hc.id
            join hr_payroll_structure hps on rel.payroll_structure_id = hps.id
            join hr_employee he on he.id = attr.employee_id
            where hc.type = 'fijo' 
            and he.id = %s
            and hps.id in %s
            and attr.active = True and
            case 
                when hc.date_end is not null then
                    hc.date_start <= %s and hc.date_end >= %s
                when hc.date_end is null and attr.date_end is not null then
                    attr.date_start <= %s and attr.date_end >= %s
                else attr.date_start <= %s
            end
          """,(employee_id.id, tuple(structure_ids), period_brw.date_end, 
          period_brw.date_start, period_brw.date_end, period_brw.date_start, 
          period_brw.date_end))
        attr_ids = cr.fetchall()
        attr_ids = [x[0] for x in attr_ids]
        all_attributes = self.pool.get('hr.attribute').browse(cr, uid, attr_ids)
        return all_attributes

    def get_cal_concept(self, params, employee, code, tipo, num_periods=False, 
      fechas_inicio_fin=[]):
        '''
        Devuelve total acumulado para el concepto con codigo code.
        code: Codigo del concepto a consultar
        tipo: Tipo de proceso del que se desea consultar el concepto
        num_periods: numero de periodos hacia atras que se desean consultar
        fechas_inicio_fin: rango de fechas en que se quiere realizar la 
          consulta
        '''
        if not num_periods and not fechas_inicio_fin:
            return (0, False)
        total = 0
        exist = False
        query = """
            select coalesce(t1.total, 0)
            from hr_payslip hp
            join hr_process hpr on hpr.id = hp.hr_process_id
            join hr_employee he on he.id = hp.employee_id
            left outer join (select hpl.slip_id, 
            sum(case when hc.type_calc = 'allocation' then hpl.total
                else hpl.total*-1
                end) as total 
            from hr_payslip_line hpl
            join hr_concept hc on hc.id =  hpl.concept_id
            where hpl.code in %s
            group by slip_id) as t1 on hp.id = t1.slip_id
            where he.id = %s
            and hpr.type in %s
            and hpr.state = 'done'
        """
        args = (tuple(code), employee.id, tuple(tipo))
        if fechas_inicio_fin:
            query = query + """ and hp.date_to >= %s
              and hp.date_from <= %s
              """
            args = args + (fechas_inicio_fin[0], fechas_inicio_fin[1])
        query += " order by hp.date_from desc"
        params[0].execute(query, args)
        lines_total = params[0].fetchall()
        lines_total = [x[0] for x in lines_total]
        if num_periods:
            if isinstance(num_periods, tuple):
                lines_total = lines_total[num_periods[0]:num_periods[1]]
            else:
                lines_total = lines_total[:num_periods]
        #Si es la primera hoja de pago, no existen valores.
        if lines_total:
            total = reduce(lambda x,y: x+y, [x for x in lines_total])
            exist = True
        self._logger.debug('get_cal_concept:Total: %s' % (total))
        return (total, exist)

    def _calcular_regla(self, cr, uid, rule, localdict, linea_liq_brw, 
      context):
        obj_rule = self.pool.get('hr.salary.rule')
        #compute the amount of the rule
        amount, qty, rate = obj_rule.compute_rule(cr, uid, rule.id, 
          localdict, context=context)
        
        #check if there is already a rule computed with that code
        previous_amount = rule.code in localdict and localdict[rule.code] or 0.0
        #set/overwrite the amount computed for this rule in the localdict
        tot_rule = amount * qty * rate / 100.0
        
        return {
            'salary_rule_id': rule.id,
            'name': rule.name,
            'code': rule.code,
            'quantity': qty,
            'sequence': rule.sequence,
            'appears_on_payslip': rule.appears_on_payslip,
            'register_id': rule.register_id.id,
            'amount': amount,
            'employee_id': linea_liq_brw.employee_id.id,
            'rate': rate,
            'state': 'draft',
            'linea_liq_id': linea_liq_brw.id,
            'active': True,
        }
    
    def vacaciones_no_disfrutadas(self, cr, uid, employee):
        ''' 
        Metodo que calcula el numero de dias de vacaciones pendientes 
        por disfrutar por cada asignacion de dias de disfrute de un trabajador
        @param employee: objeto Browseable que contiene el empleado (hr.employee)
        @return: Diccionario con la asignacion de dias y el numero de dias pendientes 
        de esas vacaciones
        '''
        result_dict = {}
        result_dict_hol = {}
        remanente = 0
        
        holidays_employee_ids = self.pool.get('hr.employee.holidays').search(cr, 
          uid, [('employee_id','=',employee.id),('state','=','done')])
        if holidays_employee_ids:
            for holidays_employee in self.pool.get('hr.employee.holidays').browse(cr, 
              uid, holidays_employee_ids):
                add = []
                remove = []
                result_dict_hol[holidays_employee] = {}
                holidays_asig_ids = self.pool.get('hr.holidays').search(cr, 
                  uid, [('employee_id','=',employee.id),
                  ('type','=','add'),('state','=','validate'),
                  ('employee_holidays_add_id','=',holidays_employee.id)])
                if holidays_asig_ids:
                    for holidays_asig in self.pool.get('hr.holidays').browse(cr, 
                      uid, holidays_asig_ids):
                        add = add+[holidays_asig]
                    result_dict_hol[holidays_employee]['add'] = add
                holidays_disf_ids = self.pool.get('hr.holidays').search(cr, 
                  uid, [('employee_id','=',employee.id),
                  ('type','=','remove'),('state','=','validate'),
                  ('employee_holidays_remove_id','=',holidays_employee.id)])
                if holidays_disf_ids:
                    for holidays_disf in self.pool.get('hr.holidays').browse(cr, 
                      uid, holidays_disf_ids):
                        remove = remove+[holidays_disf]
                    result_dict_hol[holidays_employee]['remove'] = remove
        for hol in result_dict_hol:
            if not 'add' in result_dict_hol[hol]:
                raise osv.except_osv(_('ERROR!'), _('El trabajador tiene \
                  un registro de vacaciones pero no tiene dias asignados'))
            for holidays_asig in result_dict_hol[hol]['add']:
                result_dict[holidays_asig] = holidays_asig.number_of_days_temp
                holidays_disf = result_dict_hol[hol]['remove'].pop() if \
                  ('remove' in result_dict_hol[hol] and result_dict_hol[hol]['remove']) \
                  else False
                if holidays_disf or remanente:
                    if holidays_disf and holidays_disf.number_of_days_temp < \
                      holidays_asig.number_of_days_temp:
                        result_dict[holidays_asig] = holidays_asig.number_of_days_temp - \
                          holidays_disf.number_of_days_temp - remanente
                    elif (not holidays_disf) and remanente:
                        result_dict[holidays_asig] = holidays_asig.number_of_days_temp - \
                          remanente
                    else:
                        del result_dict[holidays_asig]
                        remanente = holidays_disf.number_of_days_temp - \
                          holidays_asig.number_of_days_temp
        return result_dict
        
    def ultimo_proceso_utilidades(self, cr, uid, employee, linea_liq):
        ''' 
        Consultar el ultimo de proceso de utilidades en el que se le 
        pago al empleado 
        @param employee: objeto Browseable que contiene el empleado (hr.employee)
        @param linea_liq: objeto Browseable que contiene la linea de liquidacion 
            que se esta calculando (hr.linea.liquidacion)
        @return : Ultimo proceso de utilidades
        '''
        fecha_inicio_fin = []
        process_util = False
        
        process_util_list = [x.hr_process_id for x in employee.payslip_ids \
          if (x.type_process == 'utilidades' and x.state == 'done')]
        process_util_sorted = sorted(process_util_list, key=lambda x: x.date_end, reverse=True)
        if process_util_sorted:
            process_util = process_util_sorted[0]
            fecha_inicio_fin = [process_util.date_start, process_util.date_end]
        return (process_util, fecha_inicio_fin)
        
    def get_payslip_lines(self, cr, uid, structure_brw, linea_liq_brw, 
      context, variable_rule=False):
        def _sum_salary_rule_category(localdict, category, amount):
            if category.parent_id:
                localdict = _sum_salary_rule_category(localdict, 
                  category.parent_id, amount)
                localdict['categories'].dict[category.code] = category.code in \
                  localdict['categories'].dict and localdict['categories'].dict[category.code] + \
                  amount or amount
            return localdict

        #we keep a dict with the result because a value can be overwritten 
        #by another rule with the same code
        result_dict = {}
        categories_dict = {}
        categories_concept_dict = {}
        parameters_dict = {}
        payroll_dict = {}
        period_dict = {}
        blacklist = []
        obj_rule = self.pool.get('hr.salary.rule')
        parameter_obj = self.pool.get('hr.parameters')
        get_method = getattr(self.pool.get('hr.employee'), '_get')
        get_concept = getattr(self, 'get_cal_concept')

        employee = linea_liq_brw.employee_id
        
        fecha_liquidacion = datetime.strptime(linea_liq_brw.liquidacion_id.date,"%Y-%m-%d")
        period = self.pool.get('hr.period').search(cr, uid, [
          ('date_start','<=', fecha_liquidacion), 
          ('date_end','>=', fecha_liquidacion), 
          ('type','=',employee.hr_payroll_id.hr_payment_calendar_id.type)])
                                    
        if not period:
            raise osv.except_osv(_('ERROR!'), _('No hay un periodo asociado \
              a la fecha de la linea de liquidación'))
        
        period = self.pool.get('hr.period').browse(cr, uid, period[0])

        #Verificar si ya se corrio proceso de prestaciones del mes actual
        proceso_prestaciones = True
        process_prest_ids = self.pool.get('hr.process').search(cr, uid, 
          [('hr_period_ids','=', [period.id]),
          ('type','=','prestaciones'), ('state','=','done')])
        payslip_prest = self.pool.get('hr.payslip').search(cr, uid, 
          [('employee_id','=',employee.id),
          ('hr_process_id','in',process_prest_ids)])
        if not payslip_prest:
            proceso_prestaciones = False
            
        feriados = self.pool.get('hr.holidays.calendar').search(cr, uid, 
          [('date','>=',datetime(datetime.strptime(period.date_start,"%Y-%m-%d").year,01,01)),
          ('date','<=',datetime(datetime.strptime(period.date_end,"%Y-%m-%d").year,12,31))])
        feriados = [f.date for f in self.pool.get('hr.holidays.calendar').browse(cr, 
          uid, feriados)]
        acumulado_prestaciones = self.pool.get('prestaciones.employee').acumulado_prestaciones(cr, 
          uid, employee)
        anticipos = self.pool.get('prestaciones.employee').anticipos(cr, 
          uid, employee)
        
        #Registro de ultimas vacaciones pagadas
        employee_hol_brw = False
        
        '''
            vac_vencidas: Lista de tuplas. Cada tupla tiene la forma (vac_vencida, 
            num_dias_adicionales)
        '''
        start_rel_lab = datetime.strptime(employee.start_rel_lab,"%Y-%m-%d")
        vac_vencidas = []
        employee_hol_ids = self.pool.get('hr.employee.holidays').search(cr, 
          uid, [('employee_id','=',employee.id),('state','=','done')], order='corresp_to_start desc')
        if employee_hol_ids:
            employee_hol_brw = self.pool.get('hr.employee.holidays').browse(cr, 
              uid, employee_hol_ids[0], context)
            
            employee_hol_date = datetime.strptime(employee_hol_brw.corresp_to_end,"%Y-%m-%d")

            #Se cancelan 1 dia adicional por año a partir del 2º año
            dias_adicionales = employee_hol_date.year-start_rel_lab.year-1 if \
              employee_hol_date.year-start_rel_lab.year > 1 else 0
            dias_adicionales = dias_adicionales if dias_adicionales < 15 \
              else 15
            
            num_vac_vencidas = (fecha_liquidacion.year - employee_hol_date.year) if \
              fecha_liquidacion.month >= employee_hol_date.month else \
              (fecha_liquidacion.year - employee_hol_date.year - 1)
            for x in range(num_vac_vencidas):
                vac_vencidas.append((employee_hol_date.year+x, dias_adicionales + \
                  1 if dias_adicionales < 15 else 15))
        else:
            new_date = datetime(start_rel_lab.year, start_rel_lab.month,
              start_rel_lab.day)
            num_vac_vencidas = (fecha_liquidacion.year - new_date.year) if \
              fecha_liquidacion.month > new_date.month else \
              (fecha_liquidacion.year - new_date.year - 1)
            for x in range(num_vac_vencidas):
                dias_adicionales = x
                vac_vencidas.append((new_date.year + x, dias_adicionales \
                  if dias_adicionales < 15 else 15))
        
        new_date = datetime(start_rel_lab.year, start_rel_lab.month,
          start_rel_lab.day)
        ultimo_anio_pagado = datetime.strptime(employee_hol_brw.corresp_to_end,"%Y-%m-%d") \
          if employee_hol_brw else new_date
        reg_vac_no_disf = self.vacaciones_no_disfrutadas(cr, uid, employee)

        process_util = self.ultimo_proceso_utilidades(cr, uid, employee, 
          linea_liq_brw)
        
        localdict = {
            'atributo': get_method,
            'historial': get_concept,
            'param': [cr, uid],
            'concepto': {},
            'cantidad_horas': {},
            'categoria_concepto': {},
            'datetime': datetime,
            'feriados': feriados,
            'acumulado_prestaciones': acumulado_prestaciones,
            'anticipos': anticipos,
            'motivo': linea_liq_brw.type.name,
            'vac_vencidas': vac_vencidas,
            'ultimas_vac_pagadas': employee_hol_brw,
            'fecha_inicio_fin': process_util[1],
            'fecha_liquidacion': fecha_liquidacion,
            'proceso_prestaciones':proceso_prestaciones,
            'calendar': calendar,
            'dias_no_trabajados': 0,
            'self': self,
            'sueldo_prestaciones': linea_liq_brw.sueldo_prestaciones,
        }
        
        edad = (datetime.now() - datetime.strptime(employee.birthday,"%Y-%m-%d")).days/365
        localdict.update({'empleado': employee,
            'sexo': 'Femenino' if employee.gender == 'female' else 'Masculino',
            'edad': edad,
            'jornada_dia': employee.shift_id.jor_day,
            'jornada_semana': employee.shift_id.jor_week,})
        
        rules_dict = {}
        hours_dict = {}
        
        #Incluir en el localdict categories los montos de los conceptos variables
        for line in linea_liq_brw.payslip_line_ids:
            rules_dict[line.code] = line.total
            localdict['concepto'] = rules_dict

        #Agregar parametros de la nomina
        for parameter in employee.hr_payroll_id.parameters_ids:
            parameters_dict[parameter.type] = parameter.value or 0.0
        localdict.update({'parametros': parameters_dict,})

        #Busqueda del concepto que se definio como concepto sueldo en 
        #los parametros de la nomina
        param_concept_salary_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'concepto_sueldo'),
          ('payroll_id', '=', employee.hr_payroll_id.id)])
        if not param_concept_salary_id:
            param_concept_salary_id = parameter_obj.search(cr, uid, 
              [('type', '=', 'concepto_sueldo'),('payroll_id', '=', None)])
        if not param_concept_salary_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parametro definido \
              para el concepto salario para la nomina %s. Ir a \
              la pestaña Configuracion -> Configuraciones de nomina -> \
              Parametros de nomina y registrar un parametro de tipo \
              Concepto Salario')%(employee.hr_payroll_id.name))

        concept_salary_brw = parameter_obj.browse(cr, uid, 
          param_concept_salary_id)[0].concept_wage_id
        
        #Busqueda del concepto que se definio como Concepto para registro 
        #de fecha para calculos de prestaciones
        param_fp_id = parameter_obj.search(cr, uid, [('type', '=', 'fecha_prest')])
        concept_fp_id = 0
        if param_fp_id:
            concept_fp_id = parameter_obj.browse(cr, uid, param_fp_id)[0].concept_prest_id
        
        #Busqueda del concepto que se definio como concepto Vacaciones vencidas
        param_vac_ven_id = parameter_obj.search(cr, uid, [
          ('type', '=', 'concepto_vac_venc')])
        if not param_vac_ven_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parametro \
              definido para el Concepto Vacaciones vencidas. Ir a \
              la pestaña Configuracion -> Configuraciones de nomina -> \
              Parametros de nomina y registrar un parametro de tipo \
              Concepto Vacaciones vencidas'))

        concept_vac_ven_brw = parameter_obj.browse(cr, uid, param_vac_ven_id)[0].concept_vac_ven_id
        
        #Busqueda del concepto que se definio como Concepto Dias 
        #Vacaciones vencidas
        param_dias_vac_ven_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'concepto_dias_vac_ven')])
        if not param_dias_vac_ven_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parametro \
              definido para el Concepto Dias Vacaciones vencidas. Ir a \
              la pestaña Configuracion -> Configuraciones de nomina -> \
              Parametros de nomina y registrar un parametro de tipo \
              Concepto Dias Vacaciones vencidas'))

        concept_dias_vac_ven_brw = parameter_obj.browse(cr, uid, 
          param_dias_vac_ven_id)[0].concepto_dias_vac_ven_id
        
        #Busqueda del concepto que se definio como Concepto Dias 
        #adicionales Vacaciones vencidas
        param_dias_adic_vac_ven_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'concepto_dias_adic_vac_ven')])
        if not param_dias_adic_vac_ven_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parametro \
              definido para el Concepto Dias adicionales Vacaciones vencidas. Ir a \
              la pestaña Configuracion -> Configuraciones de nomina -> \
              Parametros de nomina y registrar un parametro de tipo \
              Concepto Dias adicionales Vacaciones vencidas'))

        concept_dias_adic_vac_ven_brw = parameter_obj.browse(cr, uid, 
          param_dias_adic_vac_ven_id)[0].concepto_dias_adic_vac_ven_id
        
        #Busqueda del concepto que se definio como conceptos de Vacaciones 
        #no disfrutadas
        param_vac_no_disf_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'concepto_vac_no_disf')])
        if not param_vac_no_disf_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parametro \
              definido para Conceptos Vacaciones no disfrutadas. Ir a \
              la pestaña Configuracion -> Configuraciones de nomina -> \
              Parametros de nomina y registrar un parametro de tipo \
              Conceptos Vacaciones no disfrutadas'))

        concept_vac_no_disf_brw = parameter_obj.browse(cr, uid, 
          param_vac_no_disf_id)[0].concept_vac_no_disf_id
        
        #Busqueda del concepto que se definio como Concepto Utilidades 
        #Legales para Liquidaciones
        param_util_liq_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'concepto_util_liq')])
        if not param_util_liq_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parametro \
              definido para Concepto Utilidades Legales para Liquidaciones. Ir a \
              la pestaña Configuracion -> Configuraciones de nomina -> \
              Parametros de nomina y registrar un parametro de tipo \
              Concepto Utilidades Legales para Liquidaciones'))

        concept_util_liq_brw = parameter_obj.browse(cr, uid, 
          param_util_liq_id)[0].concept_util_liq_id
        
        #Busqueda del concepto que se definio como Concepto Utilidades 
        #fraccionadas para Liquidaciones
        param_util_frac_liq_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'concepto_util_frac_liq')])
        if not param_util_frac_liq_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parametro \
              definido para Concepto Utilidades fraccionadas para Liquidaciones. Ir a \
              la pestaña Configuracion -> Configuraciones de nomina -> \
              Parametros de nomina y registrar un parametro de tipo \
              Concepto Utilidades fraccionadas para Liquidaciones'))

        concept_util_frac_liq_brw = parameter_obj.browse(cr, uid, 
          param_util_frac_liq_id)[0].concept_util_frac_liq_id
        
        #Busqueda del concepto que se definio como Concepto Prestaciones 
        #de Antiguedad por Liquidacion
        param_prest_liq_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'concepto_prest_liq')])
        if not param_prest_liq_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parametro \
              definido para Concepto Prestaciones de Antiguedad por Liquidacion. Ir a \
              la pestaña Configuracion -> Configuraciones de nomina -> \
              Parametros de nomina y registrar un parametro de tipo \
              Concepto Prestaciones de Antiguedad por Liquidacion'))

        concept_prest_liq_brw = parameter_obj.browse(cr, uid, 
          param_prest_liq_id)[0].concepto_prest_liq_id
        
        if not employee.hr_payroll_id.hr_payment_calendar_id:
            raise osv.except_osv(_('ERROR!'), _('La nomina %s no tiene \
              calendario de pago. Debe asignarle un calendario de pago \
              antes de ejecutar cualquier proceso')
              %(employee.hr_payroll_id.name))

        localdict['periodo'] = period
        
        if not employee.contract_id:
            raise osv.except_osv(_('ERROR!'), _('El empleado %s no tiene \
              un contrato registrado')%(employee.name))
        period_end_year = datetime.strptime(period.date_end,"%Y-%m-%d").year
        #Fecha de ingreso segun fecha de prestaciones
        attr_date_prest = list(set(concept_fp_id.attribute_ids) & \
          set(employee.attribute_ids)) if concept_fp_id else False
        date_prest = attr_date_prest[0].date_value if attr_date_prest \
          else employee.start_rel_lab

        antiguedad = ((fecha_liquidacion.year * 12) + fecha_liquidacion.month) - \
          ((datetime.strptime(date_prest,"%Y-%m-%d").year * 12) + \
          datetime.strptime(date_prest,"%Y-%m-%d").month)

        localdict['antiguedad'] = antiguedad
        
        #get the rules of the structure and thier children
        rule_ids = self.pool.get('hr.payroll.structure').get_all_rules(cr, 
          uid, [structure_brw.id], employee, period.id, context=context)
        if variable_rule:
            rule_ids = rule_ids + [(variable_rule.id, variable_rule.sequence)]
        #get the attributes of the structure
        attribute_ids = self.get_all_attributes(cr, uid, [structure_brw], 
          employee, period.id, context=context)
        
        #run the rules by sequence
        sorted_rule_ids = [id for id, sequence in sorted(rule_ids, 
          key=lambda x:x[1])]

        if not employee.attribute_ids:
            raise osv.except_osv(_('ERROR!'), _('El empleado %s no \
              tiene atributos')%(employee.name))
                            
        for attribute in employee.attribute_ids:
            if attribute.concept_id.id == concept_salary_brw.id:
                rules_dict['SUELDO'] = attribute.amount
                localdict['concepto'] = rules_dict

        for attribute in attribute_ids:
            key = attribute.code
            if not key in result_dict:
                result_dict[key] = {
                    'attribute_id': attribute.id,
                    'name': attribute.name,
                    'code': attribute.code,
                    'appears_on_payslip': attribute.appears_on_payslip,
                    'amount': attribute.amount if not attribute.loan_ids \
                      else attribute.loan_ids[0].remaining_debt,
                    'employee_id': employee.id,
                    'quantity': 1.00,
                    'rate': 100.00,
                    'state': 'draft',
                    'linea_liq_id': linea_liq_brw.id,
                }
                rules_dict[attribute.code] = attribute.amount or 0.0
                localdict['concepto'] = rules_dict
            else:
                result_dict[key+str(attribute.id)] = {
                    'attribute_id': attribute.id,
                    'name': attribute.name,
                    'code': attribute.code,
                    'appears_on_payslip': attribute.appears_on_payslip,
                    'amount': attribute.amount if not attribute.loan_ids \
                      else attribute.loan_ids[0].remaining_debt,
                    'employee_id': employee.id,
                    'quantity': 1.00,
                    'rate': 100.00,
                    'state': 'draft',
                    'linea_liq_id': linea_liq_brw.id,
                }
                rules_dict[attribute.code] = rules_dict[attribute.code] + \
                  (attribute.amount or 0.0)
                localdict['concepto'] = rules_dict
            
            if attribute.concept_id.category_id.code not in categories_concept_dict:
                categories_concept_dict[attribute.concept_id.category_id.code] = \
                  attribute.amount or 0.0
            else:
                categories_concept_dict[attribute.concept_id.category_id.code] = \
                  categories_concept_dict[attribute.concept_id.category_id.code] + \
                  attribute.amount
                localdict['categoria_concepto'] = categories_concept_dict

        for rule in obj_rule.browse(cr, uid, sorted_rule_ids, context=context):
            key = rule.code
            localdict['result'] = None
            localdict['result_qty'] = localdict['cantidad'] = 1.0
            #check if the rule can be applied
            if obj_rule.satisfy_condition(cr, uid, rule.id, localdict, 
              context=context) and rule.id not in blacklist:
                #compute the amount of the rule
                inicial_dict = self._calcular_regla(cr, uid, rule, 
                  localdict, linea_liq_brw, context)
                amount = inicial_dict['amount']
                qty = localdict['cantidad'] = inicial_dict['quantity']
                
                if rule.code == concept_vac_ven_brw.code or rule.code == \
                  concept_dias_vac_ven_brw.code:
                    qty_concept = parameters_dict['vacaciones'] \
                      if rule.code == concept_vac_ven_brw.code else 15
                    for c in range(len(vac_vencidas)+1):
                        desde = datetime.strptime(linea_liq_brw.liquidacion_id.start_rel_lab,"%Y-%m-%d")
                        if fecha_liquidacion.year > desde.year:
                            if fecha_liquidacion.month == desde.month:
                                meses = fecha_liquidacion.month - desde.month
                            
                            elif fecha_liquidacion.month < desde.month:
                                if fecha_liquidacion.day < desde.day:
                                    meses = 12 - desde.month + fecha_liquidacion.month - 1
                                else:
                                    meses = 12 - desde.month + fecha_liquidacion.month
                            else:
                                meses = fecha_liquidacion.month - desde.month
                                if fecha_liquidacion.day < desde.day:
                                    meses = fecha_liquidacion.month - desde.month - 1
                                else:
                                    meses = fecha_liquidacion.month - desde.month
                        else:
                            meses = fecha_liquidacion.month - desde.month
                            if fecha_liquidacion.day < desde.day:
                                meses = fecha_liquidacion.month - desde.month - 1
                            else:
                                meses = fecha_liquidacion.month - desde.month
                        
                        qty = qty_concept if ((ultimo_anio_pagado.year+c < fecha_liquidacion.year-1) or \
                          (ultimo_anio_pagado.year+c == fecha_liquidacion.year-1 and \
                          fecha_liquidacion.month > ultimo_anio_pagado.month)) \
                          else float(qty_concept)/12*meses
    
                        key_ = key + '-' + str(ultimo_anio_pagado.year+c)
                        result_dict[key_] = inicial_dict.copy()
                        result_dict[key_].update({
                            'name': rule.name + (' Periodo ' + str(ultimo_anio_pagado.year+c) \
                              + '-' + str(ultimo_anio_pagado.year+1+c))\
                              if ((ultimo_anio_pagado.year+c < fecha_liquidacion.year-1) or \
                              (ultimo_anio_pagado.year+c == fecha_liquidacion.year-1 and \
                              fecha_liquidacion.month > ultimo_anio_pagado.month)) \
                              else (rule.name + (' Fraccion periodo ' + \
                              str(fecha_liquidacion.year) \
                              + '-' + str(fecha_liquidacion.year+1)) if \
                              fecha_liquidacion.month > ultimo_anio_pagado.month else
                              rule.name + (' Fraccion periodo ' + \
                              str(fecha_liquidacion.year-1) \
                              + '-' + str(fecha_liquidacion.year))),
                            'code': key_,
                            'quantity': qty,
                        })
                        rules_dict[key_] = amount*qty or 0.0
                        localdict['concepto'] = rules_dict
                        
                elif rule.code == concept_dias_adic_vac_ven_brw.code:
                    for c in range(len(vac_vencidas)):
                        qty = vac_vencidas[c][1]
                        key_ = key + '-' + str(ultimo_anio_pagado.year+c)
                        result_dict[key_] = inicial_dict.copy()
                        result_dict[key_].update({
                            'name': rule.name + (' Periodo ' + str(ultimo_anio_pagado.year+c) \
                              + '-' + str(ultimo_anio_pagado.year+1+c))\
                              if ((ultimo_anio_pagado.year+c < fecha_liquidacion.year-1) or \
                              (ultimo_anio_pagado.year+c == fecha_liquidacion.year-1 and \
                              fecha_liquidacion.month > ultimo_anio_pagado.month)) \
                              else (rule.name + (' Fraccion periodo ' + \
                              str(fecha_liquidacion.year) \
                              + '-' + str(fecha_liquidacion.year+1)) if \
                              fecha_liquidacion.month > ultimo_anio_pagado.month else
                              rule.name + (' Fraccion periodo ' + \
                              str(fecha_liquidacion.year-1) \
                              + '-' + str(fecha_liquidacion.year))),
                            'code': key_,
                            'quantity': qty,
                        })
                        rules_dict[key_] = amount*qty or 0.0
                        localdict['concepto'] = rules_dict
                        
                elif rule.code == concept_vac_no_disf_brw.code:
                    for _vac in reg_vac_no_disf:
                        anio = datetime.strptime(_vac.employee_holidays_add_id.corresp_to_end,"%Y-%m-%d").year
                        tipo = _vac.name[_vac.name.find('/')+13:]
                        qty = reg_vac_no_disf[_vac]
                        key_ = key + '-' + str(_vac.name[_vac.name.find('/')+2:])
                        result_dict[key_] = inicial_dict.copy()
                        result_dict[key_].update({
                            'name': rule.name + ' periodo ' + str(anio-1) + \
                              ' - ' + str(anio) + ' ' + tipo,
                            'code': key_,
                            'quantity': qty,
                        })
                        rules_dict[key_] = amount*qty or 0.0
                        localdict['concepto'] = rules_dict
                    
                else:
                    result_dict[key] = inicial_dict.copy()
                    
                    if rule.code == concept_util_liq_brw.code:
                        qty = parameters_dict['utilidades']
                        result_dict[key]['quantity'] = qty
                        
                    elif rule.code == concept_prest_liq_brw.code:
                        qty = 5
                        result_dict[key]['quantity'] = qty
                        
                    elif rule.code == concept_util_frac_liq_brw.code:
                        contract_date_start = datetime.strptime(employee.start_rel_lab,"%Y-%m-%d")
                        fraccion_mes = fecha_liquidacion.day / \
                          calendar.monthrange(fecha_liquidacion.year,fecha_liquidacion.month)[1]
                        if contract_date_start.year < fecha_liquidacion.year:
                            qty = parameters_dict['utilidades']/12*(fecha_liquidacion.month \
                              - 1 + fraccion_mes)
                            result_dict[key]['quantity'] = qty
                        elif contract_date_start.year == fecha_liquidacion.year:
                            qty = parameters_dict['utilidades']/12*(fecha_liquidacion.month - \
                              contract_date_start.month+fraccion_mes)
                            result_dict[key]['quantity'] = qty
                        
                    rules_dict[key] = amount*qty or 0.0
                    localdict['concepto'] = rules_dict
                
                if rule.concept_id.category_id.code not in categories_concept_dict:
                    categories_concept_dict[rule.concept_id.category_id.code] = \
                      amount or 0.0
                else:
                    categories_concept_dict[rule.concept_id.category_id.code] = \
                      categories_concept_dict[rule.concept_id.category_id.code] \
                      + amount
                localdict['categoria_concepto'] = categories_concept_dict
                
            else:
                #blacklist this rule and its children
                blacklist += [id for id, seq in 
                  self.pool.get('hr.salary.rule')._recursive_search_of_rules(cr, 
                  uid, [rule], context=context)]
        result = [value for code, value in result_dict.items()]
        return result

    def on_change_payslip_line_ids(self, cr, uid, ids, payslip_line_ids):
        line_liq_brw = self.browse(cr, uid, ids)
        result = {
            'total_allocations': line_liq_brw[0].total_allocations,
            'total_deductions': line_liq_brw[0].total_deductions,
            'total': line_liq_brw[0].total,
        }
        return {'value': result}
        
hr_linea_liquidacion()

class hr_liquidacion(osv.osv):
    '''
        Cálculo de liquidaciones
    '''
    _inherit = 'hr.liquidacion'
    _description = 'Cálculo de liquidaciones'
    
    _columns = {
        'linea_liquidacion_ids': fields.one2many('hr.linea.liquidacion', 
          'liquidacion_id', 'Propuestas de liquidacion', ondelete='cascade'),
    }
    
    def create(self, cr, uid, vals, context=None):
        if context is None:
            context = {}
        name = 'Liquidacion '+ str(self.pool.get('hr.employee').browse(cr, 
          uid, vals['employee_id']).name)
        vals['name'] = name
        return super(hr_liquidacion, self).create(cr, uid, vals, context)
        
    def write(self, cr, uid, ids, vals, context=None):
        if not context:
            context = {}
        if 'state' in vals or 'linea_liquidacion_ids' in vals:
            return super(hr_liquidacion, self).write(cr, uid, ids, vals, 
              context)
            
        lineas = reduce(lambda x,y: x+y, [x.linea_liquidacion_ids \
          for x in self.browse(cr, uid, ids)])
        lineas_ids = [x.id for x in lineas if x.state <> 'cancelado']
        self.pool.get('hr.linea.liquidacion').write(cr, uid, lineas_ids, 
          {'state':'borrador'}, context)
        vals.update({'state':'borrador'})
        return super(hr_liquidacion, self).write(cr, uid, ids, vals, context)

    def unlink(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if type(ids) != list:
            ids = [ids]

        for liq in self.browse(cr, uid, ids):
            if liq.state in ('aprobado','cancelado'):
                raise osv.except_osv(_('Accion no permitida!'), _('No se \
                  permite eliminar Liquidaciones en estado %s'%(liq.state)))
            
        return super(hr_liquidacion, self).unlink(cr, uid, ids, context)
        
hr_liquidacion()

class hr_payslip_line(osv.osv):
    '''
    Pay Slip
    '''
    _inherit = 'hr.payslip.line'
    _description = 'Payslip Line'

    _columns = {
        'linea_liq_id':fields.many2one('hr.linea.liquidacion', 
          'Línea de liquidacion', ondelete='cascade'),
    }
            
    def create(self, cr, uid, vals, context=None):
        if context is None:
            context = {}
        if 'procesar' in context or not 'linea_liq_id' in vals:
            return super(hr_payslip_line, self).create(cr, uid, vals, context)
        
        linea_liq_brw = self.pool.get('hr.linea.liquidacion').browse(cr, 
          uid, vals['linea_liq_id'])
        salary_rule_brw = self.pool.get('hr.salary.rule').browse(cr, 
          uid, vals['salary_rule_id'])
        
        parameter_obj = self.pool.get('hr.parameters')
        param_struct_id = parameter_obj.search(cr, uid, 
          [('type', '=', 'estructuras_liq')])
        if not param_struct_id:
            raise osv.except_osv(_('ERROR!'), _('No hay un parametro \
              definido para Estructuras de liquidaciones. Ir a \
              la pestaña Configuracion -> Configuraciones de nomina -> \
              Parametros de nomina y registrar un parametro de tipo \
              Estructuras para liquidaciones'))

        struct_list = parameter_obj.browse(cr, uid, param_struct_id)[0].estruc_liq_ids
        struct_brw = [x for x in struct_list if x.hr_payroll_id == \
          linea_liq_brw.employee_id.hr_payroll_id]

        if not struct_brw:
             raise osv.except_osv(_('ERROR!'), _('No hay una Estructuras \
               de liquidaciones para la nómina %s')
               %(linea_liq_brw.employee_id.hr_payroll_id))
                        
        struct_brw = struct_brw[0]
        lines = self.pool.get('hr.linea.liquidacion').get_payslip_lines(cr, 
          uid, struct_brw, linea_liq_brw, context=context, 
          variable_rule=salary_rule_brw)
        
        line = [x for x in lines if x['code'] == salary_rule_brw.code]
        
        if line:
            line[0].update({'quantity':vals['quantity'], 'variable':True})
            if 'amount' in vals and vals['amount'] > 0.0:
                line[0].update({'amount':vals['amount']})
            save_on_database = False
            rule = self.pool.get('hr.salary.rule').browse(cr, uid, 
              line[0]['salary_rule_id'])
            save_on_database = rule.save_on_database
            if save_on_database: #Se debe guardar en BD
                self.pool.get('hr.linea.liquidacion').write(cr, uid, 
                  linea_liq_brw.id, {'state':'borrador'})
                return super(hr_payslip_line, self).create(cr, uid, line[0], 
                  context)

        return False
        
    def write(self, cr, uid, ids, vals, context=None):
        if context is None:
            context = {}
        if not isinstance(ids, list):
            ids = [ids]
            
        payslip_line_brw = self.browse(cr, uid, ids)
        
        for payslip_line in payslip_line_brw:
            if not 'create' in context and payslip_line.linea_liq_id:
                raise osv.except_osv(_('Acceso Denegado!'),_('No se permite \
                  modificar Lineas de Propuesta de Liquidacion. Debe \
                  eliminar la linea y crearla de nuevo'))
        return super(hr_payslip_line, self).write(cr, uid, ids, vals, context)
        
    
    def unlink(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        
        if not isinstance(ids, list):
            ids = [ids]
            
        payslip_line_brw = self.browse(cr, uid, ids)
        for payslip_line in payslip_line_brw:
            if payslip_line.attribute_id.loan_ids and not 'procesar' in context \
              and payslip_line.linea_liq_id:
                raise osv.except_osv(_('Accion no permitida!'), _('No se \
                  permite eliminar Lineas creadas a partir de prestamos\
                  pendientes'))
                                                
            self.pool.get('hr.linea.liquidacion').write(cr, uid, 
              payslip_line.linea_liq_id.id, {'date':payslip_line.linea_liq_id.date})
            
        return super(hr_payslip_line, self).unlink(cr, uid, ids, context)
        
hr_payslip_line()

class account_move(osv.osv):

    _inherit = "account.move"
    _description = "Account Entry"

    _columns = {
        'linea_liquidacion_id': fields.many2one('hr.linea.liquidacion', 
          'Línea de cálculo de liquidaciones'),
    }

account_move()

class hr_linea_liquidacion(osv.osv):
    '''
        Línea de Cálculo de liquidaciones
    '''
    _inherit = 'hr.linea.liquidacion'
    _description = 'Línea de Cálculo de liquidaciones'
    
    _columns = {
        'payslip_line_ids': fields.one2many('hr.payslip.line', 
          'linea_liq_id', 'Lineas de pago', 
          domain=[('appears_on_payslip', '=', True)], ondelete='cascade'),
        'account_move_ids': fields.one2many('account.move', 
          'linea_liquidacion_id', 'Asientos contables'),
    }
    
    def unlink(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if type(ids) != list:
            ids = [ids]

        for linea_liq in self.browse(cr, uid, ids):
            if linea_liq.state in ('aprobado','cancelado'):
                raise osv.except_osv(_('Accion no permitida!'), _('No se \
                  permite eliminar Propuestas de Liquidacion en \
                  estado %s'%(linea_liq.state)))
            
        return super(hr_linea_liquidacion, self).unlink(cr, uid, 
          ids, context)
        
hr_linea_liquidacion()