~clearcorp-drivers/openerp-hr-payroll-cr/5.0

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
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
# -*- encoding: utf-8 -*-
##############################################################################
#
#    hr_payroll_cr.py
#    hr_payroll_cr
#    First author: Carlos Vásquez <carlos.vasquez@clearcorp.co.cr> (ClearCorp S.A.)
#    Copyright (c) 2010-TODAY ClearCorp S.A. (http://clearcorp.co.cr). All rights reserved.
#    
#    Redistribution and use in source and binary forms, with or without modification, are
#    permitted provided that the following conditions are met:
#    
#       1. Redistributions of source code must retain the above copyright notice, this list of
#          conditions and the following disclaimer.
#    
#       2. Redistributions in binary form must reproduce the above copyright notice, this list
#          of conditions and the following disclaimer in the documentation and/or other materials
#          provided with the distribution.
#    
#    THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND ANY EXPRESS OR IMPLIED
#    WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
#    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
#    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
#    ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#    ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#    
#    The views and conclusions contained in the software and documentation are those of the
#    authors and should not be interpreted as representing official policies, either expressed
#    or implied, of ClearCorp S.A..
#    
##############################################################################

from osv import osv, fields
import tools
import datetime
import calendar
import time
from datetime import timedelta, date
import string
from tools import config
from tools import debug



class hr_payroll_cr_payroll(osv.osv):
	_name = 'hr_payroll_cr.payroll'
	_rec_name = 'detail'
	_columns = {
		'detail': fields.char('Detail', size=150, select=1, readonly=True),
		'date': fields.date('Date', select=1, readonly=True),
		'type': fields.selection([('U', 'Unemployment Fee'), ('F', 'Final Payment'), ('P', 'Payroll'), ('C', 'Christmas Bonus'), ('FC', 'Unemployment fee per Company')], 'Type', translate=True, select=1, readonly=True, help="Payroll type: Payroll, Unemployment Fee, Final Payment, Christmas Bonus"),
		'company_id': fields.many2one('res.company', 'Company', select=1, readonly=True),
		'contract':fields.many2one('hr.contract', 'Contract', readonly=True, select=2, help="Required only to pay unemployment fee, christmas bonus and final payment"),
		'payment': fields.one2many('hr_payroll_cr.payment', 'payroll', 'Payment', select=0, readonly=True),
		'notes': fields.text('Notes'),
	}
	incapacity_payment_dictionary = { }
	deduction_payment_dictionary = { }
	other_income_payment_total = { }
	saving_payment_dictionary = { }
	loan_payment_dictionary = { }
	holidays_payment_dictionary = { }
	retirement_payment_dictionary = { }
	working_holiday_payment_dictionary = { }
	extra_hour_payment_dictionary = { }
	over_salary_payment_dictionary = { }
	commission_payment_dictionary = { }
	employer_payment_dictionary = { }
	retirement_fund = 0
	foreclosure_payment_dictionary = { }

	def str2date(self, date_str):
		date_unformat = time.strptime(date_str, '%Y-%m-%d')
		return datetime.date(date_unformat.tm_year, date_unformat.tm_mon, date_unformat.tm_mday)

	def interval(self,edate, idate):
		return (edate - idate)

#This function calculates the absences for a given contract, and creates a payment_per_contract_line
#calculates the amount to be paid per day depending on the base salary of the contract
#recieves a contract, payment per contract, a range of dates and a payment
	def _absence(self, cr, uid, contract_id, payment_per_contract, mindate, maxdate, payment):
		#gets all the absences for a contract
		absences_search = self.pool.get('hr_payroll_cr.absence').search(cr,uid,[('contract','=',contract_id), ('date', '<=', maxdate), ('date', '>=', mindate)])
		#data of the contract
		contract = self.pool.get('hr.contract').browse(cr,uid,contract_id)
		wage = contract.wage
		absence_detail = ''
		amount = wage / 30
		amount_total = 0
		ppcl_list = []
		today = time.strftime('%Y-%m-%d')
		for id in absences_search: # For each absence day, the base salary is divide into 30 to know the reduction amount
			#for each one of the ids of the search retrieves all the data of the absence
			absence_browse = self.pool.get('hr_payroll_cr.absence').browse(cr,uid,id)
			if not absence_browse.payment_per_contract_line and not absence_browse.justification:
				absence_detail = absence_browse.detail
				amount_total = amount_total + amount
				#creates a payment per contract line to storage the payment per absence
				payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':5, 'detail':absence_detail + ' - Absence','amount':amount, 'date':datetime.date.today(), 'payment_per_contract':payment_per_contract, 'payment':payment})
				#binds the payment per contract to the absence
				ppcl_list.append(payment_id)
				self.pool.get('hr_payroll_cr.absence').write(cr,uid, id, {'payment_per_contract_line': payment_id})
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'absence_per_contract_line': [(0, 0, ppcl_ind)]})
		return amount_total

# This function calculates all the over_salary for a given contract, and create an over_salary_payment for each one
#recieves a contract, an amount to calculate on, a payment per contract and a date
#creates a payment per contract line and a over salary payment
	def _over_salary_half(self, cr, uid, contract_id, gross_salary, payment_per_contract, date, payment, calculated_on):
		over_salary_search = self.pool.get('hr_payroll_cr.over_salary').search(cr,uid,[('contract','=',contract_id), ('calculated_on_base_salary', '=', calculated_on)])
		contract = self.pool.get('hr.contract').browse(cr,uid,contract_id)
		amount = 0
		amount_total = 0
		today = time.strftime('%Y-%m-%d')
		ppcl_list = []
		for id in over_salary_search:
			over_salary_browse = self.pool.get('hr_payroll_cr.over_salary').browse(cr,uid,id)
			over_salary_percent = over_salary_browse.percent
			over_salary_amount = over_salary_browse.amount
			over_salary_detail = over_salary_browse.detail
			if (over_salary_percent == True):
				if (over_salary_browse.calculated_on_base_salary == True):
					contract = self.pool.get('hr.contract').browse(cr,uid,contract_id)
					wage = contract.wage
					amount = ((wage / 100) * over_salary_amount) / 2
				else:
					amount = ((gross_salary / 100) * over_salary_amount) / 2
			else:
				amount = over_salary_amount / 2
			payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':6, 'detail':over_salary_detail + ' - Over Salary','amount':amount, 'date':datetime.date.today(), 'payment_per_contract':payment_per_contract, 'account':over_salary_browse.account.id, 'payment':payment })
			over_salary_payment_id = self.pool.get('hr_payroll_cr.over_salary_payment').create(cr,uid,{'detail':over_salary_detail,'amount':amount, 'date':date, 'percent': over_salary_percent, 'payment_per_contract_line': payment_id, 'over_salary': id, 'payment_date':datetime.date.today() })
			ppcl_list.append(payment_id)
			#creates or modifies an entrie on the dictionary to build the payment per contract lines later
			amount_total = amount_total + amount
			over_salary_account = over_salary_browse.account.id
			over_salary_type_name = ''
			key = over_salary_type_name + str(over_salary_account)
			if (key in self.over_salary_payment_dictionary):
				self.over_salary_payment_dictionary[key]['amount'] = self.over_salary_payment_dictionary[key]['amount'] + amount
				self.over_salary_payment_dictionary[key]['payment_per_contract_line'].append(payment_id)
			else:
				self.over_salary_payment_dictionary[key] = {'type':over_salary_type_name,'amount':amount,'account':over_salary_account,'payment_per_contract_line':[payment_id]}
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'over_salary_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return amount_total
	
#Commission takes all the commission of a given contract an create a payment_per_contract_line
#recieves a payment per contract and a contract
	def _commission (self, cr, uid, contract_id, payment_per_contract, payment):
		month = ''
		if 10 - datetime.date.today().month > 0:
			month = '0' + str(datetime.date.today().month)
		else:
			month = str(datetime.date.today().month)
		initdate = self.str2date(str(datetime.date.today().year) + '-' + month + '-01')
		last_day = calendar.monthrange(datetime.date.today().year, datetime.date.today().month)[1]

		finaldate = self.str2date(str(datetime.date.today().year) + '-' + str(month) + '-' + str(last_day)) #FAIL AT FEBRUARY

		commission_search = self.pool.get('hr_payroll_cr.commission').search(cr,uid,[('contract','=',contract_id), ('date', '<=', finaldate), ('date', '>=', initdate)])
		contract = self.pool.get('hr.contract').browse(cr,uid,contract_id)
		amount = 0
		amount_total = 0
		ppcl_list = []
		today = datetime.date.today()
		for id in commission_search:
			commission_browse = self.pool.get('hr_payroll_cr.commission').browse(cr,uid,id)
			commission_amount = commission_browse.amount
			commission_detail = commission_browse.detail
			commission_percent = commission_browse.percent
			if (commission_percent == True):
				amount = (contract.wage / 100) * commission_amount
			else:
				amount = commission_amount
			amount_total = amount_total + amount
			payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':7, 'detail':commission_detail + ' - Commission','amount':amount, 'date':datetime.date.today(), 'payment_per_contract':payment_per_contract, 'account':commission_browse.account.id, 'payment':payment})
			ppcl_list.append(payment_id)
			self.pool.get('hr_payroll_cr.commission').write(cr,uid, id, {'payment_per_contract_line': payment_id})
			#creates or modifies an entrie on the dictionary to build the payment per contract lines later
			commission_account = commission_browse.account.id
			commission_type_name = ''
			key = commission_type_name + str(commission_account)
			if (key in self.commission_payment_dictionary):
				self.commission_payment_dictionary[key]['amount'] = self.commission_payment_dictionary[key]['amount'] + amount
				self.commission_payment_dictionary[key]['payment_per_contract_line'].append(payment_id)
			else:
				self.commission_payment_dictionary[key] = {'type':commission_type_name,'amount':amount,'account': commission_account,'payment_per_contract_line':[payment_id]}
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'commission_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return amount_total
		
#############################################
#Method to calculate the amount paid per rent
#############################################
	def _rent_tax(self, cr, uid, contract_id, pre_gross_salary, payment_per_contract, date, payment):
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
		employee_id = contract.employee_id.id
		debug(employee_id)
		employee = self.pool.get('hr.employee').browse(cr, uid, employee_id)
		apply_rent = employee.apply_rent
		children = employee.children_for_rent_tax
		amount_total = 0
		siblings_amount = 0
		if apply_rent:
				siblings_amount = 1820 + (children * 1230)
		if pre_gross_salary > 307500 and pre_gross_salary <= 488500:
			amount_total = siblings_amount + (pre_gross_salary * 0.10) / 2
		elif pre_gross_salary > 488500:
			amount_total = siblings_amount + (pre_gross_salary * 0.15) / 2
		else:
			amount_total = siblings_amount / 2
		debug(siblings_amount)
		debug(amount_total)
		payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'detail':'Rent tax','amount':amount_total, 'date':date, 'payment_per_contract':payment_per_contract, 'payment':payment})
		rent = self.pool.get('hr_payroll_cr.rent_tax').create(cr, uid, {'contract':contract_id, 'amount':amount_total, 'date':date, 'payment_per_contract_line':payment_id})		
		debug(amount_total)
		return amount_total

	def _rent_tax_complete(self, cr, uid, contract_id, pre_gross_salary, payment_per_contract, date, payment):
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
		employee_id = contract.employee_id.id
		employee = self.pool.get('hr.employee').browse(cr, uid, employee_id)
		apply_rent = employee.apply_rent
		children = employee.children_for_rent_tax
		amount_total = 0
		amount = 0
		siblings_amount = 0
		month = self.str2date(date).month
		year = self.str2date(date).year
		month_str = ''
		if month < 10:
			month_str = '0' + str(month)
		else:
			month_str = str(month)
		
		first_day_month = self.str2date(str(year) + '-' + month_str + '-' + '01')
		older_payments = self.pool.get('hr_payroll_cr.payment_per_contract').search(cr, uid, [('contract', '=', contract_id), ('payroll_date', '<', date), ('payroll_date', '>=', first_day_month)])
		total_gross = 0
		for old_pay in older_payments:
			older_payments_browse = self.pool.get('hr_payroll_cr.payment_per_contract').browse(cr, uid, old_pay)
			total_gross = total_gross + older_payments_browse.gross_salary
		if apply_rent:
				siblings_amount = 1820 + (children * 1230)
		if total_gross > 615000 and total_gross <= 977000:
			amount = siblings_amount + (total_gross * 0.10)
		elif total_gross > 977000:
			amount = siblings_amount + (total_gross * 0.15)
		else:
			amount = siblings_amount
		debug(total_gross)
		debug(amount)
		first_rent_amount = 0
		first_rent = self.pool.get('hr_payroll_cr.rent_tax').search(cr, uid, [('contract', '=', contract_id), ('date', '>=', first_day_month), ('date', '<', date)])
		if first_rent != []:
			first_rent_browse = self.pool.get('hr_payroll_cr.rent_tax').browse(cr, uid, first_rent[0])
			first_rent_amount = first_rent_browse.amount
		else:
			first_rent_amount = 0
		debug(first_rent_amount)
		debug(amount_total)
		amount_total = amount - first_rent_amount
		
		rent = self.pool.get('hr_payroll_cr.rent_tax').create(cr, uid, {'contract':contract_id, 'amount':amount_total})		
		payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'detail':'Rent tax','amount':amount_total, 'date':date, 'payment_per_contract':payment_per_contract, 'payment':payment})
		self.pool.get('hr_payroll_cr.rent_tax').write(cr, uid, rent, {'payment_per_contract_line':payment_id})
		return amount_total
#adds or substracts an amount defined in the other income table, the amount on the table can be negative or positive
#recieves a contract, payment per contract and a range of dates
#creates a payment per contract line
	def _other_income(self, cr, uid, contract_id, payment_per_contract, mindate, maxdate, payment, calculated_on):
		other_income_search = self.pool.get('hr_payroll_cr.other_income').search(cr,uid,[('contract',"=",contract_id), ('calculated_on_base_salary', '=', calculated_on),('date', '<=', maxdate), ('date', '>=', mindate)])
		contract = self.pool.get('hr.contract').browse(cr,uid,contract_id)
		amount = 0
		amount_total = 0
		ppcl_list = []
		for id in other_income_search:
			other_income_browse = self.pool.get('hr_payroll_cr.other_income').browse(cr,uid,id)
			debug(other_income_browse.payment_per_contract_line)
			if not other_income_browse.payment_per_contract_line:
				other_income_detail = other_income_browse.detail
				amount = other_income_browse.amount
				amount_total = amount_total + amount
				today = time.strftime('%Y-%m-%d')
				payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':3, 'detail':other_income_detail + ' - Other Income','amount':amount, 'date':datetime.date.today(), 'payment_per_contract':payment_per_contract, 'account':other_income_browse.account.id, 'payment':payment})
				ppcl_list.append(payment_id)
				self.pool.get('hr_payroll_cr.other_income').write(cr,uid, id, {'payment_per_contract_line': payment_id})
				#creates or modifies an entrie on the dictionary to build the payment per contract lines later
				other_inc_account = other_income_browse.account.id
				other_inc_type_name = ''
				key = other_inc_type_name + str(other_inc_account)
				if (key in self.other_income_payment_total):
					self.other_income_payment_total[key]['amount'] = self.other_income_payment_total[key]['amount'] + amount
					self.other_income_payment_total[key]['payment_per_contract_line'].append(payment_id)
				else:
					self.other_income_payment_total[key] = {'type':other_inc_type_name,'amount':amount,'account':other_inc_account,'payment_per_contract_line':[payment_id]}
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'other_income_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return amount_total

#returns the total amount of extra hours to be paid, and create a payment per contract line of extra hours 
#recieves a contract, payment per contract and a range of dates
#calculates the amount to be paid per hour, then takes the amount of extra hours worked and multiply it by the field multiplier
#multiplier indicates how the extra hour is gonna be paid, for example if multiplier = 1.5, and the hour is paid by $2, then the extra hour is gonna be paid $3
	def _extra_hour(self, cr, uid, contract_id, payment_per_contract, mindate, maxdate, payment):
		#gets the ids of the extra hours per the contract and in the range of given dates
		extra_hours = self.pool.get('hr_payroll_cr.extra_hour').search(cr,uid,[('contract',"=",contract_id), ('date', '<=', maxdate), ('date', '>=', mindate)])
		total_hours = 0 #amount of payment per extra hours
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)

		#debug(contract_id)
		ppcl_list = []
		today = datetime.date.today()
		#debug(contract.working_schedule)
		working_schedule = self.pool.get('hr_payroll_cr.working_schedule').browse(cr, uid, contract.working_schedule.id)
		#debug(working_schedule.hoursperday)
		payment_per_hour = (contract.wage / 30) / working_schedule.hoursperday
		for eh in extra_hours:
			fields_extra = self.pool.get('hr_payroll_cr.extra_hour').browse(cr, uid, eh)
			total_hours_add = payment_per_hour * fields_extra.multiplier * fields_extra.hours
			total_hours = total_hours + total_hours_add

			ppcl = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr, uid, {'type':8, 'amount' : total_hours_add, 'detail' : 'Extra Hours', 'payment_per_contract':payment_per_contract, 'account':fields_extra.account.id, 'date':datetime.date.today(), 'payment':payment})
			ppcl_list.append(ppcl)

			self.pool.get('hr_payroll_cr.extra_hour').write(cr, uid, eh, {'payment_per_contract_line' : ppcl})
			#creates or modifies an entrie on the dictionary to build the payment per contract lines later
			e_h_account = fields_extra.account.id
			e_h_type_name = ''
			key = e_h_type_name + str(e_h_account)
			if (key in self.extra_hour_payment_dictionary):
				self.extra_hour_payment_dictionary[key]['amount'] = self.extra_hour_payment_dictionary[key]['amount'] + total_hours_add
				self.extra_hour_payment_dictionary[key]['payment_per_contract_line'].append(ppcl)
			else:
				self.extra_hour_payment_dictionary[key] = {'type':e_h_type_name,'amount':total_hours_add,'account':e_h_account,'payment_per_contract_line':[ppcl]}	
	#debug(ppcl_list)
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'extra_hour_per_contract_line': [(0, 0, ppcl_ind)]})
		return total_hours	

#returns the amount to be paid for concept of worked holidays
#recieves a contract, a payment per contract and a range of dates
#creates a payment per contract line
#calculates the amount to be paid per day, search the schedule assigned to the contract, and calculates the amount per day according to the hours per day defined in the schedule	
	def _working_holiday(self, cr, uid, contract_id, payment_per_contract, mindate, maxdate, payment):
		working_holiday = self.pool.get('hr_payroll_cr.working_holiday').search(cr,uid,[('contract',"=",contract_id), ('date', '<=', maxdate), ('date', '>=', mindate)])
		total_holiday = 0 #amount of payment per worked holiday
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
		company = self.pool.get('res.company').browse(cr, uid, contract.company_id)
		base_salary = contract.wage
		working_schedule = self.pool.get('hr_payroll_cr.working_schedule').browse(cr, uid, contract.working_schedule.id)
		pay_per_day = ((base_salary/30) / working_schedule.hoursperday) * company.working_holiday_percent_payment
		ppcl_list = []
		for wh in working_holiday:
			fields_holiday = self.pool.get('hr_payroll_cr.working_holiday').browse(cr, uid, wh)
			pay_per_day = pay_per_day * fields_holiday.hours
			if not fields_holiday.payment_per_contract_line:
				total_holiday = total_holiday + pay_per_day
				ppcl = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid, {'type':9, 'amount' : pay_per_day, 'detail' : 'Working Holiday', 'payment_per_contract':payment_per_contract, 'account':fields_holiday.account.id, 'date':datetime.date.today(), 'payment':payment})
				ppcl_list.append(ppcl)
				self.pool.get('hr_payroll_cr.working_holiday').write(cr, uid, wh, {'payment_per_contract_line' : ppcl})
				#creates or modifies an entrie on the dictionary to build the payment per contract lines later
				w_h_account = fields_holiday.account.id
				w_h_type_name = ''
				key = w_h_type_name + str(w_h_account)
				if (key in self.working_holiday_payment_dictionary):
					self.working_holiday_payment_dictionary[key]['amount'] = self.working_holiday_payment_dictionary[key]['amount'] + pay_per_day
					self.working_holiday_payment_dictionary[key]['payment_per_contract_line'].append(ppcl)
				else:
					self.working_holiday_payment_dictionary[key] = {'type':w_h_type_name,'amount':pay_per_day,'account':w_h_account,'payment_per_contract_line':[ppcl]}
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'working_holiday_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return total_holiday

#returns the total amount to reduce for concept of permits
#creates a payment per contract line if the permit is without salary
#recieves a contract, a payment per contract a date and a payment
#search the permit per day that havent been paid
	def _permit(self, cr, uid, contract_id, payment_per_contract, date, payment):
		permit_search = self.pool.get('hr_payroll_cr.permit').search(cr,uid,[('contract','=',contract_id)])
		permit_detail = ''
		amount_total = 0
		ppcl_list = []
		for id in permit_search:
			permit_browse = self.pool.get('hr_payroll_cr.permit').browse(cr,uid,id)
			permit_per_day = self.pool.get('hr_payroll_cr.permit_per_day').search(cr, uid, [('permit', '=', id)])
			contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
			base_salary = contract.wage
			reduce_per_day = base_salary/30
			permit_detail = permit_browse.detail
			if not permit_browse.with_salary:
				for ppd in permit_per_day:
					ppd_browse = self.pool.get('hr_payroll_cr.permit_per_day').browse(cr, uid, ppd)				
					if not ppd_browse.payment_per_contract_line and ppd_browse.date <= date:
						amount_total = amount_total + reduce_per_day
						#debug(reduce_per_day)
						ppcl = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':10, 'detail':permit_detail + ' - Permit','amount':reduce_per_day, 'payment_per_contract':payment_per_contract, 'payment':payment, 'date':date})
						ppcl_list.append(ppcl)
						self.pool.get('hr_payroll_cr.permit_per_day').write(cr, uid, ppd, {'payment_per_contract_line' : ppcl})
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'permit_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return amount_total

#Returns the amount to pay for incapacity period
#recieves a date, a contract and a payment per contract and a payment
#pays the incapacity days that havent been paid before the specified date
#checks the incapacity period per day of the incapacity period, each incapacity period per day specifies the amount to be paid per day
	def _incapacity_period(self, cr, uid, contract_id, payment_per_contract, date, payment):
		incapacity_search = self.pool.get('hr_payroll_cr.incapacity_period').search(cr, uid, [('contract', '=', contract_id), ('start_date', '<=', date)])
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
		amount = 0
		ppcl_list = []
		for ins in incapacity_search:
			inc_brow = self.pool.get('hr_payroll_cr.incapacity_period').browse(cr, uid, ins)
			inc_per_day = self.pool.get('hr_payroll_cr.incapacity_period_per_day').search(cr, uid, [('incapacity_period', '=', inc_brow.id)])
			inc_type = self.pool.get('hr_payroll_cr.incapacity_period_type').browse(cr, uid, inc_brow.incapacity_period_type.id)
			amount_reduction = 0
			contract_per_day = contract.wage / 30
			payment_id = None
			for ipd in inc_per_day:
				ipd_fields = self.pool.get('hr_payroll_cr.incapacity_period_per_day').browse(cr, uid, ipd)
				if ipd_fields.date <= date and not ipd_fields.paid and ipd_fields.reflectible:
					if ipd_fields.percent:
						perc = ipd_fields.amount / 100
						amount_reduction = perc * contract_per_day
						amount = amount + amount_reduction
					else:
						amount_reduction = ipd_fields.amount
						amount = amount + amount_reduction
					ppcl = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid, {'type':11, 'amount' : amount_reduction, 'detail' : inc_brow.detail + ' - Incapacity Period', 'payment_per_contract':payment_per_contract, 'account':ipd_fields.account, 'date':date, 'payment':payment})
					ppcl_list.append(ppcl)
					self.pool.get('hr_payroll_cr.incapacity_period_per_day').write(cr, uid, ipd, {'payment_per_contract_line' : ppcl, 'paid':True})
			inc_brow_account = inc_type.account.id
			#debug(inc_type)
			#debug(inc_type.name)
			inc_type_name = inc_type.name
			key = inc_type_name + str(inc_brow_account)
			if (key in self.incapacity_payment_dictionary):
				self.incapacity_payment_dictionary[key]['amount'] = self.incapacity_payment_dictionary[key]['amount'] + amount_reduction
				self.incapacity_payment_dictionary[key]['payment_per_contract_line'].append(payment_id)
			else:
				self.incapacity_payment_dictionary[key] = {'type':inc_type_name, 'amount': amount_reduction, 'account': inc_brow_account, 'payment_per_contract_line' : [payment_id]}
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'incapacity_period_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return amount
#returns the amount supposed to be paid in the given holiday period
#this doenst create a payment per contract line because this is just informative
	def _holiday_period(self, cr, uid, contract_id, mindate, maxdate):
		holiday_search = self.pool.get('hr_payroll_cr.holiday_per_contract').search(cr, uid, [('contract', '=', contract_id)])
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
		amount = 0
		for hol in holiday_search:
			hol_brow = self.pool.get('hr_payroll_cr.holiday_per_contract').browse(cr, uid, hol)
			hol_period_id = self.pool.get('hr_payroll_cr.holiday_period').search(cr, uid, [('holiday', '=', hol)])
			hol_per_day = self.pool.get('hr_payroll_cr.holiday_per_day').search(cr, uid, [('holiday_period', '=', hol_period_id[0])])
			amount_reduction = contract.wage / 30
			total_reduction = 0
			for hd in hol_per_day:
				hd_fields = self.pool.get('hr_payroll_cr.holiday_per_day').browse(cr, uid, hd)
				if hd_fields.date <= maxdate and  hd_fields.date >= mindate and not hd_fields.paid:
					self.pool.get('hr_payroll_cr.holiday_per_day').write(cr, uid, hd, {'paid':True})
					total_reduction = total_reduction + amount_reduction
		return total_reduction

#returns the exonerated amount of the retirement fund, needs the amount of payment with the other reductions before the gross salary
	def _exonerated_retirement_fund(self, cr, uid, contract_id, amount_so_far, date, payment_per_contract, payment):
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
		company = self.pool.get('res.company').browse(cr, uid, contract.company_id)
		company_retirement_fund_percent = company.exonerated_retirement_fund_percent
		max_exonerated = 0
		ppcl_list = []
		retirement_fund_search = self.pool.get('hr_payroll_cr.retirement_fund').search(cr, uid, [('contract', '=', contract_id)])
		#debug(retirement_fund_search)
		if len(retirement_fund_search) > 0:
			rfs = self.pool.get('hr_payroll_cr.retirement_fund').browse(cr, uid, retirement_fund_search[0])
			retirement_fund_percent = rfs.percent
			if retirement_fund_percent < company_retirement_fund_percent:
				max_exonerated = amount_so_far * (retirement_fund_percent / 100)
			else:
				max_exonerated = amount_so_far * (company_retirement_fund_percent / 100)
			today = datetime.date.today()
			payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':12, 'amount':max_exonerated, 'date':datetime.date.today(), 'account':rfs.account.id, 'payment_per_contract':payment_per_contract, 'payment':payment, 'detail':'-Exonerated retirement fund'})
			ppcl_list.append(payment_id)
			erf = self.pool.get('hr_payroll_cr.exonerated_retirement_fund').create(cr, uid, {'amount' : max_exonerated, 'detail' : '', 'percent' : retirement_fund_percent, 'date' : datetime.date.today(), 'retirement_fund' : retirement_fund_search[0], 'payment_per_contract_line':payment_id})
			self.pool.get('hr_payroll_cr.retirement_fund').write(cr,uid,retirement_fund_search,{'amount': max_exonerated})
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'retirement_fund_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return max_exonerated	

#returns the amount to reduce for deductions
#recieves a contract, a salary to reduce on, a payment per contract and a payment
#creates a payment per contract line
#checks if the deduction is a percent of the salary, a plain amount or a python code
	def _deduction(self, cr, uid, contract_id, gross_salary, payment_per_contract, payment):
		amount = 0
		ppcl_list = []
		per = False
		deduction_search = self.pool.get('hr_payroll_cr.deduction').search(cr,uid,[('contract','=',contract_id)])
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
		employee = self.pool.get('hr.employee').browse(cr, uid, contract.employee_id.id)
		for deds in deduction_search:
			deduction_browse = self.pool.get('hr_payroll_cr.deduction').browse(cr, uid, deds)
			deduction_type_browse = self.pool.get('hr_payroll_cr.deduction_type').browse(cr, uid, deduction_browse.deduction_type.id)
			amount_reduction = 0
			if deduction_browse.calc_method == 'P':
				per = True
				amount_reduction = gross_salary * (deduction_browse.amount / 100)
				amount = amount + amount_reduction
			elif deduction_browse.calc_method == 'A':
				amount_reduction = deduction_browse.amount
				amount = amount + amount_reduction
			elif deduction_browse.calc_method == 'C':
				company = self.pool.get('res.company').browse(cr, uid, contract.company_id.id)
				dictionary = {'gross_salary':gross_salary, 'contract':contract, 'employee':employee, 'company':company}
				exec string.replace(deduction_type_browse.code, '\r\n', '\n') in dictionary
				amount_reduction = dictionary['result'] #result is the variable where the final amount of the calc for deduction must be in the code field 

				amount = amount + amount_reduction
			debug(deduction_type_browse)
			debug(deduction_type_browse.name)
			debug(deduction_type_browse.detail)
			ppcl = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr, uid, {'type':4, 'amount' : amount_reduction, 'detail' : deduction_type_browse.name + ' - ' + deduction_type_browse.detail + ' - Deduction', 'payment_per_contract':payment_per_contract, 'account':deduction_type_browse.account.id, 'date':datetime.date.today(), 'payment':payment})
			ppcl_list.append(ppcl)
			dl = self.pool.get('hr_payroll_cr.deduction_line').create(cr, uid, {'deduction' : deds, 'amount' : amount_reduction, 'date' : datetime.date.today(), 'percent' : per, 'total' : amount_reduction, 'payment_per_contract_line' : ppcl})
			
			deduction_type_name = deduction_browse.name
			deduction_type_account = deduction_browse.account.id
			key = deduction_type_name + str(deduction_type_account)
			if (key in self.deduction_payment_dictionary):
				self.deduction_payment_dictionary[key]['amount'] = self.deduction_payment_dictionary[key]['amount'] + amount_reduction
				self.deduction_payment_dictionary[key]['payment_per_contract_line'].append(ppcl)
			else:
				self.deduction_payment_dictionary[key] = {'type':deduction_type_name, 'amount':amount_reduction, 'account': deduction_type_account, 'payment_per_contract_line' : [ppcl]}
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'deduction_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return amount

# Taxed retirement fund calculation
#takes the amount of the retirement fund specified in the contract and subs the exonerated amount of the retirement fund
	def _taxed_retirement_fund(self, cr, uid, contract_id, gross_salary, payment_per_contract, payment):
		retirement_fund_search = self.pool.get('hr_payroll_cr.retirement_fund').search(cr,uid,[('contract', '=', contract_id)])
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
		company = self.pool.get('res.company').browse(cr, uid, contract.company_id.id)
		retirement_fund_percent = company.exonerated_retirement_fund_percent
		today = time.strftime('%Y-%m-%d')
		amount_total = 0
		exonerated_amount = 0
		ppcl_list = []
		for id in retirement_fund_search:
			retirement_fund_browse = self.pool.get('hr_payroll_cr.retirement_fund').browse(cr,uid,id)
			account = retirement_fund_browse.account.id
			exonerated_percent = retirement_fund_browse.percent - retirement_fund_percent
			if exonerated_percent < 0:
				exonerated_percent = 0
			taxed_percent = retirement_fund_percent - exonerated_percent
			exonerated_amount = retirement_fund_browse.amount
			if (taxed_percent <= 0):
				taxed_id = self.pool.get('hr_payroll_cr.taxed_retirement_fund').create(cr, uid, {'type':12, 'amount' : 0, 'date':today, 'percent' : 0, 'retirement_fund':id})
				return 0
			else:
				amount = (gross_salary / 100) * taxed_percent
				amount_total = amount_total + amount
				exonerated_amount = exonerated_amount + amount
				payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'amount':exonerated_amount, 'date':datetime.date.today(), 'account':account, 'payment_per_contract':payment_per_contract, 'payment':payment, 'detail':'-Taxed retirement fund'})
				ppcl_list.append(payment_id)
				taxed_id = self.pool.get('hr_payroll_cr.taxed_retirement_fund').create(cr, uid, {'amount' : amount, 'date':today, 'percent' : taxed_percent, 'retirement_fund':id, 'payment_per_contract_line': payment_id})
				self.pool.get('hr_payroll_cr.retirement_fund').write(cr,uid,id,{'amount': exonerated_amount})
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'retirement_fund_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return amount_total

	def _foreclosure(self, cr, uid, contract_id, payment_per_contract, payment, mindate, date):	
		foreclosure_search = self.pool.get('hr_payroll_cr.foreclosure').search(cr, uid, [('contract', '=', contract_id), ('start_date', '<=', date)])
		amount_total = 0
		ppcl_list = []
		today = time.strftime('%Y-%m-%d')
		for id in foreclosure_search:
			foreclosure_browse = self.pool.get('hr_payroll_cr.foreclosure').browse(cr,uid,id)
			if self.str2date(mindate).day == 15 and not foreclosure_browse.second_fortnight:
				amount_total = 0
			elif self.str2date(mindate).day == 1 and not foreclosure_browse.first_fortnight:
				amount_total = 0
			else:	
				balance = foreclosure_browse.balance
				active = foreclosure.active
				if active:
					foreclosure_detail = foreclosure_browse.detail
					foreclosure_reduction = 0
					foreclosure_type_id = foreclosure_browse.foreclosure_type.id
					foreclosure_account = foreclosure_browse.account.id				
					quota = foreclosure_browse.quota
					foreclosure_reduction = quota
					amount_total = amount_total + foreclosure_reduction
					balance = balance + quota				
					foreclosure_type_browse = self.pool.get('hr_payroll_cr.foreclosure_type').browse(cr,uid,foreclosure_type_id)
					if not foreclosure_browse.name:
						foreclosure_type_name = "No Foreclosure type"
					else:
						foreclosure_type_name = foreclosure_browse.name
					payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':2, 'detail':foreclosure_detail + ' - foreclosure reduction','amount':foreclosure_reduction, 'date':date, 'payment_per_contract':payment_per_contract, 'account':foreclosure_browse.account.id, 'payment':payment})
					
					ppcl_list.append(payment_id)
					foreclosure_id = self.pool.get('hr_payroll_cr.foreclosure_payment').create(cr,uid,{'payment':foreclosure_reduction, 'foreclosure':id, 'balance': balance, 'payment_per_contract_line': payment_id, 'date': date})
					self.pool.get('hr_payroll_cr.foreclosure').write(cr,uid,id,{'balance': balance})
					key = foreclosure_type_name + str(foreclosure_account)
					if (key in self.foreclosure_payment_dictionary):
						self.foreclosure_payment_dictionary[key]['amount'] = self.foreclosure_payment_dictionary[key]['amount'] + foreclosure_reduction
						self.foreclosure_payment_dictionary[key]['payment_per_contract_line'].append(payment_id)
					else:
						self.foreclosure_payment_dictionary[key] = {'type':foreclosure_type_name, 'amount':foreclosure_reduction, 'account': foreclosure_account, 'payment_per_contract_line' : [payment_id]}
		if not ppcl_list == []:
			ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
			#debug(total_hours)
			for ppcl_ind in ppcl_read:
				self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'foreclosure_per_contract_line': [(0, 0, ppcl_ind)]})
			
		return amount_total

#loan calculation for each contract
#search for the loans of the contract, verifies if the balance is 0, if it is not 0 then calculates the quota and subs it from the balance
#creates a loan payment
	def _loan(self, cr, uid, contract_id, payment_per_contract, payment, mindate, date):	
		loan_search = self.pool.get('hr_payroll_cr.loan').search(cr, uid, [('contract', '=', contract_id), ('start_date', '<=', date)])
		amount_total = 0
		amount = 0
		ppcl_list = []
		today = time.strftime('%Y-%m-%d')
		for id in loan_search:
			loan_browse = self.pool.get('hr_payroll_cr.loan').browse(cr,uid,id)
			if self.str2date(mindate).day == 15 and not loan_browse.second_fortnight:
				amount_total = 0
			elif self.str2date(mindate).day == 1 and not loan_browse.first_fortnight:
				amount_total = 0
			else:	
				balance = loan_browse.balance
				if balance > 0:
					
					loan_detail = loan_browse.detail
					amount = loan_browse.principal
					interest = loan_browse.interest / 100
					loan_reduction = 0
					loan_type_id = loan_browse.loan_type.id
					loan_account = loan_browse.account.id
					
					paid_interests = balance * interest
					reduced = 0
					if loan_browse.fixed_quota:
						quota = loan_browse.quota
						loan_reduction = quota - (balance * interest)
						amount_total = amount_total + loan_reduction
						balance = balance - quota
						reduced = quota
					else:
						loan_term = loan_browse.term
						loan_reduction = (amount / loan_term) + (balance * interest)
						amount_total = amount_total + loan_reduction
						balance = balance - (amount / loan_term)
						reduced = amount / loan_term
					loan_type_browse = self.pool.get('hr_payroll_cr.loan_type').browse(cr,uid,loan_type_id)
					if not loan_browse.name:
						loan_type_name = "No Loan type"
					else:
						loan_type_name = loan_browse.name
					payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':2, 'detail':loan_detail + ' - Loan reduction','amount':reduced, 'date':date, 'payment_per_contract':payment_per_contract, 'account':loan_browse.account.id, 'payment':payment})
					payment_interest = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':2, 'detail':loan_detail + ' - Loan interests','amount':paid_interests, 'date':date, 'payment_per_contract':payment_per_contract, 'account':loan_browse.account.id, 'payment':payment})
					
					ppcl_list.append(payment_id)
					ppcl_list.append(payment_interest)
					loan_id = self.pool.get('hr_payroll_cr.loan_payment').create(cr,uid,{'payment':loan_reduction, 'loan':id, 'balance': balance, 'payment_per_contract_line': payment_id, 'date': date})
					self.pool.get('hr_payroll_cr.loan').write(cr,uid,id,{'balance': balance})
					key = loan_type_name + str(loan_account)
					if (key in self.loan_payment_dictionary):
						self.loan_payment_dictionary[key]['amount'] = self.loan_payment_dictionary[key]['amount'] + loan_reduction
						self.loan_payment_dictionary[key]['payment_per_contract_line'].append(payment_id)
					else:
						self.loan_payment_dictionary[key] = {'type':loan_type_name, 'amount':loan_reduction, 'account': loan_account, 'payment_per_contract_line' : [payment_id]}
		if not ppcl_list == []:
			ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
			#debug(total_hours)
			for ppcl_ind in ppcl_read:
				self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'loan_per_contract_line': [(0, 0, ppcl_ind)]})
			
		return amount_total

#amount per refunds
#a refund is made only 1 time
	def _refund(self, cr, uid, date, contract_id, payment_per_contract, payment):
		refunds = self.pool.get('hr_payroll_cr.refund').search(cr, uid, [('contract', '=', contract_id), ('paid', '=', False)])
		amount = 0
		ppcl_list = []
		for ref_id in refunds:
			refund_browse = self.pool.get('hr_payroll_cr.refund').browse(cr, uid, ref_id)
			amount = amount + refund_browse.amount
			ppcl = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr, uid, {'type':1, 'amount' : refund_browse.amount, 'detail' : refund_browse.detail + ' - Refund', 'payment_per_contract':payment_per_contract, 'account':refund_browse.account.id, 'date':date, 'payment':payment})
			ppcl_list.append(ppcl)	
			self.pool.get('hr_payroll_cr.refund').write(cr, uid, refund_browse.id, {'payment_per_contract_line':ppcl, 'paid': True})
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'refund_per_contract_line': [(0, 0, ppcl_ind)]})		
		return amount

#returns the amount reduced by savings
#looks for the saving of the contract, if it is active, verifies if the amount is a percent of the payment or a fixed amount and adds it to the amount saved so far
#creates a saving quota	
	def _saving(self, cr, uid, contract_id, gross_salary, payment_per_contract, payment, date):
		debug(contract_id)
		savings = self.pool.get('hr_payroll_cr.saving').search(cr, uid, [('contract', '=', contract_id), ('start_date', '<=', date)])
		amount = 0
		ppcl_list = []
		for sv in savings:
			amount_reduction = 0
			saving_browse = self.pool.get('hr_payroll_cr.saving').browse(cr, uid, sv)
			if saving_browse.saving_active:
				if saving_browse.percent:
					amount_reduction = (saving_browse.quota / 100) * gross_salary
					amount = amount + amount_reduction
				else:
					amount_reduction = saving_browse.quota
					amount = amount + amount_reduction

				total = amount + saving_browse.total
				ppcl = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr, uid, {'type':1, 'amount' : amount_reduction, 'detail' : saving_browse.detail + ' - Saving', 'payment_per_contract':payment_per_contract, 'account':saving_browse.account.id, 'date':date, 'payment':payment})
				sq = self.pool.get('hr_payroll_cr.saving_quota').create(cr, uid, {'date': date, 'quota': amount, 'saving': sv, 'total': saving_browse.total, 'payment_per_contract_line': ppcl,})
				self.pool.get('hr_payroll_cr.saving').write(cr, uid, sv, {'total':total})
				ppcl_list.append(ppcl)
				saving_type_id = saving_browse.type
				saving_account = saving_browse.account.id
				saving_type_browse = self.pool.get('hr_payroll_cr.saving_type').browse(cr,uid,saving_type_id.id)
				if not saving_type_browse.name:
					saving_type_name = "No Saving type"
				else:
					saving_type_name = saving_browse.name
				key = saving_type_name + str(saving_account)
				if (key in self.saving_payment_dictionary):
					self.saving_payment_dictionary[key]['amount'] = self.saving_payment_dictionary[key]['amount'] + amount_reduction
					self.saving_payment_dictionary[key]['payment_per_contract_line'].append(ppcl)
				else:
					self.saving_payment_dictionary[key] = {'type':saving_type_name,'amount':amount_reduction,'account':saving_account,'payment_per_contract_line':[ppcl]}
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'saving_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return amount

# function to calculate the employeer social security
#this doesnt affect the amount of the total payment for each contract
#TODO: add this in the calculation of the payroll
	def _employer_social_security(self, cr, uid, contract_id, gross_salary, payment_per_contract, payment):
		employer_search = self.pool.get('hr_payroll_cr.employer_social_security').search(cr, uid,[('contract','=',contract_id)])
		contract = self.pool.get('hr.contract').browse(cr,uid,contract_id)
		am_per = 0
		ppcl_list = []
		per = False
		amount_reduction = 0
		amount = 0
		for ess in employer_search:
			employer_browse = self.pool.get('hr_payroll_cr.employer_social_security').browse(cr, uid, ess)
			ess_type_browse = self.pool.get('hr_payroll_cr.employer_social_security_type').browse(cr,uid,employer_browse.employer_social_security_type.id)
			debug(employer_browse)
			if ess_type_browse.calc_method == 'P':
				per = True
				am_per = ess_type_browse.amount
				amount_reduction = gross_salary * ( am_per / 100)
				amount = amount + amount_reduction
			elif ess_type_browse.calc_method == 'A':
				amount_reduction = ess_type_browse.amount
				amount = amount + amount_reduction
				am_per = amount
			elif ess_type_browse.calc_method == 'C':
				dictionary = {'gross_salary':gross_salary, 'contract':contract, 'employee':employee}
				exec string.replace(ess_type_browse.code, '\r\n', '\n') in dictionary
				amount_reduction = dictionary['result'] #result is the variable where the final amount of the calc for deduction must be in the code field 
				amount = amount + amount_reduction
			payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr, uid, {'type':13, 'amount' : amount_reduction, 'detail' : ess_type_browse.name + ' - Employer Social Security', 'payment_per_contract':payment_per_contract, 'account':ess_type_browse.account.id, 'date':datetime.date.today(), 'payment':payment})
			ess_l = self.pool.get('hr_payroll_cr.employer_social_security_line').create(cr, uid, {'employer_social_security' : ess, 'amount' : am_per, 'start_date' : datetime.date.today(), 'end_date' : datetime.date.today(), 'percent' : per, 'total' : amount_reduction, 'payment_per_contract_line' : payment_id})
		
			ess_type_name = ess_type_browse.name
			ess_type_account = ess_type_browse.account.id
			key = ess_type_name + str(ess_type_account)
			if (key in self.employer_payment_dictionary):
				self.employer_payment_dictionary[key]['amount'] = self.employer_payment_dictionary[key]['amount'] + amount_reduction
				self.employer_payment_dictionary[key]['payment_per_contract_line'].append(payment_id)
			else:
				self.employer_payment_dictionary[key] = {'type':ess_type_name, 'amount':amount_reduction, 'account': ess_type_account, 'payment_per_contract_line' : [payment_id]}
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'employer_social_security_per_contract_line': [(0, 0, ppcl_ind)]})
		return amount


#Creates a christmas bonus if the contract has more than 3 months being active
#this doesnt affect the payroll, only accumulates the amount to be paid at the end of the year
	def _christmas_bonus(self, cr, uid, date, company, payment):
		contract_id = self.pool.get('hr.contract').search(cr, uid, [('company_id', '=', company)])
		for conts in contract_id:
			contract = self.pool.get('hr.contract').browse(cr, uid, conts)
			total = contract.christmas_bonus_amount
			debug(self.interval(datetime.date.today(), self.str2date(contract.date_start)).days)
			if self.interval(datetime.date.today(), self.str2date(contract.date_start)).days > 90:
				ppc = self.pool.get('hr_payroll_cr.payment_per_contract').create(cr, uid, {'payroll_date': date, 'contract':conts, 'total_paid':contract.christmas_bonus_amount, 'total_retained': 0, 'detail': 'Christmas Bonus', 'payment':payment, 'date':datetime.date.today()})
				cb_payment = self.pool.get('hr_payroll_cr.christmas_bonus_payment').create(cr, uid, {'date':datetime.date.today(), 'contract':conts, 'amount':contract.christmas_bonus_amount, 'payment_per_contract':ppc})
				self.pool.get('hr.contract').write(cr, uid, conts, {'christmas_bonus_amount':0})
		return total

		

###########################		
#_payroll_per_contract
#calculates the payroll for a contract
	def _payroll_per_contract(self, cr, uid, conts, mindate, maxdate, payment, payment_per_contract, date):
		over_salary = 0
		deduction = 0
		loan = 0
		debug(maxdate)
		max_date = maxdate
		over_salary_base = 0
		rent = 0
		contract = self.pool.get('hr.contract').browse(cr, uid, conts)
		date_end = contract.date_end
		debug(date_end)
		if not date_end == False:
			if date_end <= maxdate:
				max_date = date_end
		base_salary = contract.wage
		debug(max_date)
		if self.str2date(mindate).day == 1:
			debug("normal----------------------")
			over_salary_base = self._over_salary_half(cr, uid, conts, base_salary, payment_per_contract, max_date, payment, True)
		else:
			debug("complete+++++++++++++++++++++++++")
			over_salary_base = self._over_salary_complete(cr, uid, conts, base_salary, payment_per_contract, max_date, payment, True)
		absence = self._absence(cr, uid, conts, payment_per_contract, mindate, max_date, payment)
		debug(absence)
		other_income_base = self._other_income(cr, uid, conts, payment_per_contract, mindate, max_date, payment, True)
		other_income = self._other_income(cr, uid, conts, payment_per_contract, mindate, max_date, payment, False)
		incapacity = self._incapacity_period(cr, uid, conts, payment_per_contract, max_date, payment)
		debug(incapacity)
		working_holiday = self._working_holiday(cr, uid, conts, payment_per_contract, mindate, max_date, payment)
		debug(working_holiday)
		extra_hour = self._extra_hour(cr, uid, conts, payment_per_contract, mindate, max_date, payment)
		debug(extra_hour)
		permit = self._permit(cr, uid, conts, payment_per_contract, max_date, payment)
		debug(permit)
		commission = self._commission(cr, uid, conts, payment_per_contract, payment)
		debug(commission)
		pre_gross_salary = base_salary/2 - absence - incapacity - permit + working_holiday + commission + extra_hour + other_income_base
		debug(pre_gross_salary)
		if self.str2date(mindate).day == 1:
			debug("normal----------------------")
			over_salary = self._over_salary_half(cr, uid, conts, pre_gross_salary, payment_per_contract, max_date, payment, False)
		else:
			debug("complete+++++++++++++++++++++++++")
			over_salary = self._over_salary_complete(cr, uid, conts, pre_gross_salary, payment_per_contract, max_date, payment, False)
		pre_gross_salary = pre_gross_salary + over_salary
		
		if self.str2date(mindate).day == 1:
			rent = self._rent_tax(cr, uid, conts, pre_gross_salary, payment_per_contract, date, payment)
		else:
			rent = self._rent_tax_complete(cr, uid, conts, pre_gross_salary, payment_per_contract, date, payment)
		pre_gross_salary_rent = pre_gross_salary - rent
		
		exonerated_retirement_fund = self._exonerated_retirement_fund(cr, uid, conts, pre_gross_salary, fields.date, payment_per_contract, payment)
		gross_salary = pre_gross_salary_rent - exonerated_retirement_fund
		christmas_bonus = gross_salary / 12
		employer_social_security = self._employer_social_security(cr, uid, conts, gross_salary, payment_per_contract, payment)
		tef = self._taxed_retirement_fund(cr, uid, conts, gross_salary, payment_per_contract, payment)
		debug(tef)
		if self.str2date(mindate).day == 1:
			deduction = self._deduction(cr, uid, conts, gross_salary, payment_per_contract, payment)
		else:
			deduction = self._deduction_complete(cr, uid, conts, gross_salary, payment_per_contract, date, payment)
		debug(deduction)
		pre_net_salary = gross_salary  - tef - deduction		
		cb_quota = self.pool.get('hr_payroll_cr.christmas_bonus_quota').create(cr, uid, {'contract':conts, 'amount':christmas_bonus, 'date':date, 'detail':'Christmas bonus quota'})
		debug(cb_quota)
		cb_amount = contract.christmas_bonus_amount + christmas_bonus
		debug(cb_amount)
		self.pool.get('hr.contract').write(cr, uid, contract.id, {'christmas_bonus_amount':cb_amount})
		saving = self._saving(cr, uid, conts, gross_salary, payment_per_contract, payment, date)
		
		loan = self._loan(cr, uid, conts, payment_per_contract, payment, mindate, date)
		foreclosure = self._foreclosure(cr, uid, conts, payment_per_contract, payment, mindate, date)
		refund = self._refund(cr, uid, date, conts, payment_per_contract, payment)
		debug(loan)
		net_salary = pre_net_salary - loan - saving - foreclosure + other_income + refund
		retained = tef + loan + saving + foreclosure + deduction + exonerated_retirement_fund + absence + permit
		if other_income < 0:
			 retained = retained - other_income
		if other_income_base < 0:
			retained = retained - other_income_base
		self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'total_paid':net_salary, 'total_retained':retained, 'gross_salary': gross_salary})

		retirement_fund_search = self.pool.get('hr_payroll_cr.retirement_fund').search(cr,uid,[('contract', '=', conts)])
		
		if len(retirement_fund_search) > 0:
			retirement_fund_browse = self.pool.get('hr_payroll_cr.retirement_fund').browse(cr, uid, retirement_fund_search[0])
			pl = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':retirement_fund_browse.amount, 'detail':retirement_fund_browse.detail, 'payment':payment, 'account':retirement_fund_browse.account.id, 'date':datetime.date.today()})
			self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'detail':str(retirement_fund_browse.fund_operator.name) + '-Retirement Fund', 'amount':retirement_fund_browse.amount, 'date':datetime.date.today(), 'payment_per_contract':payment_per_contract, 'account':retirement_fund_browse.account.id, 'payment_line':pl, 'payment':payment})
		debug(retirement_fund_search)
#End of _payroll_per_contract
###############################

	def _unemployment_fee_per_company(self, cr, uid, company_id, payment, date):
		contract_ids = self.pool.get('hr.contract').search(cr, uid, [('company_id', '=', company_id)])
		res = 0
		for cont_id in contract_ids:
			temp = self._unemployment_fee(cr, uid, cont_id, payment, date)
			res = res + temp
		return res
		
#Unemployment fee
#calculates the salary of the last six months and gives an amount based on a table
	def _unemployment_fee(self, cr, uid, contract_id, payment, date):
		#this is the table which unempleyment fee calculation is based on
		#the keys are the amount of years worked by the contract and the values are the days to pay
		unemployment_table = {'0': 0,'0.25': 7, '0.5':14, '1':19.5, '2':20, '3':20.5, '4':21, '5':21.24, '6':21.5, '7':22, '8':22, '9':22, '10':21.5, '11':21, '12':20.5, '13':20}
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
		employee_id = contract.employee_id.id
		all_contract_ids = self.pool.get('hr.contract').search(cr, uid, [('employee_id', '=', employee_id)])
		oldest_contract = contract
		for aci in all_contract_ids:
			temp_contract = self.pool.get('hr.contract').browse(cr, uid, aci)
			if temp_contract.date_start < oldest_contract.date_start:
				oldest_contract = temp_contract
		
		debug(oldest_contract.date_start)
		company = self.pool.get('res.company').browse(cr, uid, contract.company_id)
		#calculates the dates for 6 months before, 5 months before and the first day of the month
		month = ''
		if 10 - date.month > 0:
			month = '0' + str(date.month)
		else:
			month = date.month
		initdate = str(date.year) + '-' + str(month) + '-01'
		five_months_ago_month = 0
		today_month = date.month
		today_year = date.year
		five_months_ago_year = 0
		last_month_year = 0
		last_month_month = 0
		six_months_ago_month = 0
		if today_month < 6:
			five_months_ago_year = today_year - 1
			five_months_ago_month = today_month - 5 + 12
		else:
			five_months_ago_year = today_year
			five_months_ago_month = today_month - 5
		five_months_ago_month_str = ''
		if five_months_ago_month < 10:
			five_months_ago_month_str = '0' + str(five_months_ago_month)
		else:
			five_months_ago_month_str = str(five_months_ago_month)

		five_months_ago_fifteen = str(five_months_ago_year) + '-' + five_months_ago_month_str + '-01'
		if today_month == 1:
			last_month_year = today_year - 1
			last_month_month = 12
		else:
			last_month_year = today_year
			last_month_month = today_month - 1
		last_month_month_str = ''
		if last_month_month < 10:
			last_month_month_str = '0' + str(last_month_month)
		else:
			last_month_month_str = str(last_month_month)
		last_day = calendar.monthrange(last_month_year, last_month_month)[1]
		last_month_last_day = str(last_month_year) + '-' + last_month_month_str + '-' + str(last_day)
		six_months_ago_year = ''
		if five_months_ago_month == 12:
			six_months_ago_year = today_year - 1
			six_months_ago_month = 1
		else:
			six_months_ago_year = today_year
			six_months_ago_month = five_months_ago_month - 1#verificar que se pueda convertir un '01' a int
		six_months_ago_month_str = ''
		if six_months_ago_month < 10:
			six_months_ago_month_str = '0' + str(six_months_ago_month)
		else:
			six_months_ago_month_str = str(six_months_ago_month)
		total_last_month = 0
		ppc_last_month = self.pool.get('hr_payroll_cr.payment_per_contract').search(cr, uid, [('contract', '=', contract_id), ('payroll_date', '>=', initdate)])
		debug(ppc_last_month)
		debug(initdate)
		#calculates the amount paid per day in the last month
		for ppc in ppc_last_month:
			ppc_browse = self.pool.get('hr_payroll_cr.payment_per_contract').browse(cr, uid, ppc)
			total_last_month = total_last_month + ppc_browse.total_paid
		total_last_month_per_day = total_last_month / 30 * date.day
		last_five_months = self.pool.get('hr_payroll_cr.payment_per_contract').search(cr, uid, [('contract', '=', contract_id), ('payroll_date', '<=', last_month_last_day), ('payroll_date', '>=', five_months_ago_fifteen)])
		debug(last_month_last_day)
		debug(five_months_ago_fifteen)
		debug(last_five_months)
		
		total_last_five_months = 0

		#calculates the amount per day paid in the five months before the last month
		for lfm in last_five_months:
			last_five_months_browse = self.pool.get('hr_payroll_cr.payment_per_contract').browse(cr, uid, lfm)
			total_last_five_months = total_last_five_months + last_five_months_browse.total_paid
		last_day = calendar.monthrange(six_months_ago_year, six_months_ago_month)[1]
		last_six_months_ago = str(six_months_ago_year) + '-' + six_months_ago_month_str + '-' + str(last_day)
		first_six_months_ago = str(six_months_ago_year) + '-' + six_months_ago_month_str + '-01'
		six_months_ago = self.pool.get('hr_payroll_cr.payment_per_contract').search(cr, uid, [('contract', '=', contract_id), ('payroll_date', '<=', last_six_months_ago), ('payroll_date', '>=', first_six_months_ago)])
		first_month_amount = 0

		#calculates the amount paid six months ago
		for sma in six_months_ago:
			sma_browse = self.pool.get('hr_payroll_cr.payment_per_contract').browse(cr, uid, sma)
			first_month_amount = first_month_amount + sma_browse.total_paid
		first_days = 30 - date.day
		first_month_amount_per_day = (first_month_amount / 30) * first_days
		debug(total_last_month)
		debug(total_last_five_months)
		debug(first_month_amount_per_day)
		#the three amounts added and divided by 180 is the average amount earned in the last six months (180 days)
		total = (first_month_amount_per_day + total_last_five_months + total_last_month) / 180
		#gets the amount of years worked by the employee to use it as a key for the unemployment dictionary to get the amount of days to pay
		years = date.year - self.str2date(oldest_contract.date_start).year
		
		months = date.month - self.str2date(oldest_contract.date_start).month
		if months < 0:
			years = years - 1
		if years == 0:
			if (months < 3 and months >= 0) or months < -9:
				years = 0
			elif (months >= 3 and months < 6) or (months >= -9 and months < -7):
				years = 0.25
			elif (months >= -7 and months < 0) or (months >= 6):
				years = 0.5

		debug(years)				 
		days_per_years = unemployment_table[str(years)]
		total = total * days_per_years
		payment_per_contract = self.pool.get('hr_payroll_cr.payment_per_contract').create(cr, uid, {'payroll_date':date, 'date': datetime.date.today(), 'contract': contract_id, 'detail':'Unemployment fee', 'total_paid':total})	
		self.pool.get('hr_payroll_cr.payment').write(cr, uid, payment, {'total_paid':total})
		self.pool.get('hr_payroll_cr.unemployement_fee').create(cr, uid, {'amount': total, 'contract':contract_id, 'account':company.unemployment_fee_account})
		return total


#creates the payment per contract, payment and payment lines for the first half of the month
#for all the contracts of a company
	def _payroll(self, cr, uid, ids, mindate, maxdate, date_wizard, payment, payroll_id, company_id, contract_id, cont, context=None):
		self.incapacity_payment_dictionary = { }
		self.deduction_payment_dictionary = { }
		self.other_income_payment_total = { }
		self.saving_payment_dictionary = { }
		self.loan_payment_dictionary = { }
		self.holidays_payment_dictionary = { }
		self.retirement_payment_dictionary = { }
		self.working_holiday_payment_dictionary = { }
		self.extra_hour_payment_dictionary = { }
		self.over_salary_payment_dictionary = { }
		self.commission_payment_dictionary = { }
		self.employer_payment_dictionary = { }
		retirement_fund = 0
		fields = self.pool.get('hr_payroll_cr.payroll').browse(cr,uid,payroll_id)
		today = datetime.date.today()
		self.pool.get('hr_payroll_cr.payment').write(cr, uid, payment, {'payroll':payroll_id, 'detail':fields.detail})
		if cont:
			for c_id in contract_id:
				payment_per_contract = self.pool.get('hr_payroll_cr.payment_per_contract').create(cr, uid, {'payroll_date': date_wizard, 'date': datetime.date.today(), 'contract': c_id, 'payment':payment, 'detail': 'Payment per contract ' + fields.detail})

				self._payroll_per_contract(cr, uid, c_id, mindate, maxdate, payment, payment_per_contract, date_wizard) #calls payroll_per_contract for each contract in the company
		else:
			contracts = self.pool.get('hr.contract').search(cr, uid, [('company_id', '=', company_id)])
			for conts in contracts:
				payment_per_contract = self.pool.get('hr_payroll_cr.payment_per_contract').create(cr, uid, {'payroll_date': date_wizard, 'date': datetime.date.today(), 'contract': conts, 'payment':payment, 'detail': 'Payment per contract'})

				self._payroll_per_contract(cr, uid, conts, mindate, maxdate, payment, payment_per_contract, date_wizard) #calls payroll_per_contract for each contract in the company

		#creates a payment line per each payment that must go to accounting, each dictionary is defined in payroll class
		keys_incapacity = self.incapacity_payment_dictionary.keys()
		for key in keys_incapacity:
			amount = self.incapacity_payment_dictionary[key]['amount']
			detail = self.incapacity_payment_dictionary[key]['type']
			account = self.incapacity_payment_dictionary[key]['account']
			payment_per_contract_line = self.incapacity_payment_dictionary[key]['payment_per_contract_line']
			line = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':amount, 'detail':detail, 'payment':payment, 'account':account, 'date':datetime.date.today()})
			for ind in payment_per_contract_line:
				self.pool.get('hr_payroll_cr.payment_per_contract_line').write(cr, uid, ind, {'payment_line':line, 'payment':payment})

		keys_deduction = self.deduction_payment_dictionary.keys()
		for key in keys_deduction:
			amount = self.deduction_payment_dictionary[key]['amount']
			detail = self.deduction_payment_dictionary[key]['type']
			account = self.deduction_payment_dictionary[key]['account']
			payment_per_contract_line = self.deduction_payment_dictionary[key]['payment_per_contract_line']
			line = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':amount, 'detail':detail, 'payment':payment, 'account':account, 'date':datetime.date.today()}) 
			for ind in payment_per_contract_line:
				self.pool.get('hr_payroll_cr.payment_per_contract_line').write(cr, uid, ind, {'payment_line':line, 'payment':payment})
		
		keys_saving = self.saving_payment_dictionary.keys()
		for key in keys_saving:
			amount = self.saving_payment_dictionary[key]['amount']
			detail = self.saving_payment_dictionary[key]['type']
			account = self.saving_payment_dictionary[key]['account']
			payment_per_contract_line = self.saving_payment_dictionary[key]['payment_per_contract_line']
			line = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':amount, 'detail':detail, 'payment':payment, 'account':account, 'date':datetime.date.today()})
			for ind in payment_per_contract_line:
				self.pool.get('hr_payroll_cr.payment_per_contract_line').write(cr, uid, ind, {'payment_line':line, 'payment':payment})
		keys_loan = self.loan_payment_dictionary.keys()
		for key in keys_loan:
			amount = self.loan_payment_dictionary[key]['amount']
			detail = self.loan_payment_dictionary[key]['type']
			account = self.loan_payment_dictionary[key]['account']
			payment_per_contract_line = self.loan_payment_dictionary[key]['payment_per_contract_line']
			line = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':amount, 'detail':detail, 'payment':payment, 'account':account, 'date':datetime.date.today()})
			for ind in payment_per_contract_line:
				self.pool.get('hr_payroll_cr.payment_per_contract_line').write(cr, uid, ind, {'payment_line':line, 'payment':payment})
		keys_holidays = self.holidays_payment_dictionary.keys()
		for key in keys_holidays:
			amount = holiday_payment_dictionary[key]['amount']
			detail = holiday_payment_dictionary[key]['type']
			account = holiday_payment_dictionary[key]['account']
			payment_per_contract_line = holiday_payment_dictionary[key]['payment_per_contract_line']
			line = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':amount, 'detail':detail, 'payment':payment, 'account':account, 'date':datetime.date.today()})
			for ind in payment_per_contract_line:
				self.pool.get('hr_payroll_cr.payment_per_contract_line').write(cr, uid, ind, {'payment_line':line, 'payment':payment})
		keys_retirement = self.retirement_payment_dictionary.keys()
		for key in keys_retirement:
			amount = self.retirement_payment_dictionary[key]['amount']
			detail = self.retirement_payment_dictionary[key]['type']
			account = self.retirement_payment_dictionary[key]['account']
			payment_per_contract_line = self.retirement_payment_dictionary[key]['payment_per_contract_line']
			line = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':amount, 'detail':detail, 'payment':payment, 'account':account, 'date':datetime.date.today()})	
			for ind in payment_per_contract_line:
				self.pool.get('hr_payroll_cr.payment_per_contract_line').write(cr, uid, ind, {'payment_line':line, 'payment':payment})
		keys_working_holiday = self.working_holiday_payment_dictionary.keys()
		for key in keys_working_holiday:
			amount = self.working_holiday_payment_dictionary[key]['amount']
			detail = self.working_holiday_payment_dictionary[key]['type']
			account = self.working_holiday_payment_dictionary[key]['account']
			payment_per_contract_line = self.working_holiday_payment_dictionary[key]['payment_per_contract_line']
			line = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':amount, 'detail':detail, 'payment':payment, 'account':account, 'date':datetime.date.today()})
			for ind in payment_per_contract_line:
				self.pool.get('hr_payroll_cr.payment_per_contract_line').write(cr, uid, ind, {'payment_line':line, 'payment':payment})
		keys_extra_hour = self.extra_hour_payment_dictionary.keys()
		for key in keys_extra_hour:
			amount = self.extra_hour_payment_dictionary[key]['amount']
			detail = self.extra_hour_payment_dictionary[key]['type']
			account = self.extra_hour_payment_dictionary[key]['account']
			payment_per_contract_line = self.extra_hour_payment_dictionary[key]['payment_per_contract_line']
			line = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':amount, 'detail':detail, 'payment':payment, 'account':account, 'date':datetime.date.today()})
			for ind in payment_per_contract_line:
				self.pool.get('hr_payroll_cr.payment_per_contract_line').write(cr, uid, ind, {'payment_line':line, 'payment':payment})
		keys_over_salary = self.over_salary_payment_dictionary.keys()
		for key in keys_over_salary:
			amount = self.over_salary_payment_dictionary[key]['amount']
			detail = self.over_salary_payment_dictionary[key]['type']
			account = self.over_salary_payment_dictionary[key]['account']
			payment_per_contract_line = self.over_salary_payment_dictionary[key]['payment_per_contract_line']
			line = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':amount, 'detail':detail, 'payment':payment, 'account':account, 'date':datetime.date.today()})
			for ind in payment_per_contract_line:
				self.pool.get('hr_payroll_cr.payment_per_contract_line').write(cr, uid, ind, {'payment_line':line, 'payment':payment})
		keys_commission = self.commission_payment_dictionary.keys()
		for key in keys_commission:
			amount = self.commission_payment_dictionary[key]['amount']
			detail = self.commission_payment_dictionary[key]['type']
			account = self.commission_payment_dictionary[key]['account']
			payment_per_contract_line = self.commission_payment_dictionary[key]['payment_per_contract_line']
			line = self.pool.get('hr_payroll_cr.payment_line').create(cr, uid, {'amount':amount, 'detail':detail, 'payment':payment, 'account':account, 'date':datetime.date.today()})
			for ind in payment_per_contract_line:
				self.pool.get('hr_payroll_cr.payment_per_contract_line').write(cr, uid, ind, {'payment_line':line, 'payment':payment})
		
		#writes the amounts retained and paid per contract
		ppcs_search = self.pool.get('hr_payroll_cr.payment_per_contract').search(cr, uid, [('payment', '=', payment)])
		payment_paid = 0
		payment_retained = 0
		for ppcs in ppcs_search:
			ppcs_browse = self.pool.get('hr_payroll_cr.payment_per_contract').browse(cr, uid, ppcs)
			payment_paid = payment_paid + ppcs_browse.total_paid
			payment_retained = payment_retained + ppcs_browse.total_retained
		self.pool.get('hr_payroll_cr.payment').write(cr, uid, payment, {'total_paid':payment_paid, 'total_retained':payment_retained})
		return

#########################################
#	END OF THE MONTH FUNCTIONS	#
#########################################

	#Over Salary verifies the amount paid in the first half of the month and pays the second half
	def _over_salary_complete(self, cr, uid, contract_id, gross_salary, payment_per_contract, date, payment, calculated_on):
		over_salary_search = self.pool.get('hr_payroll_cr.over_salary').search(cr,uid,[('contract','=',contract_id), ('calculated_on_base_salary', '=', calculated_on)])
		month = ''
		if 10 - self.str2date(date).month > 0:
			month = '0' + str(self.str2date(date).month)
		else:
			month = self.str2date(date).month
		contract = self.pool.get('hr.contract').browse(cr,uid,contract_id)
		amount = 0
		amount_total = 0
		ppcl_list = []
		today = time.strftime('%Y-%m-%d')
		tmp_date = self.str2date(str(self.str2date(date).year) + '-' + str(month) + '-01')
		last_day = calendar.monthrange(self.str2date(date).year, self.str2date(date).month)[1]
		tmp_date2 = self.str2date(str(self.str2date(date).year) + '-' + str(month) + '-' + str(last_day))
		for id in over_salary_search:
			over_salary_payment_search = self.pool.get('hr_payroll_cr.over_salary_payment').search(cr, uid, [('over_salary', '=', id), ('date', '>=', tmp_date), ('date', '<=', tmp_date2)])
			debug (over_salary_payment_search)
			over_salary_browse = self.pool.get('hr_payroll_cr.over_salary').browse(cr,uid,id)
			over_salary_percent = over_salary_browse.percent
			over_salary_amount = over_salary_browse.amount
			over_salary_detail = over_salary_browse.detail
			#if there is no payment on the first middle of the month, the amount of the over salary is
			#divided by 2
			if over_salary_payment_search == []:
				if (over_salary_percent == True):
					if (over_salary_browse.calculated_on_base_salary == True):
						contract = self.pool.get('hr.contract').browse(cr,uid,contract_id)
						wage = contract.wage
						amount = ((wage / 100) * over_salary_amount)
					else:
						amount = ((gross_salary / 100) * over_salary_amount)
				else:
					amount = over_salary_amount
				amount = amount / 2
				debug(amount)
				
				payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':6, 'detail':over_salary_detail + ' - Over Salary','amount':amount, 'date':datetime.date.today(), 'payment_per_contract':payment_per_contract, 'account':over_salary_browse.account.id, 'payment':payment })
				ppcl_list.append(payment_id)
				over_salary_payment_id = self.pool.get('hr_payroll_cr.over_salary_payment').create(cr,uid,{'detail':over_salary_detail,'amount':amount, 'payment_date':datetime.date.today(), 'percent': over_salary_percent, 'payment_per_contract_line': payment_id, 'over_salary': id, 'date': date})
				debug(amount)
				amount_total = amount_total + amount
			else:
				for id_over_salary_payment in over_salary_payment_search:
					over_salary_payment_browse = self.pool.get('hr_payroll_cr.over_salary_payment').browse(cr, uid, id_over_salary_payment)
					debug(over_salary_payment_browse)
					first_payment = over_salary_payment_browse.amount
					
					if (over_salary_percent == True):
						if (over_salary_browse.calculated_on_base_salary == True):
							contract = self.pool.get('hr.contract').browse(cr,uid,contract_id)
							wage = contract.wage
							amount = ((wage / 100) * over_salary_amount)
						else:
							amount = ((gross_salary / 100) * over_salary_amount)
					else:
						amount = over_salary_amount
					amount = amount - first_payment
					debug(amount)
					debug(over_salary_payment_browse.date)
					payment_id = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr,uid,{'type':6, 'detail':over_salary_detail + ' - Over Salary','amount':amount, 'date':datetime.date.today(), 'payment_per_contract':payment_per_contract, 'account':over_salary_browse.account.id, 'payment':payment })
					ppcl_list.append(payment_id)
					over_salary_payment_id = self.pool.get('hr_payroll_cr.over_salary_payment').create(cr,uid,{'detail':over_salary_detail,'amount':amount, 'payment_date':datetime.date.today(), 'percent': over_salary_percent, 'payment_per_contract_line': payment_id, 'over_salary': id, 'date': date})
					debug(amount)
					amount_total = amount_total + amount
		debug(amount_total)
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'over_salary_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return amount_total	


#Deduction for the second part of the payroll
#like over salary search the payment of the first half of the month and subs it from the total of the month
	def _deduction_complete(self, cr, uid, contract_id, gross_salary, payment_per_contract, date, payment):
		amount = 0
		per = False
		am_per = 0
		ppcl_list = []
		deduction_search = self.pool.get('hr_payroll_cr.deduction').search(cr,uid,[('contract','=',contract_id)])
		contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
		employee = self.pool.get('hr.employee').browse(cr, uid, contract.employee_id.id)
		for deds in deduction_search:
			deduction_browse = self.pool.get('hr_payroll_cr.deduction').browse(cr, uid, deds)
			deduction_type_browse = self.pool.get('hr_payroll_cr.deduction_type').browse(cr, uid, deduction_browse.deduction_type.id)
			deduction_line_search = self.pool.get('hr_payroll_cr.deduction_line').search(cr, uid, [('deduction', '=', deduction_browse.id), ('date', '=', self.str2date(str(self.str2date(date).year) + '-' + str(self.str2date(date).month) + '-15'))])
			debug (deduction_browse)
			#if there is no deduction line on the first middle of the month, the amount is divided by 2
			if deduction_line_search == []:
				if deduction_browse.calc_method == 'P':
					per = True
					amount_reduction = gross_salary * (deduction_browse.amount / 100)
					amount = amount + amount_reduction 
					am_per = deduction_browse.amount
				elif deduction_browse.calc_method == 'A':
					amount_reduction = deduction_browse.amount
					amount = amount + amount_reduction
					am_per = amount
				else:
					dictionary = {'gross_salary':gross_salary, 'contract':contract, 'employee':employee}
					exec deduction_type_browse.code in dictionary
					amount_reduction = dictionary['result'] #result is the variable where the final amount of the calc for deduction must be in the code field 
					amount = amount + amount_reduction
				ppcl = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr, uid, {'type':4, 'amount' : amount_reduction, 'detail' : deduction_type_browse.detail + ' - Deduction', 'payment_per_contract':payment_per_contract, 'account':deduction_type_browse.account.id, 'date':self.str2date(date), 'payment':payment})
				ppcl_list.append(ppcl)
				dl = self.pool.get('hr_payroll_cr.deduction_line').create(cr, uid, {'deduction' : deds, 'amount' : am_per, 'date' : self.str2date(date), 'percent' : per, 'total' : amount, 'payment_per_contract_line' : ppcl})
				deduction_type_name = deduction_browse.name
				deduction_type_account = deduction_browse.account.id
				key = deduction_type_name + str(deduction_type_account)
				if (key in self.deduction_payment_dictionary):
					self.deduction_payment_dictionary[key]['amount'] = self.deduction_payment_dictionary[key]['amount'] + amount_reduction
					self.deduction_payment_dictionary[key]['payment_per_contract_line'].append(ppcl)
				else:
					self.deduction_payment_dictionary[key] = {'type':deduction_type_name, 'amount':amount_reduction, 'account': deduction_type_account, 'payment_per_contract_line' : [ppcl]}
			else:
				for dls in deduction_line_search:
					deduction_line_browse = self.pool.get('hr_payroll_cr.deduction_line').browse(cr, uid, dls)
					debug (deduction_line_browse)
					if deduction_type_browse.calc_method == 'P':
						per = True
						amount_reduction = gross_salary * (deduction_type_browse.amount / 100) -  deduction_line_browse.amount
						amount = amount + amount_reduction
						am_per = deduction_browse.amount
					elif deduction_browse.calc_method == 'A':
						amount_reduction = deduction_type_browse.amount -  deduction_line_browse.amount
						amount = amount + amount_reduction
						am_per = amount
					else:
						dictionary = {'gross_salary':gross_salary, 'contract':contract, 'employee':employee}
						exec deduction_browse.code in dictionary
						amount_reduction = dictionary['result'] -  deduction_line_browse.amount #result is the variable where the final amount of the calc for deduction must be in the code field 
						amount = amount + amount_reduction
					ppcl = self.pool.get('hr_payroll_cr.payment_per_contract_line').create(cr, uid, {'type':4, 'amount' : amount_reduction, 'detail' : deduction_type_browse.detail, 'payment_per_contract':payment_per_contract, 'account':deduction_type_browse.account, 'date':self.str2date(date), 'payment':payment})
					ppcl_list.append(ppcl)
					dl = self.pool.get('hr_payroll_cr.deduction_line').create(cr, uid, {'deduction' : deds, 'amount' : am_per, 'date' : self.str2date(date), 'percent' : per, 'total' : amount, 'payment_per_contract_line' : ppcl})
					self.pool.get('hr_payroll_cr.deduction').write(cr, uid, deds, {'deduction_line' : dl})
					deduction_type_name = deduction_browse.name
					deduction_type_account = deduction_browse.account
					key = deduction_type_name + deduction_type_account
					if (key in deduction_payment_dictionary):
						deduction_payment_dictionary[key][amount] = deduction_payment_dictionary[key][amount] + amount_reduction
						deduction_payment_dictionary[key][payment_per_contract_line].append(ppcl)
					else:
						deduction_payment_dictionary[key] = {'type':deduction_type_name, 'amount':amount_reduction, 'account': deduction_type_account, 'payment_per_contract_line' : [ppcl]}
		debug (amount)
		ppcl_read = self.pool.get('hr_payroll_cr.payment_per_contract_line').read(cr, uid, ppcl_list, ['id'])
		#debug(total_hours)
		for ppcl_ind in ppcl_read:
			self.pool.get('hr_payroll_cr.payment_per_contract').write(cr, uid, payment_per_contract, {'deduction_per_contract_line': [(0, 0, ppcl_ind)]})
		
		return amount	



#type of payroll to pay the final payment, it needs a contract, a date and a payment	
	def _final_payment(self, cr, uid, ids, date, cont, payment, context=None):
		unemployment_fee = self._unemployment_fee(cr, uid, cont, payment, date)
		christmas_bonus = self._christmas_bonus(cr, uid, cont, payment)
		contract = self.pool.get('hr.contract').browse(cr, uid, cont)
		holidays = self.pool.get('hr_payroll_cr.holiday_per_contract').search(cr, uid, [('contract', '=', contract.id)])
		total_days = 0
		for hl in holidays:
			h_browse = self.pool.get('hr_payroll_cr.holiday_per_contract').browse(cr, uid, hl)
			total_days = total_days + h_browse.days
		total_holiday = total_days * contract.wage / 30
		total_final_payment = unemployment_fee + christmas_bonus + total_holiday
		ppc = self.pool.get('hr_payroll_cr.payment_per_contract').create(cr, uid, {'payroll_date':date, 'total_paid':total_final_payment, 'detail':'Final Payment', 'total_retained':0, 'payment':payment, 'contract':cont, 'date':date})

#Decides if calls unemployment fee or one of the payroll
#gets the data from the wizard made for payroll,
#needs contract, date, detail, company, a boolean to indicate if the payroll is for a contract or a company and type
#of payroll
	def _whole_payroll(self, cr, uid, ids, date_wizard, detail_wizard, company_wizard, type_wizard, contract_wizard, bool_wizard, context=None):
		payroll_search = None
		if contract_wizard == None:
			payroll_id = self.pool.get('hr_payroll_cr.payroll').create(cr,uid,{'date':self.str2date(date_wizard), 'type':type_wizard, 'detail':detail_wizard, 'company_id':company_wizard})
			payroll_search = self.pool.get('hr_payroll_cr.payroll').search(cr,uid,[('date','=',self.str2date(date_wizard)),('type','=',type_wizard),('detail','=',detail_wizard),('company_id','=',company_wizard)])
		else:
			for contract_wizard_id in contract_wizard:
				payroll_id = self.pool.get('hr_payroll_cr.payroll').create(cr,uid,{'date':self.str2date(date_wizard), 'type':type_wizard, 'detail':detail_wizard, 'company_id':company_wizard, 'contract':contract_wizard_id})
			payroll_search = self.pool.get('hr_payroll_cr.payroll').search(cr,uid,[('date','=',self.str2date(date_wizard)),('type','=',type_wizard),('detail','=',detail_wizard),('contract','in',contract_wizard)])
		
		fields = self.pool.get('hr_payroll_cr.payroll').browse(cr,uid,payroll_search[0])
		month = ''
		payment = self.pool.get('hr_payroll_cr.payment').create(cr,uid,{'date':self.str2date(date_wizard)})
		#holiday_payment = 0
		if 10 - self.str2date(date_wizard).month > 0:
			month = '0' + str(self.str2date(date_wizard).month)
		else:
			month = str(self.str2date(date_wizard).month)
		fecha = str(self.str2date(date_wizard).year) + '-' + str(month) + '-15'
		if type_wizard == "U":
			debug(contract_wizard)
			self._unemployment_fee(cr, uid, contract_wizard[0], payment, self.str2date(date_wizard))
		elif type_wizard == "P":
			if date_wizard == fecha:
				mindate = str(self.str2date(date_wizard).year) + '-' + str(month) + '-01'
				maxdate = str(self.str2date(date_wizard).year) + '-' + str(month) + '-15'
				#holiday_payment = self._holiday_period(self, cr, uid, contract_id, mindate, maxdate)
				self._payroll(cr, uid, ids, mindate, maxdate, date_wizard, payment, fields.id, company_wizard, contract_wizard, bool_wizard, context=None)
			else:
				mindate = str(self.str2date(date_wizard).year) + '-' + str(month) + '-15'
				last_day = calendar.monthrange(self.str2date(date_wizard).year, self.str2date(date_wizard).month)[1]
				maxdate = str(self.str2date(date_wizard).year) + '-' + str(month) + '-' + str(last_day)
				#holiday_payment = self._holiday_period(self, cr, uid, contract_id, mindate, maxdate)
				self._payroll(cr, uid, ids, mindate, maxdate, date_wizard, payment, fields.id, company_wizard, contract_wizard, bool_wizard, context=None) 
		elif type_wizard == "F": 
			self._final_payment(cr, uid, ids, self.str2date(date_wizard), contract_wizard[0], payment, context=None)
		elif type_wizard == "C":
			self._christmas_bonus(cr, uid, date_wizard, company_wizard, payment)
		elif type_wizard == "FC":
			self._unemployment_fee_per_company(cr, uid, company_wizard, payment, self.str2date(date_wizard))
		#return holiday_payment
		return
hr_payroll_cr_payroll()

#################################
#	  CLASS PAYMENT		#
#################################

class hr_payroll_cr_payment(osv.osv):	#this keeps the payment made by a payroll, an unemployment fee, a christmas bonus or a final payment
	_name = 'hr_payroll_cr.payment'
	_rec_name = 'detail'
	_columns = {
		'detail': fields.char('Detail', size = 150, readonly=True, select=1),
		'date': fields.date('Date', readonly=True, select=1),
		'total_paid': fields.float('Total Paid', readonly=True, digits=(16 , int(config['price_accuracy'])), select=0, help="Total paid to employees"),
		'total_retained': fields.float('Total Retained', readonly=True, digits=(16 , int(config['price_accuracy'])), select=0, help="Total retained from employees"),
		'payroll': fields.many2one('hr_payroll_cr.payroll', 'Payroll', readonly=True, select=2),
	#	'account_entry': fields.many2one('account.account.move', 'Account Entry', readonly=True, select=2, help="Account entry for this payment once it has been approved"),
		'payment_line': fields.one2many('hr_payroll_cr.payment_line', 'payment','Payment Lines', readonly=True, select=0),
		#'payment_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment', 'Payment per Contract Lines', required=False, readonly=True),
		'notes': fields.text('Notes'),
	}
hr_payroll_cr_payment()

class hr_payroll_cr_payment_line(osv.osv):
	"""
	Records each payment line for historic reporting and analysis.
	"""
	_name = 'hr_payroll_cr.payment_line'
	_rec_name = 'detail'
	_columns = {
		'detail': fields.char('Detail', size=150, readonly=True, select=1),
		'date': fields.date('Date', readonly=True, select=1),
		'amount': fields.float('Amount', required=True, digits=(16 ,  int(config['price_accuracy'])), readonly=True, select=0),
		'account': fields.many2one('account.account', 'Account', required=True, readonly=True, ),
		'payment': fields.many2one('hr_payroll_cr.payment', 'Payment'),
	#	'account_entry_line': fields.many2one('account.account.move.line', 'Entry Line'),
		'payment_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_line', 'Payment Per Contract Line'),
		'notes': fields.text('Notes'),
	}
hr_payroll_cr_payment_line()

class hr_payroll_cr_working_schedule(osv.osv): #to save the days to work for a contract
	"""
	saves a calendar to use for a contract or more
	"""
	_name = 'hr_payroll_cr.working_schedule'
	_columns = {
		'name':fields.char('Name', size=64, required=True, readonly=False, select=1),		
		'detail': fields.char('Detail', size=150, required=True, select=0),
		'sunday': fields.boolean('Sunday', select=0),
		'monday': fields.boolean('Monday', select=0),
		'tuesday': fields.boolean('Tuesday', select=0),
		'wednesday': fields.boolean('Wednesday', select=0),
		'thursday': fields.boolean('Thursday', select=0),
		'friday': fields.boolean('Friday', select=0),
		'saturday': fields.boolean('Saturday', select=0),
		'hoursperday': fields.integer('Hours Per Day', required=True, select=1),
		'notes': fields.text('Notes', select=0),
	}
hr_payroll_cr_working_schedule()

class hr_payroll_cr_payment_per_contract(osv.osv): #payment made per contract, total paid and retained
	"""
	All the payments made to a contract.
	"""

	_name = 'hr_payroll_cr.payment_per_contract'
	_rec_name = 'detail'
	_columns = {
		'date': fields.date('Date', required =True),
		'payroll_date':fields.date('Payroll date'),
		'detail': fields.char('Detail', size=150),
		'notes': fields.text('Notes'),
		'total_paid': fields.float('Total Paid', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'total_retained': fields.float('Total Retained', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'gross_salary': fields.float('Gross Salary', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'contract': fields.many2one('hr.contract', 'Contract', required =True), # Contract to which payment are made
		'payment':fields.many2one('hr_payroll_cr.payment', 'Payment', required=False),
		'payment_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Payment Per Contract Line', required=False),
		'saving_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Saving Per Contract Line', required=False),
		'loan_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Loan Per Contract Line', required=False),
		'other_income_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Other Income Per Contract Line', required=False),
		'deduction_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Deductions Per Contract Line', required=False),
		'absence_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Absence Per Contract Line', required=False),
		'over_salary_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Over Salary Per Contract Line', required=False),
		'commission_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Commission Per Contract Line', required=False),
		'extra_hour_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Extra Hours Per Contract Line', required=False),
		'working_holiday_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Working Holiday Per Contract Line', required=False),
		'permit_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Permit Per Contract Line', required=False),
		'incapacity_period_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Incapacity Period Per Contract Line', required=False),
		'retirement_fund_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Retirement Fund Per Contract Line', required=False),
		'employer_social_security_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Employer Social Security Per Contract Line', required=False),
		'foreclosure_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Foreclosure Per Contract Line', required=False),
		'rent_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Rent Per Contract Line', required=False),
		'refund_per_contract_line':fields.one2many('hr_payroll_cr.payment_per_contract_line', 'payment_per_contract', 'Refund Per Contract Line', required=False),
		
				
	}
hr_payroll_cr_payment_per_contract()

class hr_payroll_cr_payment_per_contract_line(osv.osv):
	"""
	Lines of the payment per contract
	"""
	_name = 'hr_payroll_cr.payment_per_contract_line'
	_rec_name = 'id'
	_columns = {
		#'type':fields.integer('Type', readonly=True),#To filter the view with the domain
		'detail': fields.char('Detail', size=150, readonly=True),
		'employeer': fields.boolean('Employeer', readonly=True),
		'code': fields.integer('Code', help='codigo para los tipos de pago, ya sea aguinaldo, pago quincenal, semanal, etc.', readonly=True),
		'amount': fields.float('Amount', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'payment_per_contract': fields.many2one('hr_payroll_cr.payment_per_contract', 'Payment per contract', readonly=True),
		'account':fields.many2one('account.account', 'Account', readonly=True),
		'payment_line':fields.many2one('hr_payroll_cr.payment_line', 'Payment Line', readonly=True),		
		'payment':fields.many2one('hr_payroll_cr.payment', 'Payment', required=False, readonly=True),
		'date': fields.date('Date', readonly=True),		
	}
hr_payroll_cr_payment_per_contract_line()

class hr_payroll_cr_incapacity_period_type(osv.osv):
	"""
	Type of incapacities, like CCSS or INS for example
	"""
	_name = 'hr_payroll_cr.incapacity_period_type'
	_columns = {
		'notes': fields.text('Notes'),
		'periodtypeline': fields.one2many('hr_payroll_cr.incapacity_period_type_line', 'period_type', 'Period Type Line'),
		'name': fields.char('Name', required =True, size=50),
		'detail': fields.char('Detail', size=150, required=True),
		'account':fields.many2one('account.account', 'Account', required=True),
	}
hr_payroll_cr_incapacity_period_type()

class hr_payroll_cr_incapacity_period(osv.osv):
	"""
	"""
	_name = 'hr_payroll_cr.incapacity_period'
	_rec_name = 'contract'
	_columns = {
		'employee':fields.char('Employee', size=150),
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"), # Contract to which payment are made
		'paid':fields.boolean('Paid'),		
		'start_date': fields.date('Start Date', required =True,  select="1"),
		'end_date': fields.date('End Date', required =True, select="2"),
		'notes': fields.text('Notes', select="0"),
		'detail': fields.char('Detail', size=150, select="0", required=True),
		'incapacity_period_per_day': fields.one2many('hr_payroll_cr.incapacity_period_per_day', 'incapacity_period' , 'Incapacity Period Per Day', readonly=True, select="0"),
		'incapacity_period_type':fields.many2one('hr_payroll_cr.incapacity_period_type', 'Incapacity Period Type', required = True, select="0"),

	}
	
	def on_change_contract(self, cr, uid, ids, contract):
		contract_browse = self.pool.get('hr.contract').browse(cr, uid, contract)
		debug(contract_browse)
		debug(contract_browse.employee_id)
		empl = self.pool.get('hr.employee').browse(cr, uid, contract_browse.employee_id.id)
		debug(empl)
		empl_name = str(empl.name) + ' ' + str(empl.surname1) + ' ' + str(empl.surname2)
		debug(empl_name)
		v = {}
		v['employee'] = empl_name
		return {'value': v} 
		
	def str2date(self, date_str):
		date_unformat = time.strptime(date_str, '%Y-%m-%d')
		return datetime.date(date_unformat.tm_year, date_unformat.tm_mon, date_unformat.tm_mday)

	def interval(self,edate, idate):
		return (edate - idate)
		
	def _create_incapacity_per_day(self, cr, uid, ids, context=None):
		fields = self.browse(cr,uid,ids)[0]
		incapacity_period_id = fields.id
		incapacity_period_type = fields.incapacity_period_type.id
		start_date = fields.start_date
		end_date = fields.end_date
		day_quantity = self.interval(self.str2date(end_date), self.str2date(start_date)	).days + 1
		incapacity_date = self.str2date(start_date)
		incapacity_period_type_lines = self.pool.get('hr_payroll_cr.incapacity_period_type_line').search(cr, uid, [('period_type','=',incapacity_period_type)])
		lines_per_incapacity = []
		for line in incapacity_period_type_lines:
			incapacity_period_type_line = self.pool.get('hr_payroll_cr.incapacity_period_type_line').browse(cr, uid, line)
			#debug(incapacity_period_type_line)
			min = incapacity_period_type_line.start_day
			max = incapacity_period_type_line.end_day
			percent = incapacity_period_type_line.percent
			amount = incapacity_period_type_line.amount
			reflectible = incapacity_period_type_line.reflectible
			register = {'min':min , 'max':max , 'percent': percent, 'amount': amount,}
			lines_per_incapacity.append(register)
		percent = 0
		amount = 0
		delimiter = "---------------------------------------------------"
		#debug(delimiter)
		for i in range(1, day_quantity):
			#debug(delimiter)
			#debug(lines_per_incapacity)
			for reg in lines_per_incapacity:
				#debug(reg)
				if i >= reg['min'] and i <= reg['max']:
					percent = reg['percent']
					amount = reg['amount']
					break
				elif i >= reg['min'] and reg['max'] == 0:
					percent = reg['percent']
					amount = reg['amount']
					break
			self.pool.get('hr_payroll_cr.incapacity_period_per_day').create(cr, uid, {'reflectible':reflectible,'percent': percent, 'amount': amount, 'payment_per_contract_line': None, 'date': incapacity_date, 'incapacity_period': incapacity_period_id})
			#incremento la fecha al dia siguiente
			incapacity_date = incapacity_date + timedelta(1) 
		return
	
hr_payroll_cr_incapacity_period()

class hr_payroll_cr_incapacity_period_per_day(osv.osv):
	""" This table counts each day of the incapacity"""
	_name = 'hr_payroll_cr.incapacity_period_per_day'
	_rec_name = 'date'
	_columns = {
		'paid': fields.boolean('Paid'),
		'percent': fields.boolean('Percent', required=True), # This fields es to know if the incapacity is gonna be take like a percent or like an amount
		'amount': fields.float('Amount', required =True, digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
		'date': fields.date('Date', required =True),
		'reflectible':fields.boolean('Reflectible'),
		'incapacity_period':fields.many2one('hr_payroll_cr.incapacity_period', 'Incapacity Period'),
	}
hr_payroll_cr_incapacity_period_per_day()

class hr_payroll_cr_incapacity_period_extension(osv.osv):
	"""To manage incapacities extensions"""
	_name = 'hr_payroll_cr.incapacity_period_extension'
	_rec_name = 'detail'
	_columns = {
		'start_date': fields.date('Start Date', required =True),
		'end_date': fields.date('End Date', required =True),
		'notes': fields.text('Notes'),
		'detail': fields.char('Detail', required =True, size=150),
		'incapacity_period': fields.many2one('hr_payroll_cr.incapacity_period', 'Incapacity Period'),
	}
hr_payroll_cr_incapacity_period_extension()

class hr_payroll_cr_over_salary(osv.osv):
	_name = 'hr_payroll_cr.over_salary'
	_rec_name = 'detail'
	_columns = {
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"), # Contract to which payment are made
		'calculated_on_base_salary': fields.boolean('Calculated on Base Salary'), 
		'start_date': fields.date('Start Date', required =True, select="1"),
		'end_date': fields.date('End Date', required =True, select="2"),# The date fields are to establish the period of the over salary
		'amount': fields.float('Amount', required =True, digits=(16 , 4), select="0"), #FALTA REPARAR A int(config['price_accuracy'])
		'notes': fields.text('Notes', select="0"),
		'detail': fields.char('Detail', required =True, size=150, select="0"),
		'percent': fields.boolean('Percent', select="0"), # to establish if the over salary is a percent or not
		'account': fields.many2one('account.account', 'Account', required =True, select="0"),
		'over_salary_payment' : fields.one2many('hr_payroll_cr.over_salary_payment', 'over_salary', 'Over Salary Payment', select="0"),
	}
hr_payroll_cr_over_salary()

class hr_payroll_cr_over_salary_payment(osv.osv):
	"""To manage all the payments made to one over salary"""
	_name = 'hr_payroll_cr.over_salary_payment'
	_rec_name = 'detail'
	_columns = {
		'amount': fields.float('Amount', required =True, digits=(16, 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'date' : fields.date('Date', required =True),
		'percent' : fields.boolean('Percent'),
		'detail' : fields.char('Detail', size=150, required =True),
		'over_salary' : fields.many2one('hr_payroll_cr.over_salary', 'Over Salary'),
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
		'payment_date': fields.date('Payment Date'),
	}
hr_payroll_cr_over_salary_payment()

class hr_payroll_cr_permit(osv.osv):
	"""To manage the absences permits"""
	_name = 'hr_payroll_cr.permit'
	_rec_name = 'detail'
	_columns = {
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"),
		'with_salary': fields.boolean('With Salary', help='si es con salario o no', select="1"), # 
		'detail': fields.char('Detail', size=150, required =True, select="2"),
		'notes': fields.text('Notes', select="0"),
		'start_date': fields.date('Start Date', required =True, select="0"),
		'end_date': fields.date('End Date', required =True, select="0"), # The date fields are to know the days with permissions
		'permit_per_day': fields.one2many('hr_payroll_cr.permit_per_day', 'permit', 'Permit Per Day', select="0"),
	}

	def str2date(self, date_str):
		date_unformat = time.strptime(date_str, '%Y-%m-%d')
		return datetime.date(date_unformat.tm_year, date_unformat.tm_mon, date_unformat.tm_mday)

	def interval(self,edate, idate):
		return (edate - idate)

	def _create_permit_per_day(self, cr, uid, ids, context=None):
		fields = self.browse(cr,uid,ids)[0]
		permit_id = fields.id
		start_date = fields.start_date
		end_date = fields.end_date
		day_quantity = self.interval(self.str2date(end_date), self.str2date(start_date)	).days + 1
		permit_date = self.str2date(start_date)

		for i in range(1, day_quantity):
			self.pool.get('hr_payroll_cr.permit_per_day').create(cr, uid, {'payment_per_contract_line': None, 'date': permit_date, 'permit': permit_id})
			#incremento la fecha al dia siguiente
			permit_date = permit_date + timedelta(1)
		return
hr_payroll_cr_permit()

class hr_payroll_cr_permit_per_day(osv.osv):
	_name = 'hr_payroll_cr.permit_per_day'
	_rec_name = 'date'
	_columns = {
		'date': fields.date('Date', required =True),
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
		'permit': fields.many2one('hr_payroll_cr.permit', 'Permit'),
	}
hr_payroll_cr_permit_per_day()

class hr_payroll_cr_extra_hour(osv.osv):
	_name = 'hr_payroll_cr.extra_hour'
	_rec_name = 'contract'
	_columns = {
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"), # Contract to which payment are made
		'date': fields.date('Date', required =True, select="0"),
		'hours': fields.float('Hours', required =True, digits=(16 , 4), select="0"), #FALTA REPARAR A int(config['price_accuracy'])
		'account': fields.many2one('account.account', 'Account', required =True, select="0"),
		'payment_per_contract_line':fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
		'multiplier': fields.float('Multiplier', digits=(16, 4), required=True, select="0"),
	}
hr_payroll_cr_extra_hour()

class hr_payroll_cr_absence(osv.osv):
	_name = 'hr_payroll_cr.absence'
	_rec_name = 'detail'
	_columns = {
		'detail': fields.char('Detail', size=150, required =True, select="2"),
		'date': fields.date('Date', required =True, select="1"),
		'contract': fields.many2one('hr.contract', 'Contract', required =True),
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
		'justification': fields.boolean('Justification', select="1"),
		'notes': fields.text('Notes', select="0"),
	}
hr_payroll_cr_absence()

class hr_payroll_cr_contract(osv.osv):
	"""Remive working hours per day"""
	_name =  'hr.contract' #'hr_payroll_cr.contract'
	_inherit = 'hr.contract'
	_columns = {
		'surname1':fields.char('surname1', size=64),
		'surname2':fields.char('surname2', size=64),
		#'active':fields.boolean('Active', required=False),
		'christmas_bonus_amount': fields.float('Christmas Bonus Amount', digits=(16 , 4), readonly=True), #FALTA REPARAR A int(config['price_accuracy'])
		'christmas_bonus_quota': fields.one2many('hr_payroll_cr.christmas_bonus_quota', 'contract', 'Christmas Bonus Quota'),
		'christmas_bonus_account':fields.many2one('account.account', 'Account', required=True),
		'payment_per_contract': fields.one2many('hr_payroll_cr.payment_per_contract', 'contract', 'Payment Per Contract'),
		'working_schedule': fields.many2one('hr_payroll_cr.working_schedule', 'Working Schedule', required=True),
		'working_holiday': fields.one2many('hr_payroll_cr.working_holiday', 'contract', 'Working Day'),
		'christmas_bonus': fields.one2many('hr_payroll_cr.christmas.bonus', 'contract', 'Christmas Bonus'),
		'absence': fields.one2many('hr_payroll_cr.absence', 'contract', 'Absence'),
		'company_id': fields.many2one('res.company', 'Company', required=True),
		'code': fields.char('Code', required =True, size=50),
		'accumulated_holidays': fields.integer('Accumulated Holiday', help="Accumulated vacations for the employee in the current contract"),
	}
	def name_get(self, cr, user, ids, context={}):
		if not len(ids):
			return []
		def _name_get(d):
			name = d.get('name','')
			employee_id = d.get('employee_id',False)
			#debug(employee_id[0])
			code = ''
			if employee_id:
				employee = self.pool.get('hr.employee').browse(cr, user, employee_id[0])
				#debug(employee)
				code = employee.name + ' ' + employee.surname1 + ' ' + employee.surname2
			if not (code == ''):
				name = '[%s] %s' % (code,name)
			return (d['id'], name)
		result = map(_name_get, self.read(cr, user, ids, ['name','employee_id'], context))
		return result
	
	def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=80):
		if not args:
			args=[]
		if not context:
			context={}
		if name:
			ids = self.search(cr, user, [('employee_id','=',name)]+ args, limit=limit, context=context)
			if not len(ids):
				ids = self.search(cr, user, [('employee_id',operator,name)]+ args, limit=limit, context=context)
				ids = ids + self.search(cr, user, [('name',operator,name)]+ args, limit=limit, context=context)
		else:
			ids = self.search(cr, user, args, limit=limit, context=context)
		result = self.name_get(cr, user, ids, context)
		return result

	def on_change_employee(self, cr, uid, ids, employee_id):
		employee = self.pool.get('hr.employee').browse(cr, uid, employee_id)
		v={}
		v['surname1'] = employee.surname1
		v['surname2'] = employee.surname2
		return{'value':v} 	

	def create(self, cr, uid, vals, context=None):
		self.pool.get('hr_payroll_cr.contract_data').create(cr, uid, vals, context=None)
		return super(hr_payroll_cr_contract, self).create(cr, uid, vals, context=None)

	def write(self, cr, uid, id, vals, context=None):
		#if not cb:
		if not 'christmas_bonus_amount' in vals and 'wage_type_id' in vals:
			self.pool.get('hr_payroll_cr.contract_data').create(cr, uid, vals, context=None)
		return super(hr_payroll_cr_contract, self).write(cr, uid, id, vals, context=None)

hr_payroll_cr_contract()

#TODO: modify create on contract to create a contract data
class hr_payroll_cr_contract_data(osv.osv):
	_name = 'hr_payroll_cr.contract_data'
	_inherit = 'hr.contract'
	_columns = {
	}
		
	def create(self, cr, uid, vals, context=None):
		return super(hr_payroll_cr_contract, self).create(cr, uid, vals, context=None)
hr_payroll_cr_contract_data()

class hr_payroll_cr_national_holiday(osv.osv):
	_name = 'hr_payroll_cr.national_holiday'
	_columns = {
		'name':fields.char('Name', size=64, required=True, readonly=False),
		'date': fields.date('Date', help="This is not the official date of the holiday", required=True),
		'holiday_days': fields.one2many('hr_payroll_cr.national_holiday_days','holiday','Holiday'),
	}
hr_payroll_cr_national_holiday()

class hr_payroll_cr_national_holiday_days(osv.osv):
	_name = 'hr_payroll_cr.national_holiday_days'
	_rec_name = 'date'
	_columns = {
		'date': fields.date('Date', required =True, help="Official date of the holiday"),
		'detail': fields.char('Detail', required =True, size=150),
		'holiday': fields.many2one('hr_payroll_cr.national_holiday','National Holiday'),
	}
hr_payroll_cr_national_holiday_days()

class hr_payroll_cr_working_holiday(osv.osv):
	"""All the holidays that were worked"""
	_name = 'hr_payroll_cr.working_holiday'
	_rec_name = 'contract'
	_columns = {
		'date': fields.date('Date', required =True, select="1"),
		'hours': fields.float('Hours', required =True, digits=(16 , 4), select="2"), #FALTA REPARAR A int(config['price_accuracy'])
		'holiday': fields.many2one('hr_payroll_cr.national_holiday', 'National Holiday', required=True, select="0"),
		'account': fields.many2one('account.account', 'Account', required =True, select="0"),
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"),
		'paid':fields.boolean('Paid', required=False),
		'payment_per_contract_line':fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line', required=False),
	}
hr_payroll_cr_working_holiday()

class hr_payroll_cr_employee(osv.osv):
	_name = 'hr.employee' #'hr_payroll_cr.employee' 
	_inherit = 'hr.employee'
	_columns = {
		'surname1':fields.char('Last Name', size=64, required =True, readonly=False),
		'surname2':fields.char('Second Last Name', size=64, required =True, readonly=False),
		'employee_id': fields.char('Id', size=64, required =True),
		'children_for_rent_tax': fields.integer('Quantity of children for rent tax', default=0),
		'apply_rent':fields.boolean('Apply Rent', help = "This field will be checked if your spouse doesn't pay rent"),
	}
hr_payroll_cr_employee()

class hr_payroll_cr_deduction_type(osv.osv):
	_name = 'hr_payroll_cr.deduction_type'
	_columns = {
		'detail': fields.char('Detail', size=150, required=True),
		'notes': fields.text('Notes'),
		'account': fields.many2one('account.account', 'Account', required =True),
		'amount': fields.float('Amount', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'name': fields.char('Name', size=150, required =True),
		'calc_method': fields.selection([('P','Percent'), ('A','Amount'), ('C','Code')],'Calc Method', required =True), # To establish the calculated method
		'code': fields.text('Code'),
		'deduction' : fields.one2many('hr_payroll_cr.deduction', 'deduction_type', 'Deduction'),
	}
	_defaults = {
		'detail': lambda*a: ' ',
	}
hr_payroll_cr_deduction_type()

class hr_payroll_cr_deduction(osv.osv):
	_name = 'hr_payroll_cr.deduction'
	_columns = {
		'deduction_type' : fields.many2one('hr_payroll_cr.deduction_type', 'Deduction Type', select="0", required=True),
		'deduction_line' : fields.one2many('hr_payroll_cr.deduction_line', 'deduction', 'Deduction Line', select="4"),
		'account': fields.many2one('account.account', 'Account', required =True, select="1"),
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"),
		'name': fields.char('Name', size = 50, required=True),
		'amount':fields.float('Amount', digits=(16, 4)),
		'detail':fields.char('Detail', size=150, required=True),
		'notes':fields.text('Notes'),
		'code':fields.text('Code'),
		'calc_method': fields.selection([('P','Percent'), ('A','Amount'), ('C','Code')],'Calc Method', required =True), # To establish the calculated method
	}
	
	def on_change_type(self, cr, uid, ids, deduction_type):
		v = {}
		ded_type_browse = self.pool.get('hr_payroll_cr.deduction_type').browse(cr, uid, deduction_type)
		v['amount'] = ded_type_browse.amount
		v['calc_method'] = ded_type_browse.calc_method
		v['code'] = ded_type_browse.code
		v['name'] = ded_type_browse.name
		return {'value':v}
	
hr_payroll_cr_deduction()

class hr_payroll_cr_deduction_line(osv.osv):
	_name = 'hr_payroll_cr.deduction_line'
	_rec_name = 'total'
	_columns = {
		'deduction' : fields.many2one('hr_payroll_cr.deduction', 'Deduction', required =True),
		'amount' : fields.float('Amount', digits=(16,4), required =True),
		'date' : fields.date('Date'),
		'percent' : fields.boolean('Percent'),
		'total' : fields.float('Total', digits=(16,4)),
		'payment_per_contract_line' : fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
	}	
hr_payroll_cr_deduction_line()

class hr_payroll_cr_loan_type(osv.osv):
	_name = 'hr_payroll_cr.loan_type'
	_columns = {
		'name': fields.char('Name', size=150, required =True),
		'interest': fields.float('Interest', required =True, digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'notes': fields.text('Notes'),
		'deadline': fields.date('Date Line'),
		'principal': fields.float('Principal', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'account':fields.many2one('account.account', 'Account', select="0"),
	}
hr_payroll_cr_loan_type()

#########################################
#TODO
#Create of loan solicitude
#########################################

class hr_payroll_cr_loan(osv.osv):
	_name = 'hr_payroll_cr.loan'
	_rec_name = 'detail'
	_columns = {
		'name': fields.char('Name', size=150, required =True),
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"), # Contract to which payment are made
		'start_date': fields.date('Start Date', required =True, select="1"),
		'term': fields.integer('Term', required =True, select="0", help="If you select both fortnights, the term becomes biweekly, if you select one of these, the term becomes monthly"), # this field store the term of the loan
		'payment': fields.one2many('hr_payroll_cr.loan_payment','loan','Payment', select="0"), #FALTA REPARAR A int(config['price_accuracy'])
		'detail': fields.char('Detail', size=150, required =True),
		'notes': fields.text('Notes', select="0"),
		'principal': fields.float('Principal', digits=(16 , 4), required =True, select="1"), #FALTA REPARAR A int(config['price_accuracy'])
		'balance': fields.float('Balance', digits=(16 , 4), required =True, select="0"), #FALTA REPARAR A int(config['price_accuracy'])
		'interest': fields.float('Interests', digits=(16 , 4), required =True, select="0", help="If you select both fortnights, the interest becomes biweekly, if you select one of these, the interest becomes monthly"), #FALTA REPARAR A int(config['price_accuracy'])
		'loan_type': fields.many2one('hr_payroll_cr.loan_type', 'Loan Type', select="0", required=True),
		'account':fields.many2one('account.account', 'Account', required=True, select="0"),
		'first_fortnight':fields.boolean('First Fortnight'),
		'second_fortnight':fields.boolean('Second Fortnight'),
		'fixed_quota':fields.boolean('Fixed Quota'),
		'quota': fields.float('Quota', digits=(16, 4)),
	}
	


	def on_change_second_fortnight(self, cr, uid, ids, fortnight):
		v={}
		if not fortnight:
			v['first_fortnight'] = True
		return {'value' : v}
	def on_change_first_fortnight(self, cr, uid, ids, fortnight):
		v={}
		if not fortnight:
			v['second_fortnight'] = True
		return {'value' : v}
	
	def on_change_type(self, cr, uid, ids, loan_type):
		v = {}
		loan_type_browse = self.pool.get('hr_payroll_cr.loan_type').browse(cr, uid, loan_type)
		v['principal'] = loan_type_browse.principal
		v['interest'] = loan_type_browse.interest
		v['balance'] = loan_type_browse.principal
		v['name'] = loan_type_browse.name
		#v['account'] = loan_type_browse.account
		return {'value' : v}

	_defaults={
		'first_fortnight':lambda *a: True,
		'second_fortnight':lambda *a: True,
	}
hr_payroll_cr_loan()

class hr_payroll_cr_other_income(osv.osv):
	_name = 'hr_payroll_cr.other_income'
	_rec_name = 'detail'
	_columns = {
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"), # Contract to which payment are made
		'date': fields.date('Date', required =True, select="1"),
		'amount': fields.float('Amount', digits=(16 , 4), required =True, select="2"), #FALTA REPARAR A int(config['price_accuracy'])
		'notes': fields.text('Notes', select="0"),
		'detail': fields.char('Detail', size=150, select="0", required=True),
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
		'account': fields.many2one('account.account', 'Account', required =True, select="0"),
		'calculated_on_base_salary': fields.boolean('Calculated on Base Salary', select="0"), 
	}
hr_payroll_cr_other_income()

class hr_payroll_cr_saving_type(osv.osv):
	_name = 'hr_payroll_cr.saving_type'
	_columns = {
		'name': fields.char('Name', size=64, required =True),
		'percent': fields.boolean('Percent'),
		'quota': fields.float('Quota', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'notes': fields.text('Notes'),
		'saving': fields.one2many('hr_payroll_cr.saving', 'type', 'Saving', required =True),
		'account':fields.many2one('account.account', 'Account', select="0"),
	}
hr_payroll_cr_saving_type()

#########################################
#TODO
#Create a wizard to the saving solicitude
#########################################

class hr_payroll_cr_saving(osv.osv):
	_name = 'hr_payroll_cr.saving'
	_rec_name = 'detail'
	_columns = {
		'name': fields.char('Name', size=64, required =True),
		'start_date': fields.date('Start Date', required =True, select="1"),
		'end_date': fields.date('End Date', select="2"),
		'quota': fields.float('Quota', digits=(16 , 4), required =True, select="0"), #FALTA REPARAR A int(config['price_accuracy'])
		'detail': fields.char('Detail', size=150, select="0", required=True),
		'notes': fields.text('Notes', select="0"),
		'total': fields.float('Total', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'type': fields.many2one('hr_payroll_cr.saving_type', 'Saving Type', select="0", required=True),
		'percent': fields.boolean('Percent', select="0"),
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"),
		'saving_active':fields.boolean('Saving Active', select = "0"),
		'account':fields.many2one('account.account', 'Account', required=True, select="0"),
	}

    
	def on_change_type(self, cr, uid, ids, saving_type):
		v={}
		saving_type_browse = self.pool.get('hr_payroll_cr.saving_type').browse(cr, uid, saving_type)
		v['quota'] = saving_type_browse.quota
		v['percent'] = saving_type_browse.percent
		v['name'] = saving_type_browse.name
		return {'value': v}
		
	_defaults = {
		'saving_active': lambda *a: True,
    }
hr_payroll_cr_saving()



class hr_payroll_cr_christmas_bonus_payment(osv.osv):
	_name = 'hr_payroll_cr.christmas_bonus_payment'
	_rec_name = 'detail'
	_columns = {
		'date': fields.date('Date', required =True),
		'amount': fields.float('Amount', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'detail': fields.char('Detail', size=150),
		'notes': fields.text('Notes'),
		'payment_per_contract': fields.many2one('hr_payroll_cr.payment_per_contract', 'Payment Per Contract'),
		'contract': fields.many2one('hr.contract', 'Contract')
	}
hr_payroll_cr_christmas_bonus_payment()

class hr_payroll_cr_christmas_bonus_quota(osv.osv):
	_name = 'hr_payroll_cr.christmas_bonus_quota'
	_rec_name = 'detail'
	_columns = {
		'date': fields.date('Date', required =True),
		'amount': fields.float('Amount', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'detail': fields.char('Detail', size=150, required =True),
		'contract': fields.many2one('hr.contract', 'Contract')
	}
hr_payroll_cr_christmas_bonus_quota()

class hr_payroll_cr_saving_quota(osv.osv):
	_name = 'hr_payroll_cr.saving_quota'
	_rec_name = 'date'
	_columns = {
		'date': fields.date('Date', required =True),
		'quota': fields.float('Quota', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'saving': fields.many2one('hr_payroll_cr.saving', 'Saving', required =True),
		'total': fields.float('Total', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
	}
hr_payroll_cr_saving_quota()

class hr_payroll_cr_loan_payment(osv.osv):
	_name = 'hr_payroll_cr.loan_payment'
	_rec_name = 'date'
	_columns = {
		'date': fields.date('Date', required =True),
		'payment': fields.float('Payment', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'loan': fields.many2one('hr_payroll_cr.loan', 'Loan', required =True),
		'balance': fields.float('balance', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
	}
hr_payroll_cr_loan_payment()

class hr_payroll_cr_unemployement_fee(osv.osv):
	_name = 'hr_payroll_cr.unemployement_fee'
	_rec_name = 'contract'
	_columns = {
		'contract': fields.many2one('hr.contract', 'Contract', required =True), # Contract to which payment are made
		'amount': fields.float('Amount', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'account':fields.many2one('account.account', 'Account'),
	}
hr_payroll_cr_unemployement_fee()

class hr_payroll_cr_company(osv.osv):
	_name = 'res.company' # 'hr_payroll_cr.company'
	_inherit = 'res.company'
	_columns = {
		'national_holiday': fields.many2one('hr_payroll_cr.national_holiday', 'National Holiday'),
		'min_days_for_vacation': fields.integer('Minimum days for vacation'),
		'default_over_salary_account': fields.many2one('account.account', 'Default Over Salary Account'),
		'default_extra_hours_account': fields.many2one('account.account', 'Default Extra Hours Account'),
		'default_saving_account': fields.many2one('account.account', 'Default Saving Account'),
		'default_loan_account': fields.many2one('account.account', 'Default Loan Account'),
		'default_working_holiday_account': fields.many2one('account.account', 'Default Working Holiday Account'),
		'default_other_income_account': fields.many2one('account.account', 'Default Other Income Account'),
		'default_incapacity_period_type_account': fields.many2one('account.account', 'Default Incapacity Period Time Account'),
		'default_other_deduction_account': fields.many2one('account.account', 'Default Other Deduction Account'),
		'christmas_bonus_account': fields.many2one('account.account', 'Christmas Bonus Account'),
		'unemployment_fee_account': fields.many2one('account.account', 'Unemploymet Fee Account'),
		'default_commission_account': fields.many2one('account.account', 'Default Comission Account'),
		'exonerated_retirement_fund_percent': fields.float('Exonerated Retirement Fund Percent', digits = (16, 4)),
		'amount_for_children': fields.float('Rent Tax reduce amount per child', digits =(16,4)),
		'amount_for_spouse': fields.float('Rent Tax reduce amount for spouse', digits =(16,4)),
		'working_holiday_percent_payment': fields.float('Payment Percent per worked holiday', digits = (16, 4)),
	}
	_defaults = {
        'amount_for_children': lambda *a: 0,
        'amount_for_spouse' : lambda *a: 0,
        'working_holiday_percent_payment' : lambda *a: 2,
    }
hr_payroll_cr_company()

class hr_payroll_cr_incapacity_period_type_line(osv.osv):
	_name = 'hr_payroll_cr.incapacity_period_type_line'
	_rec_name = 'amount'
	_columns = {
		'amount': fields.float('Amount', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'start_day': fields.integer('Start Day', required =True, help='Start day of the period, if it\'s the first one is 1; if not, it\'s the last value + 1.'),
		'end_day': fields.integer('End Day', required =True, help='If this period line doesn\'t have an end date, then the value is 0.'),
		'percent': fields.boolean('Percent'),
		'reflectible': fields.boolean('Reflectible', help='Mark this option if you want this benefit to be reflected on the gross salary'),
		'period_type': fields.many2one('hr_payroll_cr.incapacity_period_type', 'Period Type'),
	}
hr_payroll_cr_incapacity_period_type_line()

class hr_payroll_cr_holiday_per_contract(osv.osv): #### 
	_name = 'hr_payroll_cr.holiday_per_contract'
	_columns = {
		'contract': fields.many2one('hr.contract', 'Contract', required=True, select="2"),
		'notes': fields.text('Notes', select="0"),
	#	'history': fields.one2many('hr_payroll_cr.vacation.history', 'vacation', 'Vacation History'),
		'holiday_period': fields.one2many('hr_payroll_cr.holiday_period', 'holiday', 'Holiday period', readonly=True),
		'account':fields.many2one('account.account', 'Account', required=True, select="0"),
	}	
	_rec_name = 'contract'
	
hr_payroll_cr_holiday_per_contract()

class hr_payroll_cr_holiday_period(osv.osv):
	_name = 'hr_payroll_cr.holiday_period'
	_columns = {

		'detail': fields.char('Detail', size=150, select="1"),
		'start_date': fields.date('Date Start', select="2"),
		'end_date': fields.date('Date End', select="2"),

		'notes': fields.text('Notes', select="0"),
		'total_days': fields.integer('Total days', select="2"),
		'holiday_per_day': fields.one2many('hr_payroll_cr.holiday_per_day', 'holiday_period', 'Holiday per Day', select="0"),
		'holiday': fields.many2one('hr_payroll_cr.holiday_per_contract', 'Holiday', select="2"),
		'name':fields.char('Name', size=64),
		'surname1':fields.char('Surname 1', size=64),
		'surname2':fields.char('Surname 2', size=64),
	}	
	_rec_name = 'start_date'
	
	def _onchange_holiday(self, cr, uid, ids, holiday, total_days):
		holiday_browse = self.pool.get('hr_payroll_cr.holiday_per_contract').browse(cr, uid, holiday)
		debug(holiday_browse)
		debug(holiday_browse.contract.id)
		contract = self.pool.get('hr.contract').browse(cr, uid, holiday_browse.contract.id)
		debug(contract)
		accumulated_holidays = contract.accumulated_holidays
		remaining_holidays = 0
		remaining_holidays = accumulated_holidays - total_days
		self.pool.get('hr.contract').write(cr, uid, contract.id, {'accumulated_holidays':remaining_holidays}, None)
		employee_browse = self.pool.get('hr.employee').browse(cr, uid, contract.employee_id.id)
		v = {}
		v['name'] = employee_browse.name
		v['surname1'] = employee_browse.surname1
		v['surname2'] = employee_browse.surname2
		return{'value':v}
			
	def str2date(self, date_str):
		date_unformat = time.strptime(date_str, '%Y-%m-%d')
		return datetime.date(date_unformat.tm_year, date_unformat.tm_mon, date_unformat.tm_mday)

	def interval(self,edate, idate):
		return (edate - idate)
		
	def _create_holiday_per_day(self, cr, uid, ids, context=None):
		fields = self.browse(cr,uid,ids)[0]
		holiday_period_id = fields.id
		start_date = fields.start_date
		end_date = fields.end_date
		
		day_quantity = self.interval(self.str2date(end_date), self.str2date(start_date)	).days + 1
		holiday_date = self.str2date(start_date)
		for i in range(1, day_quantity):			
			self.pool.get('hr_payroll_cr.holiday_per_day').create(cr, uid, {'date': holiday_date, 'paid':False, 'holiday_period':fields.id})
			#incremento la fecha al dia siguiente
			holiday_date = holiday_date + timedelta(1) 
		return
		
	def onchange_date(self, cr, uid, ids, start_date, end_date):
		result = {}
		if start_date:
			days = self.interval(self.str2date(end_date), self.str2date(start_date)).days + 1
			result['total_days'] = days
		return {'value':result}
		
	def holiday_cron(self, cr, uid, context=None):
		months30=[4,6,9,11]
		contract_ids = self.pool.get('hr.contract').search(cr, uid, [])
		debug(contract_ids)
		for contract_id in contract_ids:
			debug(contract_id)
			contract = self.pool.get('hr.contract').browse(cr, uid, contract_id)
			today = date.today()
			month= date.month
			date_start = self.str2date(contract.date_start)
			debug(today)
			debug(date_start)
			if month == 2:
				if  today == 29:
					a=none
				elif today == 28 and contract_id >= 28:
					plus_one = contract.accumulated_holidays + 1
					debug(plus_one)
					self.pool.get('hr.contract').write(cr, uid, contract_id, {'accumulated_holidays':plus_one}, None)
				elif today > date_start and today.day == date_start.day:
					plus_one = contract.accumulated_holidays + 1
					debug(plus_one)
					self.pool.get('hr.contract').write(cr, uid, contract_id, {'accumulated_holidays':plus_one}, None)
			elif month in months30:
				if today==30 and contract_id >= 30:
					plus_one = contract.accumulated_holidays + 1
					debug(plus_one)
					self.pool.get('hr.contract').write(cr, uid, contract_id, {'accumulated_holidays':plus_one}, None)
				elif today > date_start and today.day == date_start.day:
					plus_one = contract.accumulated_holidays + 1
					debug(plus_one)
					self.pool.get('hr.contract').write(cr, uid, contract_id, {'accumulated_holidays':plus_one}, None)
			
			elif today > date_start and today.day == date_start.day:
					plus_one = contract.accumulated_holidays + 1
					debug(plus_one)
					self.pool.get('hr.contract').write(cr, uid, contract_id, {'accumulated_holidays':plus_one}, None)
			
hr_payroll_cr_holiday_period()

class hr_payroll_cr_holiday_per_day(osv.osv):
	_name = 'hr_payroll_cr.holiday_per_day'
	_rec_name = 'date'
	_columns = {
		'date': fields.date('Date'),
		'paid': fields.boolean('Paid', readonly=True),
		'holiday_period': fields.many2one('hr_payroll_cr.holiday_period', 'Holiday'),
	}
hr_payroll_cr_holiday_per_day()

class hr_payroll_cr_holiday_history(osv.osv):
	_name = 'hr_payroll_cr.holiday_history'
	_rec_name = 'holiday_period'
	_columns = {
		'actual_quantity': fields.integer('Accumulated days', readonly=True),
		'requested_quantity': fields.integer('Requested days', readonly=True),
		'new_quantity': fields.integer('New accumulated days', readonly=True),
		'holiday_period': fields.many2one('hr_payroll_cr.holiday_period', 'Holiday Period'),
		'holiday': fields.many2one('hr_payroll_cr.holiday_per_contract', 'Holiday Per Contract'),
	}
hr_payroll_cr_holiday_history()


class hr_payroll_cr_commission(osv.osv):
	_name = 'hr_payroll_cr.commission'
	_rec_name = 'detail'
	_columns = {
		'amount': fields.float('Amount', digits=(16 , 4), required =True, select="1"), #FALTA REPARAR A int(config['price_accuracy'])
		'notes': fields.text('Notes', select="2"),
		'detail': fields.char('Detail', size=150, select="0", required=True),
		'percent': fields.boolean('Percent', select="0"),
		'account': fields.many2one('account.account', 'Account', required =True, select="0"),
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"),
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
		'date': fields.date('Date', required =True, select="0"),
	}
hr_payroll_cr_commission()


class hr_payroll_cr_retirement_fund(osv.osv):
	_name = 'hr_payroll_cr.retirement_fund'
	_rec_name = 'contract'
	_columns = {
		'amount': fields.float('Amount', digits=(16 , 4), select="1"), #FALTA REPARAR A int(config['price_accuracy'])
		'fund_operator': fields.many2one('res.partner', 'Fund Operator', select="2"),
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"),
		'exonerated_retirement_fund': fields.one2many('hr_payroll_cr.exonerated_retirement_fund', 'retirement_fund', 'Exonerated Retirement Fund', select="0"),
		'taxed_retirement_fund': fields.one2many('hr_payroll_cr.taxed_retirement_fund', 'retirement_fund', 'Taxed Retirement Fund', select="0"),
		'retirement_fund_history': fields.one2many('hr_payroll_cr.retirement_fund_history', 'retirement_fund', 'Retirement Fund History', select="0"),
		'account':fields.many2one('account.account', 'Account', required=True, select="0"),
		'percent': fields.float('Percent', digits=(16, 4), select="1"),
		'detail':fields.char('Detail', size=64, required=False, readonly=False, select="0"),
	}
hr_payroll_cr_retirement_fund()

class hr_payroll_cr_retirement_fund_history(osv.osv):
	_name = 'hr_payroll_cr.retirement_fund_history'
	_rec_name = 'retirement_fund'
	_columns = {
		'detail': fields.char('Detail', size=150, required=True),
		'notes': fields.text('Notes'),
		'amount': fields.float('Amount', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'date': fields.date('Date', required =True),
		'retirement_fund': fields.many2one('hr_payroll_cr.retirement_fund', 'Retirement Fund', required =True)
	}
hr_payroll_cr_retirement_fund_history()

class hr_payroll_cr_exonerated_retirement_fund(osv.osv):
	_name = 'hr_payroll_cr.exonerated_retirement_fund'
	_rec_name = 'retirement_fund'
	_columns = {
		'amount': fields.float('Amount', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'detail': fields.char('Detail', size=150),
		'date': fields.date('Date', required =True),
		'percent': fields.float('Percent', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'retirement_fund': fields.many2one('hr_payroll_cr.retirement_fund', 'Retirement Fund'),
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
	}
hr_payroll_cr_exonerated_retirement_fund()

class hr_payroll_cr_taxed_retirement_fund(osv.osv):
	_name = 'hr_payroll_cr.taxed_retirement_fund'
	_rec_name = 'retirement_fund'
	_columns = {
		'amount': fields.float('Amount', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'detail': fields.char('Detail', size=150),
		'date': fields.date('Date', required =True),
		'percent': fields.float('Percent', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'retirement_fund': fields.many2one('hr_payroll_cr.retirement_fund', 'Retirement Fund'),
	}
hr_payroll_cr_taxed_retirement_fund()

class hr_payroll_cr_employer_social_security_type(osv.osv):
	_name = 'hr_payroll_cr.employer_social_security_type'
	_columns = {
		'detail': fields.char('Detail', size=150, required=True),
		'notes': fields.text('Notes'),
		'account': fields.many2one('account.account', 'Account', required =True),
		'amount': fields.float('Amount', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'name': fields.char('Name', size=150, required =True),
		'percent': fields.boolean('Percent'),
		'calc_method': fields.selection([('P', 'Percent'), ('A', 'Amount'), ('C', 'Code')], 'Calc Method', size=1, required =True),	# P percent, A amount, C code
		'code': fields.text('Code'),
		'employer_social_security' : fields.one2many('hr_payroll_cr.employer_social_security', 'employer_social_security_type', 'Employer Social Security')
	}
hr_payroll_cr_employer_social_security_type()

class hr_payroll_cr_employer_social_security(osv.osv):
	_name = 'hr_payroll_cr.employer_social_security'
	_columns = {
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"), # Contract to which payment are made
		'name': fields.char('Name', size=64, required =True, select="1"),
		'account': fields.many2one('account.account', 'Account', required =True, select="2"),
		'notes': fields.text('Notes', select="0"),
		'employer_social_security_type' : fields.many2one('hr_payroll_cr.employer_social_security_type', 'Employer Social Security Type', required = True, select="1"),
		'employer_social_security_line' : fields.one2many('hr_payroll_cr.employer_social_security_line', 'employer_social_security', 'Employer Social Security Line'),
	}
hr_payroll_cr_employer_social_security()

class hr_payroll_cr_employer_social_security_line(osv.osv):
	_name = 'hr_payroll_cr.employer_social_security_line'
	_rec_name = 'employer_social_security'
	_columns = {
		'employer_social_security' : fields.many2one('hr_payroll_cr.employer_social_security', 'Employer Social Security', required =True),
		'amount' : fields.float('Amount', digits=(16,4), required =True),
		'start_date' : fields.date('start date', required =True),
		'end_date' : fields.date('end date', required =True),
		'percent' : fields.boolean('Percent'),
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
	}
hr_payroll_cr_employer_social_security_line()

class hr_payroll_cr_rent_tax(osv.osv):
	_name = 'hr_payroll_cr.rent_tax'
	_rec_name = 'contract'
	_columns = {
		'contract':fields.many2one('hr.contract', 'Contract'),
		'amount':fields.float('Amount', digits=(16, 4)),
		'date':fields.date('Date'),	
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),	
	}
hr_payroll_cr_rent_tax()



class hr_payroll_cr_foreclosure_type(osv.osv):
	_name = 'hr_payroll_cr.foreclosure_type'
	_columns = {
		'name': fields.char('Name', size=150, required =True),
		'notes': fields.text('Notes'),
		'account':fields.many2one('account.account', 'Account', required=True, select="0"),
		'quota':fields.integer('Quota'),
	}
	_defaults={
		'quota':lambda *a: 0.0000,
	}
hr_payroll_cr_foreclosure_type()

class hr_payroll_cr_foreclosure(osv.osv):
	_name = 'hr_payroll_cr.foreclosure'
	_rec_name = 'detail'
	_columns = {
		'name': fields.char('Name', size=150, required =True),
		'active':fields.boolean('Active'),
		'contract': fields.many2one('hr.contract', 'Contract', required =True, select="0"), # Contract to which payment are made
		'start_date': fields.date('Start Date', required =True, select="1"),
		'payment': fields.one2many('hr_payroll_cr.foreclosure_payment','foreclosure','Payment', select="0"), #FALTA REPARAR A int(config['price_accuracy'])
		'detail': fields.char('Detail', size=150, required =True),
		'notes': fields.text('Notes', select="0"),
		'balance': fields.float('Balance', digits=(16 , 4), select="0"), #FALTA REPARAR A int(config['price_accuracy'])
		'foreclosure_type': fields.many2one('hr_payroll_cr.foreclosure_type', 'Foreclosure Type', select="0", required=True),
		'account':fields.many2one('account.account', 'Account', required=True, select="0"),
		'first_fortnight':fields.boolean('First Fortnight'),
		'second_fortnight':fields.boolean('Second Fortnight'),
		'quota': fields.float('Quota', digits=(16, 4)),
	}

	def on_change_second_fortnight(self, cr, uid, ids, fortnight):
		v={}
		if not fortnight:
			v['first_fortnight'] = True
		return {'value' : v}
	def on_change_first_fortnight(self, cr, uid, ids, fortnight):
		v={}
		if not fortnight:
			v['second_fortnight'] = True
		return {'value' : v}
	
	def on_change_type(self, cr, uid, ids, foreclosure_type):
		v = {}
		foreclosure_type_browse = self.pool.get('hr_payroll_cr.foreclosure_type').browse(cr, uid, foreclosure_type)
		v['name'] = foreclosure_type_browse.name
		v['quota'] = foreclosure_type_browse.quota
		#v['account'] = loan_type_browse.account
		return {'value' : v}

	_defaults={
		'first_fortnight':lambda *a: True,
		'second_fortnight':lambda *a: True,
		'balance':lambda *a: 0.0000,
	}
hr_payroll_cr_foreclosure()

class hr_payroll_cr_foreclosure_payment(osv.osv):
	_name = 'hr_payroll_cr.foreclosure_payment'
	_rec_name = 'date'
	_columns = {
		'date': fields.date('Date', required =True),
		'payment': fields.float('Payment', digits=(16 , 4)), #FALTA REPARAR A int(config['price_accuracy'])
		'foreclosure': fields.many2one('hr_payroll_cr.foreclosure', 'Foreclosure', required =True),
		'balance': fields.float('balance', digits=(16 , 4), required =True), #FALTA REPARAR A int(config['price_accuracy'])
		'payment_per_contract_line': fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
	}
hr_payroll_cr_foreclosure_payment()

class hr_payroll_cr_refund(osv.osv):
	_name='hr_payroll_cr.refund'
	_rec_name='contract'
	_columns={
		'date':fields.date('Date'),
		'amount':fields.float('Amount', digits=(16, 4)),
		'contract':fields.many2one('hr.contract', 'Contract'),
		'detail':fields.char('Detail', size=120),
		'account':fields.many2one('account.account', 'Account', required=True, select="0"),
		'paid':fields.boolean('Paid'),
		'payment_per_contract_line':fields.many2one('hr_payroll_cr.payment_per_contract_line', 'Payment Per Contract Line'),
	}
hr_payroll_cr_refund()