Repository navigation
Expand file tree
/
Copy pathXTax.py
More file actions
1506 lines (1318 loc) · 56.4 KB
/
Copy pathXTax.py
File metadata and controls
1506 lines (1318 loc) · 56.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Python 3.8.0 32-bit
# language: python
# name: python38032bit6948bcf2bd1d495c8d3b7cfa49a7d542
# ---
# +
import yaml
import pandas as pd
import os
import datetime
import inspect
class Tax:
"""Class representing a spécific year of Tax"""
#
# Function __init__
#
# Params: year of tax
#
# Description : Class initializer
# if a Tax profile file corresponding to the year exists in the current directory, it is automatically loaded
#
# Return: Nothing
#
def __init__(self, year=2010, loglevel=3, autoload=True, user=""):
self.LogLevel = loglevel
self.__Log("Beginning of Init")
self.__Reset()
self.LogLevel = loglevel
self.Year = year
#Search for the TaxDefinition file
found = False
fname = f'{self.classAbsDir}\\TaxDefinition.yaml'
if os.path.isfile(fname):
found = True
self.Taxedeffile = fname
else:
fname = f'{self.classAbsDir}\\Profiles\\TaxDefinition.yaml'
if os.path.isfile(fname):
found = True
self.Taxedeffile = fname
if not found:
ExceptError = "ERROR No tax definition file available - Read the documentation to continue"
self.__Log(ExceptError)
raise ValueError(ExceptError)
found = False
#Search for a potential profile to autoload
if autoload:
fname = f'{self.classAbsDir}\\{year}.yaml'
if os.path.isfile(fname):
found = True
else:
fname = f'{self.classAbsDir}\\Profiles\\{year}.yaml'
if os.path.isfile(fname):
found = True
if not found and user != "":
#Check path with user
fname = f'{self.classAbsDir}\\{user}-{year}.yaml'
if os.path.isfile(fname):
found = True
else:
fname = f'{self.classAbsDir}\\Profiles\\{user}\\{year}.yaml'
if os.path.isfile(fname):
found = True
if found:
self.__Log("Automatic load of {}".format(fname))
self.LoadProfile(fname)
Profile_Name=fname
self.__Log("End of Init")
#---------------------------------------------------------------------------------------------------------------------- return
# Internals Method/function
#-----------------------------------------------------------------------------------------------------------------------
#
# Function Reset
#
# Params: Initialize any Class Global Variable (Properties)
#
# Description : Function needed to avoid side effect on module reload
#
# Return: Nothing
#
def __Reset(self):
self.__Log("Reset Properties")
self.Year = 0
self.NbParts = 1
self.bProfileLoaded = False
self.bTaxDefLoaded = False
self.bFormsProcessed = False
self.bTaxCalculted = False
self.bIRCalulated = False
self.LogLevel = 3
self.RawTaxProfile = None
self.RawTaxDef = None
self.NetTax = 0
self.SoldeImpot = 0
self.RevFiscalRef = 0
self.DeficitFoncierAnterieur = 0
self.TauxPrelevementSource = 0
self.Taxedeffile = ""
self.classAbsDir = os.path.abspath(os.path.join(inspect.getfile(self.__class__), os.pardir))
self.ListDeficit = []
self.FormList = []
self.VarDict = {}
self.FieldDict = {}
self.StepperDict={}
self.GVarTaxDefDict={}
self.ReportDict = {}
self.EnableComputeLog = False
self.ComputeLogBuffer = []
self.Local2Del = []
return
#
# Function Log
#
# Params: String to log
# level of the logging
#
# Description : If the LogLevel is compatible, the string is written to the console
#
# Loglevel 1 = Debug <-default for each Log calls
# Loglevel 2 = Log
# Loglevel 3 = Warning <- Default level at Class init (show only warning and errors)
# LogLevel 4 = Errors
# Loglevel 5 = Exceptions
#
# Return: Nothing
#
def __Log(self, string, level=1):
if level >= self.LogLevel:
print (string)
return
#
# Function ExecStr
#
# Params: String to log
# logging enabled or not
#
# Description : Execute a python code and eventually log it
#
#
# Return: Nothing
#
def __ExecStr(self, string):
result = True
bef = locals().copy()
try:
exec(string, globals(),locals())
except Exception as e:
self.__Log(f'Exception while Computing {string}',5)
self.__Log(f'Exception : {e.__class__}',5)
result = False
aft= locals().copy()
if result:
for k in aft.keys():
if k not in bef.keys() and k != 'bef':
if k not in self.Local2Del:
self.Local2Del.append(k)
globals()[k]=locals()[k]
if self.EnableComputeLog:
if not string.startswith('del') and not string.startswith('ldv'):
self.ComputeLogBuffer.append(string)
return result
#
# Function LoadYamlFile
#
# Params: Yaml File name to load
#
# Description : Load and serialize a Tax Profile
#
# Return: True of False and the Yaml Raw Content
#
def __LoadYaml(self, file):
self.__Log(f'Beginning of LoadYamlFile {file}')
if os.path.isfile(file):
with open(file) as yaml_file:
YamlContent = yaml.load(yaml_file, Loader=yaml.FullLoader)
yaml_file.close()
result=True
else:
result=False
self.__Log(f'End of LoadYamlFile {file}')
return result,YamlContent
# Function FlatenTP
#
# Params:
#
# Description
# From the RawTaxProfile loaded, if any, the function build a set of Field,variable dictionary
# as well as a list of Forms definition found
# Each Field name follow the naming schema :
# F{Form Number Name}S{Section Number}{FieldName}
#
# Return:
#
def __FlatenTP(self):
self.__Log("Beginning of FlatenTP")
if self.RawTaxProfile != None:
for gv in self.RawTaxProfile:
if gv != "Forms":
try:
self.VarDict[f'GV_{gv}']=int(f'{self.RawTaxProfile[gv]}')
except:
self.VarDict[f'GV_{gv}']=f'{self.RawTaxProfile[gv]}'
pass
self.__Log(f' Variable GV_{gv}: {self.RawTaxProfile[gv]}',2)
if 'Forms' in self.RawTaxProfile:
self.__Log(f'\nLoading Forms variables',2)
for i1, lv1 in enumerate(self.RawTaxProfile["Forms"]):
for k1, dv1 in lv1.items():
if k1.lower() == "form":
self.FormList.append(dv1)
curform="F"+str(dv1)
self.__Log(f' Form {curform}',2)
if k1.lower() == "sections":
for i2, lv2 in enumerate(dv1):
for k2, dv2 in lv2.items():
if k2.lower() == "section":
cursection="S"+str(dv2)
elif k2.lower() == "fields":
for i3, lv3 in enumerate(dv2):
for k3, dv3 in lv3.items():
fieldname = curform + cursection + "_" + k3
self.FieldDict[fieldname]=dv3
self.__Log(f' Field {fieldname}: {dv3}',2)
else:
self.VarDict[f'{curform}{cursection}_{k2}']=f'{dv2}'
self.__Log(f' Variable {curform}{cursection}_{k2}: {dv2}',2)
self.__Log("End of FlatenTP")
return
# Function FlatenTD
#
# Params:
#
# Description
# From the RawTaxDef loaded, if any, the function build a set of variables and execution steps per section per Form
# Each variable name follow the naming schema :
# TDV_F{Form Number Name}S{Section Number}{dName}
# Each step name follow the naming schema :
# TDS_F{Form Number Name}S{Section Number}{SeqNumber}
#
# Return:
#
def __FlatenTD(self):
self.__Log("Beginning of FlatenTD")
if self.RawTaxDef != None:
for k in self.RawTaxDef["Tax"]:
if k.lower() != "forms":
keyname=f'TDV_G_{k.lower()}'
self.GVarTaxDefDict[keyname]=self.RawTaxDef["Tax"][k]
stepperseq=0
for i, val in enumerate(self.RawTaxDef["Tax"]["Forms"]):
carryto2042List=""
finalresultList=""
for k, v in val.items():
if k.lower() == "form":
curform="F"+str(v)
if k.lower() == "carryto2042":
if carryto2042List == "":
carryto2042List=str(v)
else:
carryto2042List=f"{carryto2042List},{v}"
if k.lower() == "finalresult":
if finalresultList == "":
finalresultList=str(v)
else:
finalresultList=f"{finalresultList},{v}"
if k.lower() == "sections":
for ii, vval in enumerate(v):
for kk, vv in vval.items():
if kk.lower() == "section":
cursection="S"+str(vv)
stepperseq=0
else:
keyname=f'TDS_{curform}{cursection}_S{stepperseq}_{kk.lower()}'
self.StepperDict[keyname]=vv
stepperseq+=1
if carryto2042List != "":
keyname=f'TDS_{curform}S0_carryto2042'
self.StepperDict[keyname]=carryto2042List
if finalresultList != "":
keyname=f'TDS_{curform}S0_finalresult'
self.StepperDict[keyname]=finalresultList
self.__Log("End of FlatenTD")
return
# Function GetSectionFromName
#
# Params:
#
# Description :
# Extract the Section from the Name in the form of TDS_F{form}S{section}_S{Seq}_{Action}
#
# Return:
#
def __GetSectionFromName(self,StepName):
self.__Log(f'Beginning of GetSectionFromName {StepName}')
section = StepName[10:12]
if section[-1:]=="_": section = section[:1]
self.__Log(f'End of GetSectionFromName - Section = {section}')
return int(section)
# Function GetActionFromName
#
# Params:
#
# Description :
# Extract the Section from the Name in the form of TDS_F{form}S{section}_S{Seq}_{Action}
#
# Return:
#
def __GetActionFromName(self,StepName):
self.__Log(f'Beginning of GetActionFromName {StepName}')
sa = StepName.split("_")
action = sa[len(sa)-1]
self.__Log(f'End of GetActionFromName - Action = {action}')
return action
# Function LoadStepsFor
#
# Params:
#
# Description :
# Given a Forms Name, the function return a step dictionnary to execute in order to process the Form
#
# Return:
#
def __LoadStepsFor(self,FormsName):
self.__Log(f'Beginning of LoadStepsFor {FormsName}')
steps = pd.DataFrame.from_dict(self.StepperDict,orient='index')
steps.reset_index(level=0, inplace=True)
steps.rename(columns={'index': 'StepName', 0: 'Step'}, inplace=True)
steps["Section"]=steps["StepName"].apply(lambda x: self.__GetSectionFromName(x))
steps["Action"]=steps["StepName"].apply(lambda x: self.__GetActionFromName(x))
search_string=f'TDS_F{FormsName}'
StepsFor=steps[steps['StepName'].str.contains(search_string)]
self.__Log(f'End of LoadStepsFor {FormsName}')
return StepsFor
# Function GetSectionFields
#
# Params:
# fns : Form string name
# fdict : Dictionary where to populate fields:values
#
# Description :
#
#
# Return:
# flds : list of field=value
#
def __GetSectionFields(self,fns,fdict):
self.__Log(f'Beginning of __GetSectionFields for forms {fns}')
flds = [f'{k}={self.FieldDict[k]}' for k in list(self.FieldDict.keys()) if fns in k[:len(fns)]]
#Gen a dict with fields:values
for li in flds:
isl = li.split("=")
if len(isl) > 1:
fdict[isl[0]]=isl[1]
self.__Log(f'End of GetSectionFields {fdict}')
return flds
# Function ProcesSteps
#
# Params:
#
# Description :
# Given a Step list, Execute them and return the result in a Dictionary
#
# Return:
# Bool : False if error detected
#
def __ProcesSteps(self,Steps,CurForm):
self.__Log(f'Beginning of ProcesSteps for {CurForm}')
if self.EnableComputeLog:
self.ComputeLogBuffer.append(f'#Forms {CurForm}')
result = True
global CurLoop
currentfieldnamecontext=f"{CurForm}"
currentloopext=""
Sg=Steps.groupby('Section')
self.__Log(f'Sections found in form {CurForm} : {Sg.groups.keys()}')
lvarlist=[]
# Focus on each section of the Form
for cursection in sorted(Sg.groups.keys()):
if cursection != 0: self.__Log(f'\n Processing Section : {cursection}',2)
currentloopext=""
currentloopvl=[]
curcompute=[]
WeDoCompute=True
ConditionDetected=False
currentfieldnamecontext = f"F{CurForm}S{cursection}"
self.__Log(f"Current Field Prefix {currentfieldnamecontext}")
if self.EnableComputeLog and cursection!=0:
self.ComputeLogBuffer.append(f'# Section {cursection}')
# Narrow the Steps to the actual section
StepsForCurSection = Steps[Steps['Section']==cursection]
self.__Log(StepsForCurSection['Action'])
# CleanUp localy created Variable before processing section
for v in self.Local2Del:
r = self.__ExecStr(f'del globals()["{v}"]')
if r == False:
self.__Log(f'Error : While cleaning variable {v}',4)
self.Local2Del.clear()
# Look for loopon
sFor="loopon"
if not StepsForCurSection[StepsForCurSection['Action']==sFor].empty:
dfb = StepsForCurSection[StepsForCurSection['Action']==sFor].index.values.astype(int)[0]
currentloopext=StepsForCurSection.loc[dfb,"Step"]
self.__Log("\nLoop on detected")
currentloopext = f'{currentfieldnamecontext}_{currentloopext}'
if currentloopext in self.VarDict.keys():
self.__Log(f'Loop On : {self.VarDict[currentloopext]}',2)
currentloopvl = self.VarDict[currentloopext].split(",")
else:
self.__Log(f'Warning : Loop On Variable "{currentloopext}" not defined',2)
currentloopext = ""
# Look for reqfields
sFor="reqfields"
if not StepsForCurSection[StepsForCurSection['Action']==sFor].empty:
dfb = StepsForCurSection[StepsForCurSection['Action']==sFor].index.values.astype(int)[0]
self.__Log("\nRequired Fields detected")
if currentloopext == "":
currentloopvl.clear()
currentloopvl.append("*")
#Foreach element in currentloopvl
for lctxt in currentloopvl:
ifv = StepsForCurSection.loc[dfb,"Step"].split(",")
for i in range(len(ifv)):
if lctxt == "*":
ifv[i] = f"{currentfieldnamecontext}_{ifv[i]}"
else:
ifv[i] = f"{currentfieldnamecontext}_{ifv[i]}_{lctxt}"
# Gen LoopName and verify required Fields
for i in ifv:
self.__Log(f'Checking required field or variable {i}')
s0name = f'F{CurForm}S0_{i.split("_")[1]}'
lvname = f'F{CurForm}S{cursection}_{i.split("_")[1]}'
# If name not in the local section field dict
if i not in self.FieldDict.keys():
#Check in S0 contect of the Field Dict
if s0name in self.FieldDict.keys():
self.__Log(f'Loading Field variable {i} with its global S0 value : {self.FieldDict[s0name]}')
self.FieldDict[i]=self.FieldDict[s0name]
#Check as a variable
elif lvname not in self.VarDict.keys():
self.__Log(f' field or variable not defined yet. Initializing as a field with 0')
self.FieldDict[i]=0
else:
self.__Log(f' found as a variable with value {self.VarDict[i]}')
else:
self.__Log(f' found with value {self.FieldDict[i]}')
# Look for Condition
sFor="condition"
if not StepsForCurSection[StepsForCurSection['Action']==sFor].empty:
dfb = StepsForCurSection[StepsForCurSection['Action']==sFor].index.values.astype(int)[0]
Condition=StepsForCurSection.loc[dfb,"Step"].split(",")[0]
self.__Log("\nCondition detected")
self.__Log(f'Condition found to continue process section {cursection} : {Condition}',2)
ConditionDetected=True
#Look for repportfields
sFor="repportfields"
if not StepsForCurSection[StepsForCurSection['Action']==sFor].empty:
dfb = StepsForCurSection[StepsForCurSection['Action']==sFor].index.values.astype(int)[0]
self.__Log("\nRepport Fields detected")
if currentloopext == "":
currentloopvl.clear()
currentloopvl.append("*")
#Foreach element in currentloopvl
rfv = []
for lctxt in currentloopvl:
fv = StepsForCurSection.loc[dfb,"Step"].split(",")
for i in range(len(fv)):
if lctxt == "*":
fn = f"{currentfieldnamecontext}_{fv[i]}"
else:
fn = f"{currentfieldnamecontext}_{fv[i]}_{lctxt}"
rfv.append(fn)
self.__Log(f'List of Repport fields : {rfv}')
# Look for compute_custom
sFor="compute"
if not StepsForCurSection[StepsForCurSection['Action'].str.contains(sFor)].empty:
self.__Log("\nCompute sequence detected")
for dfb in StepsForCurSection[StepsForCurSection['Action'].str.contains(sFor)].index.values.astype(int):
cs = StepsForCurSection.loc[dfb,"Step"]
curcompute.append(cs)
self.__Log(f'List of Compute sequence : {curcompute}')
#Foreach element in currentloopvl
for lctxt in currentloopvl:
self.__Log(f'\nProcessing on variable {lctxt}',2)
CurLoop = lctxt
if self.EnableComputeLog and lctxt!="*":
self.ComputeLogBuffer.append(f'# Loop {lctxt}')
# CleanUp localy created Variable before processing loopOn
for v in self.Local2Del:
r = self.__ExecStr(f'del globals()["{v}"]')
if r == False:
self.__Log(f'Error : While cleaning variable {v}',4)
self.Local2Del.clear()
# Propagate localy the Fields of the section
self.__Log("\nField propagation in Locals",2)
for k in self.FieldDict.keys():
if k.startswith(f'{currentfieldnamecontext}'):
if lctxt == "*" or lctxt == k.split('_')[2]:
lf = k.split('_')[1]
if isinstance(self.FieldDict[k],str):
execstring = f'{lf} = "{self.FieldDict[k]}"'
else:
execstring = f'{lf} = {self.FieldDict[k]}'
r = self.__ExecStr(execstring)
if lf in globals().keys() and r != False:
self.__Log(f'Variable {lf} successfully created')
self.__Log(f'{lf} = {globals()[lf]}',2)
else:
self.__Log(f'Error : While emitting "{lf}"',4)
result = False
break
# Propagate localy the variables of the section
self.__Log("\nVariable propagation in Locals")
for k in self.VarDict.keys():
if k.startswith(f'{currentfieldnamecontext}'):
lf = k.split('_')[1]
if isinstance(self.VarDict[k],str):
execstring = f'{lf} = "{self.VarDict[k]}"'
else:
execstring = f'{lf} = {self.VarDict[k]}'
r = self.__ExecStr(execstring)
if lf in globals().keys() and r != False:
self.__Log(f'Variable {lf} successfully created')
self.__Log(f'{lf} = {globals()[lf]}',2)
else:
self.__Log(f'Error : While emitting "{lf}"',4)
result = False
break
if ConditionDetected:
try:
WeDoCompute = eval (Condition)
except Exception as e:
pass
if WeDoCompute:
# Compute
self.__Log('',2)
self.__Log("\nCompute")
for c in curcompute:
self.__Log(f'Processing {c}',2)
r = self.__ExecStr(c)
if r != True:
result = False
break
# Propagate back to dictionary
self.__Log("\nField back propagation to dictionary")
self.__Log("For fields in profile")
self.__Log('',2)
for f in self.Local2Del:
if lctxt == "*":
updf = f'{currentfieldnamecontext}_{f}'
else:
updf = f'{currentfieldnamecontext}_{f}_{lctxt}'
self.__Log(f'Updating self.FieldDict["{updf}"]')
if updf in self.FieldDict.keys():
self.__Log(f' Initial value : {self.FieldDict[updf]}')
r = self.__ExecStr(f'ldv = {f}')
if r == True:
self.FieldDict[updf] = ldv
self.Local2Del.remove("ldv")
self.__Log(f' New value : {self.FieldDict[updf]}')
if updf in rfv:
self.ReportDict[updf]=self.FieldDict[updf]
self.__Log("\nFor fields in report")
for k in rfv:
lf = k.split('_')[1]
if self.EnableComputeLog:
self.ComputeLogBuffer.append(f'print ("{lf} =",{lf})')
if lf not in self.Local2Del:
if lctxt == "*" or lctxt == k.split('_')[2]:
self.__Log(f'Updating self.FieldDict["{k}"]')
if k in self.FieldDict.keys():
self.__Log(f'Value of self.FieldDict["{k}"] = {self.FieldDict[k]}]')
else:
self.FieldDict[k] = 0
self.__Log(f'New value of self.FieldDict["{k}"] = {self.FieldDict[k]}')
self.ReportDict[updf]=self.FieldDict[k]
# Look for Agregate
flagkeep = False
sFor="agregate"
if not StepsForCurSection[StepsForCurSection['Action']==sFor].empty and WeDoCompute:
dfb = StepsForCurSection[StepsForCurSection['Action']==sFor].index.values.astype(int)[0]
agglist=StepsForCurSection.loc[dfb,"Step"].split(",")
if "[keep]" in agglist:
flagkeep = True
agglist.remove("[keep]")
self.__Log("\nAgregate detected")
self.__Log(f'\nField list to Aggregate : {agglist}')
if flagkeep:
self.__Log('With Flag Keep enabled')
for f in agglist:
f2clean=[]
lookupf = f'{currentfieldnamecontext}_{f}'
aggval = 0
for k in self.FieldDict.keys():
if k.startswith(f'{lookupf}'):
self.__Log(f'Found {k} = {self.FieldDict[k]} to aggregate')
try:
aggval = aggval + self.FieldDict[k]
if not flagkeep:
f2clean.append(k)
except:
self.__Log(f'Exception while aggregating {k}',5)
result = False
break
aggval = int(round(aggval))
#Cleanup the FieldDict after Aggregation
for fc in f2clean:
del self.FieldDict[fc]
self.__Log(f'Loading self.FieldDict[{lookupf}] with {aggval}',2)
self.FieldDict[lookupf]=aggval
# Look for Save
sFor="save"
if not StepsForCurSection[StepsForCurSection['Action']==sFor].empty:
dfb = StepsForCurSection[StepsForCurSection['Action']==sFor].index.values.astype(int)[0]
savlist=StepsForCurSection.loc[dfb,"Step"].split(",")
self.__Log("\nSave detected")
self.__Log(f'Field list to propagate in the S0 section for later calculation : {savlist}')
for f in savlist:
sectionf = f'{currentfieldnamecontext}_{f}'
targetf = f'F{CurForm}S0_{f}'
if sectionf in self.FieldDict.keys():
self.__Log(f'Loading {targetf} with value of {sectionf} = {self.FieldDict[sectionf]}',2)
self.FieldDict[targetf]=self.FieldDict[sectionf]
else:
self.__Log(f'Creating {targetf} loaded with {sectionf} = 0',2)
self.FieldDict[targetf]=0
# At the End ( After looping on each section)
# Get the steps for section 0
StepsForCurSection = Steps[Steps['Section']==0]
frlist=[]
# Look for FinalResult
sFor="finalresult"
if not StepsForCurSection[StepsForCurSection['Action']==sFor].empty:
dfb = StepsForCurSection[StepsForCurSection['Action']==sFor].index.values.astype(int)[0]
frlist=StepsForCurSection.loc[dfb,"Step"].split(",")
self.__Log("\nFinal Result detected")
self.__Log(f'Final Result list to propagate their equivalente in CarryTo2042 : {frlist}')
# Look for CarryTo2042
sFor="carryto2042"
if not StepsForCurSection[StepsForCurSection['Action']==sFor].empty:
dfb = StepsForCurSection[StepsForCurSection['Action']==sFor].index.values.astype(int)[0]
carrylist=StepsForCurSection.loc[dfb,"Step"].split(",")
self.__Log("\nCarry To 2042 detected")
self.__Log(f'Carry to 2042 list : {carrylist}')
if not frlist:
self.__Log(f'But the Final Result List is empty',4)
result = False
else:
i = 0
for f in carrylist:
resultf = f'F{CurForm}S0_{frlist[i]}'
targetf = f'F2042{f}'
if resultf in self.FieldDict.keys():
self.__Log(f'Loading {targetf} with value of {resultf} = {self.FieldDict[resultf]}')
if targetf in self.FieldDict.keys():
self.FieldDict[targetf]=self.FieldDict[targetf] + self.FieldDict[resultf]
else:
self.FieldDict[targetf]=self.FieldDict[resultf]
self.__Log(f'New value for {targetf} : {self.FieldDict[resultf]}')
i = i + 1
self.__Log(f'\nEnd of ProcesSteps\n\n')
return result
#-----------------------------------------------------------------------------------------------------------------------
# Public functions Helper
#-----------------------------------------------------------------------------------------------------------------------
# Function Dump
#
# Params:
#
# Description :
#
# Return:
#
def Dump(self,topic="all"):
self.__Log("Beginning of Object Dump")
if (topic.lower() == "all" or topic.lower() == "raw"):
print ("")
print ("Raw Records :")
print ("")
if self.bProfileLoaded:
print (f'Tax Profile Raw Records : {yaml.dump(self.RawTaxProfile)}')
if self.bTaxDefLoaded:
print (f'Tax Def Raw Records : {yaml.dump(self.RawTaxDef)}')
if (topic.lower() == "all" or topic.lower() == "var"):
print ("Variables :")
print ("")
if self.bProfileLoaded:
print (f'Profil Variables :')
print (self.VarDict)
if self.bTaxDefLoaded:
print ("")
print (f'Tax Def Global Variables :')
print (self.GVarTaxDefDict)
if (topic.lower() == "all" or topic.lower() == "field"):
if self.bProfileLoaded:
print ("")
print (f'Fields :')
print (self.FieldDict)
if (topic.lower() == "all" or topic.lower() == "step"):
if self.bTaxDefLoaded:
print ("")
print (f'Steps :')
print (self.StepperDict)
if (topic.lower() == "all" or topic.lower() == "report"):
if self.bTaxCalculted:
print ("")
print (f'Report :')
print (self.ReportDict)
if self.bProfileLoaded:
print ("")
print (f'List of Forms : {self.FormList}')
self.__Log("End of Object Dump")
return
# Function CleanUpListInt
#
# Params:
# lst : list to Clean
#
# Description :
#
#
# Return:
# lst : Cleaned List
#
def CleanUpListInt(self,lst):
self.__Log(f'Beginning of CleanUpList for {lst}')
if not isinstance(lst, list):
if isinstance(lst, str):
if lst[:1] == "[":
lst = lst[1:len(lst)-1].split(",")
else:
lst = lst.split(",")
for a in lst:
lst[lst.index(a)] = int(a)
self.__Log(f'End of CleanUpList returning {lst}')
return lst
# Function AllocateDeficit
#
# Params:
# amount : amount to distribute
# amountlist : list of amount available for the distribution
#
# Description :
#
# Return:
# repartlist : List of amount distributed
# newamountlist : list of amount after distribution
# remains : amount remaining if all can't be distributed
#
def AllocateDeficit(self,amount,amountlist):
self.__Log(f'Beginning of AllocateDeficit of {amount} thru {amountlist}')
repartlist = []
newamountlist = []
remains = amount
#Input Sanitization
amount = int(amount)
#Check if the 2nd arg is really a list (direct call) or a string representing a list (call from the yaml)
self.CleanUpListInt(amountlist)
try:
for a in amountlist:
remains = amount - a
if remains <= 0:
newamountlist.append(abs(remains))
repartlist.append(amount)
remains = 0
amount = 0
else:
newamountlist.append(0)
repartlist.append(a)
amount = remains
except Exception as e:
self.__Log(f'Exception in AllocatDeficit',5)
self.__Log(f'Exception : {e.__class__}',5)
self.__Log(f'End of AllocateDeficit returning reparlist = {repartlist}, updated amountlist {newamountlist}, remaining amount {remains}')
return repartlist,newamountlist,remains
# Function SumSectionFields
#
# Params:
# f : Form name
# s : section number
#
# Description :
#
# Return:
# sumf : Sum of fields in the section
#
def SumSectionFields(self,f,s,filter=[]):
self.__Log(f'Beginning of SumSectionFields on section {s}')
sname = f'F{f}S{s}'
locd = self.FieldDict.copy()
ld = []
if CurLoop != "":
for k in locd.keys():
if not k.endswith(CurLoop):
ld.append(k)
for f in filter:
fname = f'{sname}_{f}'
for k in locd.keys():
if k.startswith(fname):
if k not in ld:
ld.append(k)
for e in ld:
del locd[e]
lstf = [locd[k] for k in list(locd.keys()) if sname in k[:len(sname)]]
sumf = sum(lstf)
self.__Log(f'End of SumSectionFields returning Sum of Fields = {sumf}')
return sumf
# Function DisplayComputeLog
#
# Params:
#
# Description : When EnableComputeLog is enable, all Compute instruction are logged in a buffer that can be dump thru this function
# In theory you could replay some calulation made by XTax and get the same result. (Experimental)
#
# Return:
#
def DisplayComputeLog(self,section="all"):
self.__Log("Beginning of DisplayComputeLog")
if self.EnableComputeLog:
for l in self.ComputeLogBuffer:
print (l)
self.__Log("End of DisplayComputeLog")
return
# Function ReportFieldsInSections
#
# Params:
# f : Form number
# s : Section to number (if none s=0 then all section in the forms are processed)
# display : If true (default) the fields and their value are printed
#
# Description :
#
#
# Return:
# fdict : dictionary of fields of the section/s
#
def ReportFieldsInSections(self,f,s=None,display=True):
if s == None:
ends = ""
else:
ends = f' and section {s}'
self.__Log(f'Beginning of ReportFieldsInSections for forms {f}{ends}')
fdict = {}
if s == None:
for i in range(1,12):
fn = f'F{f}S{i}'
flds = self.__GetSectionFields(fn,fdict)
if len(flds) > 0:
self.__Log(f'Section {i} : {flds}',2)
else:
fn = f'F{f}S{s}'
flds = self.__GetSectionFields(fn,fdict)
self.__Log(f'Section {s} : {flds}',2)
self.__Log(f'End of ReportFieldsInSections {fdict}')
return fdict
#-----------------------------------------------------------------------------------------------------------------------
# Public Method/function
#-----------------------------------------------------------------------------------------------------------------------
#
# Function ComputeProgressiveTax
#
# Params: Year
# Taxable Revenu
#
# Description : Use a Range Grid (one per year) to calculate the Taxe
#
# Return: Taxe amount
#
def ComputeProgressiveTax(self, year=datetime.datetime.now().year,taxablerevenue=0,nbpart=1):
self.__Log(f'Beginning of ComputeProgressiveTax for year {year} income of {taxablerevenue} and {nbpart} part')
if self.bTaxDefLoaded == False: self.LoadTaxDef()
if self.bTaxDefLoaded:
FoundRanges = False
Grids = self.RawTaxDef["Tax"]["Grids"]
for g in Grids:
if g["Grid"] == year:
if None != g["IrpropCalc"]:
FoundRanges = True
RL = g["IrpropCalc"]["Ranges"]
if FoundRanges:
TaxeAmount = 0
Rev = taxablerevenue / nbpart
while (Rev > 0):
for i,r in enumerate(RL):
a,b,c = r[f'R{i+1}']