gcstruct.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. import pandas as pd
  2. import xml.etree.ElementTree as ET
  3. import json
  4. import re
  5. from bs4 import BeautifulSoup
  6. from functools import reduce
  7. reisacher = True
  8. reisacher_remote = True
  9. config = {
  10. 'path': "c:/projekte/python/gcstruct",
  11. 'path2': "c:/projekte/python/gcstruct",
  12. 'output': "gcstruct.json",
  13. 'default': ["SKR51", "Herkunft_KST", "Absatzkanal", "Kostentraeger", "Marke", "Standort", "Manuelle_Konten"],
  14. 'special': {
  15. 'Planner': ["Kostenstelle", "Ebene1", "Ebene2"],
  16. 'Test': ["Ebene1", "Ebene2"]
  17. }
  18. }
  19. if reisacher:
  20. config = {
  21. 'path': "c:/projekte/python/gcstruct_reisacher_planung",
  22. 'path2': "c:/projekte/python/gcstruct_reisacher_planung",
  23. 'output': "gcstruct_reisacher.json",
  24. 'default': ["Struktur_FB", "Struktur_TEK", "Struktur_GuV", "Struktur_Bilanz", "Struktur_HBV", "Bruttoertrag"],
  25. 'special': {
  26. 'Planner': ["Kostenstelle", "Ebene1", "Ebene2"],
  27. 'Test': ["Ebene1", "Ebene2"]
  28. }
  29. }
  30. if reisacher_remote:
  31. config = {
  32. 'path': "X:/Robert/Planung Reisacher/GCStruct_neue_Struktur_Planung",
  33. 'path2': "C:/Projekte/Angular/gc-form/src/assets/data",
  34. 'output': "gcstruct_reisacher.json",
  35. 'default': ["Struktur_FB", "Struktur_TEK", "Struktur_GuV", "Struktur_Bilanz", "Struktur_HBV", "Bruttoertrag"],
  36. 'special': {
  37. 'Planner': ["Kostenstelle", "Ebene1", "Ebene2"],
  38. 'Test': ["Ebene1", "Ebene2"]
  39. }
  40. }
  41. columns = ["Konto_Nr", "Konto_Bezeichnung", "Konto_Art", "Kostenstelle", "STK", "Konto_1", "Konto_2", "Konto_3", "Konto_4", "Konto_5"]
  42. json_result = {"accounts": {}, "tree": {}, "flat": {}}
  43. def get_tree_root(node, structure):
  44. id = ";" * 9
  45. return {
  46. "id": id,
  47. "text": node.attrib['Name'],
  48. "children": get_tree(node, [], structure),
  49. "parents": [],
  50. "accounts": [],
  51. "level": 0,
  52. "form": ''
  53. }
  54. def get_tree(node, parents, structure):
  55. result = []
  56. for child in node:
  57. p = get_parents_list(parents)
  58. parents.append(child.attrib['Name'])
  59. id = ";".join(parents) + ";" * (10 - len(parents))
  60. result.append({
  61. "id": id,
  62. "text": child.attrib['Name'],
  63. "children": get_tree(child, parents, structure),
  64. "parents": p,
  65. "accounts": get_accounts(structure, id),
  66. "level": len(parents),
  67. "form": child.attrib.get('Split', '')
  68. })
  69. parents.pop()
  70. return result
  71. def get_flat(node):
  72. result = [{
  73. "id": node['id'],
  74. "text": node['text'],
  75. "children": [x['id'] for x in node['children']],
  76. "children2": [],
  77. "parents": node['parents'],
  78. "accounts": node['accounts'],
  79. "costcenter": "",
  80. "level": node['level'],
  81. "drilldown": node['level'] < 2, # (node['level'] != 2 and len(node['accounts']) == 0),
  82. "form": node['form'],
  83. "accountlevel": False,
  84. "absolute": True,
  85. "seasonal": True,
  86. "status": "0",
  87. "values": [],
  88. "values2": {}
  89. }]
  90. for child in node['children']:
  91. result += get_flat(child)
  92. return result
  93. def get_accounts(structure, id):
  94. return [x['Konto_Nr'] for x in json_result['accounts'] if x[structure] == id]
  95. def get_parents_list(p_list):
  96. id = ";".join(p_list) + ";" * (10 - len(p_list))
  97. if len(p_list) > 0:
  98. return [id] + get_parents_list(p_list[:-1])
  99. return [";" * 9]
  100. def structure_from_tree(node):
  101. result = []
  102. result.append(node['id'])
  103. for child in node['children']:
  104. result.extend(structure_from_tree(child))
  105. return result
  106. def xml_from_tree(xml_node, tree_node):
  107. for child in tree_node['children']:
  108. element = ET.SubElement(xml_node, "Ebene")
  109. element.set("Name", child['text'])
  110. xml_from_tree(element, child)
  111. def split_it(text, index):
  112. try:
  113. return re.findall(r"([^;]+) - ([^;]*);;", text)[0][index]
  114. except Exception:
  115. return ""
  116. def get_default_cols(i):
  117. return ["Ebene" + str(i) for i in range(i * 10 + 1, (i + 1) * 10 + 1)]
  118. def get_structure_and_tree(struct):
  119. df = pd.read_csv(f"{config['path']}/Kontenrahmen/Kontenrahmen.csv", sep=";", encoding="ansi", decimal=",", converters={i: str for i in range(0, 200)}) # , index_col="Konto_Nr")
  120. for i, (s, cols) in enumerate(struct.items()):
  121. df[s] = reduce(lambda x, y: x + ";" + df[y], cols, "")
  122. df[s] = df[s].apply(lambda x: x[1:])
  123. df['LetzteEbene' + str(i + 1) + '_Nr'] = df[s].apply(lambda x: split_it(x, 0))
  124. df['LetzteEbene' + str(i + 1) + '_Bez'] = df[s].apply(lambda x: split_it(x, 1))
  125. len_items = len(struct)
  126. df = df[columns + [*struct] + ['LetzteEbene' + str(i + 1) + '_Nr' for i in range(len_items)] + ['LetzteEbene' + str(i + 1) + '_Bez' for i in range(len_items)]]
  127. json_result["accounts"] = df.to_dict("records")
  128. # df2 = pd.read_csv("config['path'] + "/Strukturen/Kontenrahmen.csv/SKR51.csv", sep=";", encoding="ansi", decimal=",", converters={i: str for i in range(0, 200)})
  129. # print(df2.head())
  130. for i, (s, cols) in enumerate(struct.items()):
  131. try:
  132. tree = ET.parse(f"{config['path']}/Xml/{s}.xml")
  133. json_result["tree"][s] = get_tree_root(tree.getroot(), s)
  134. except FileNotFoundError:
  135. print("XML-Datei fehlt")
  136. used_entries = [x.split(";")[1:] for x in set(df[s].to_numpy())]
  137. print(used_entries)
  138. root = ET.Element("Ebene")
  139. root.set("Name", s)
  140. json_result["tree"][s] = get_tree_root(root, s)
  141. # json_result["tree"][s] = get_tree_from_accounts(cols, [])
  142. json_result["flat"][s] = get_flat(json_result["tree"][s])
  143. json.dump(json_result, open(f"{config['path2']}/{config['output']}", "w"), indent=2)
  144. def post_structure_and_tree():
  145. json_post = json.load(open(f"{config['path']}/{config['output']}", "r"))
  146. # Kontenrahmen.csv
  147. ebenen = ["Ebene" + str(i) for i in range(1, len(config['default']) * 10 + 1)]
  148. header = ";".join(columns + ebenen)
  149. cols = columns + config['default']
  150. with open(config['path'] + "/Kontenrahmen/Kontenrahmen_out.csv", "w", encoding="ansi") as f:
  151. f.write(header + "\n")
  152. for row in json_post['Kontenrahmen']:
  153. f.write(";".join([row[e] for e in cols]) + "\n")
  154. # print(header)
  155. # xml und evtl. Struktur.csv
  156. for i, s in enumerate(config['default']):
  157. with open(config['path'] + "/Strukturen/Kontenrahmen.csv/" + s + "_out.csv", "w", encoding="ansi") as f:
  158. f.write(";".join(["Ebene" + str(i * 10 + j) for j in range(1, 11)]) + "\n")
  159. rows = structure_from_tree({"id": ";" * 9, "children": json_post[s]})
  160. f.write("\n".join(rows))
  161. # with open(config['path'] + "/Strukturen/Kontenrahmen.csv/" + structure + "_2.csv", "w", encoding="ansi") as f:
  162. root = ET.Element("Ebene")
  163. root.set("Name", s)
  164. xml_from_tree(root, {"id": ";" * 9, "children": json_post[s]})
  165. with open(config['path'] + "/Xml/" + s + "_out.xml", "w", encoding="utf-8") as f:
  166. f.write(BeautifulSoup(ET.tostring(root), "xml").prettify())
  167. if __name__ == '__main__':
  168. struct = dict([(x, get_default_cols(i)) for (i, x) in enumerate(config['default'])])
  169. struct.update(config['special'])
  170. get_structure_and_tree(struct)
  171. # post_structure_and_tree()