gchr.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import pandas as pd
  2. import numpy as np
  3. import xml.etree.ElementTree as ET
  4. import csv
  5. from xml.dom import minidom
  6. from datetime import datetime
  7. import logging
  8. from pathlib import Path
  9. ACCOUNT_INFO = ['Account', 'Make', 'Site', 'Origin', 'SalesChannel', 'CostCarrier', 'CostAccountingString']
  10. class GCHR:
  11. def __init__(self, project_name) -> None:
  12. self.base_dir = f'/home/robert/projekte/python/gcstruct/{project_name}/'
  13. self.account_translation = self.base_dir + 'Kontenrahmen_uebersetzt.csv'
  14. self.account_bookings = Path(self.base_dir).glob('GuV_Bilanz_Salden*.csv')
  15. self.first_month_of_financial_year = '01'
  16. pd.set_option('display.max_rows', 500)
  17. pd.set_option('display.float_format', lambda x: '%.2f' % x)
  18. def set_bookkeep_period(self, year, month):
  19. self.current_year = year
  20. self.current_month = month
  21. period = f'{year}-{month}'
  22. prot_file = self.base_dir + f'protokoll_{period}.log'
  23. logging.basicConfig(
  24. filename=prot_file,
  25. filemode='w',
  26. encoding='utf-8',
  27. level=logging.DEBUG
  28. )
  29. self.account_ignored = self.base_dir + f'ignoriert_{period}.csv'
  30. self.account_invalid = self.base_dir + f'ungueltig_{period}.csv'
  31. self.last_year = str(int(self.current_year) - 1)
  32. self.last_year2 = str(int(self.current_year) - 2)
  33. self.next_year = str(int(self.current_year) + 1)
  34. def header(self, makes, sites):
  35. return {
  36. 'Country': 'DE',
  37. 'MainBmCode': sites[0]['Standort_HBV'],
  38. 'Month': self.current_month,
  39. 'Year': self.current_year,
  40. 'Currency': 'EUR',
  41. 'NumberOfMakes': len(makes),
  42. 'NumberOfSites': len(sites),
  43. 'ExtractionDate': datetime.now().strftime('%d.%m.%Y'),
  44. 'ExtractionTime': datetime.now().strftime('%H:%M:%S'),
  45. 'BeginFiscalYear': self.first_month_of_financial_year
  46. }
  47. def bookkeep_filter(self):
  48. period = [self.current_year + str(i).zfill(2) for i in range(1, 13)]
  49. if self.first_month_of_financial_year != '01':
  50. if self.first_month_of_financial_year > self.current_month:
  51. period = [self.last_year + str(i).zfill(2) for i in range(1, 13)] + period
  52. else:
  53. period = period + [self.next_year + str(i).zfill(2) for i in range(1, 13)]
  54. fm = int(self.first_month_of_financial_year)
  55. period = period[fm - 1:fm + 12]
  56. rename_to = ['Period' + str(i).zfill(2) for i in range(1, 13)]
  57. return dict(zip(period, rename_to))
  58. def extract_acct_info(self, df: pd.DataFrame):
  59. acct_info = ['Marke', 'Standort', 'Konto_Nr', 'Kostenstelle', 'Absatzkanal', 'Kostenträger']
  60. df['Konto_Nr_SKR51'] = df.index
  61. df[acct_info] = df['Konto_Nr_SKR51'].str.split('-', 6, expand=True)
  62. return df
  63. def export_period(self, year, month):
  64. self.set_bookkeep_period(year, month)
  65. # Übersetzungstabelle laden
  66. df_translate = pd.read_csv(self.account_translation, decimal=',', sep=';', encoding='latin-1',
  67. converters={i: str for i in range(0, 200)})
  68. logging.info(df_translate.shape)
  69. df_translate['duplicated'] = df_translate.duplicated()
  70. logging.info(df_translate[df_translate['duplicated']])
  71. df_translate.drop(columns=['duplicated'], inplace=True)
  72. df_translate.drop_duplicates(inplace=True)
  73. df_translate.set_index('Konto_Nr_Händler')
  74. # Kontensalden laden
  75. df2 = []
  76. for csv_file in self.account_bookings:
  77. df2.append(pd.read_csv(csv_file, decimal=',', sep=';', encoding='latin-1', converters={0: str, 1: str}))
  78. df_bookings = pd.concat(df2)
  79. # Kontensalden auf gegebenen Monat filtern
  80. filter_from = self.current_year + self.first_month_of_financial_year
  81. filter_prev = self.last_year + self.first_month_of_financial_year
  82. if self.first_month_of_financial_year > self.current_month:
  83. filter_from = self.last_year + self.first_month_of_financial_year
  84. filter_prev = self.last_year2 + self.first_month_of_financial_year
  85. filter_to = self.current_year + self.current_month
  86. filter_opening = self.current_year + '00'
  87. filter_prev_opening = self.last_year + '00'
  88. prev_year_closed = True
  89. df_opening_balance = df_bookings[(df_bookings['Bookkeep Period'] == filter_opening)]
  90. if df_opening_balance.shape[0] == 0:
  91. df_opening_balance = df_bookings[(df_bookings['Bookkeep Period'] == filter_prev_opening) |
  92. ((df_bookings['Bookkeep Period'] >= filter_prev) &
  93. (df_bookings['Bookkeep Period'] < filter_from))]
  94. df_opening_balance['Bookkeep Period'] = filter_opening
  95. prev_year_closed = False
  96. # df_opening_balance = df_opening_balance.merge(df_translate, how='inner', on='Konto_Nr_Händler')
  97. df_opening_balance = df_opening_balance[(df_opening_balance['Konto_Nr_Händler'].str.contains(r'-[013]\d\d+-'))]
  98. df_opening_balance['amount'] = (df_opening_balance['Debit Amount'] + df_opening_balance['Credit Amount']).round(2)
  99. # df_opening_balance.drop(columns=['Debit Amount', 'Credit Amount', 'Debit Quantity', 'Credit Quantity'], inplace=True)
  100. # df_opening_balance = df_opening_balance.groupby(['Marke', 'Standort']).sum()
  101. opening_balance = df_opening_balance['amount'].sum().round(2)
  102. logging.info('Gewinn/Verlustvortrag')
  103. logging.info(opening_balance)
  104. if not prev_year_closed:
  105. row = {
  106. 'Konto_Nr_Händler': '01-01-0861-00-00-00',
  107. 'Bookkeep Period': filter_opening,
  108. 'Debit Amount': opening_balance,
  109. 'Credit Amount': 0,
  110. 'Debit Quantity': 0,
  111. 'Credit Quantity': 0,
  112. 'amount': opening_balance
  113. }
  114. df_opening_balance = df_opening_balance.append(row, ignore_index=True)
  115. print(df_opening_balance.tail())
  116. df_bookings = df_bookings[(df_bookings['Bookkeep Period'] >= filter_from) & (df_bookings['Bookkeep Period'] <= filter_to)]
  117. df_bookings['amount'] = (df_bookings['Debit Amount'] + df_bookings['Credit Amount']).round(2)
  118. df_stats = df_bookings.copy()
  119. # df_stats = df_stats[df_stats['Konto_Nr_Händler'].str.match(r'-[24578]\d\d\d-')]
  120. df_stats['Konto_Nr_Händler'] = df_stats['Konto_Nr_Händler'].str.replace(r'-(\d\d\d+)-', r'-\1_STK-', regex=True)
  121. df_stats['amount'] = (df_bookings['Debit Quantity'] + df_bookings['Credit Quantity']).round(2)
  122. df_bookings = pd.concat([df_opening_balance, df_bookings, df_stats])
  123. df_bookings = df_bookings[df_bookings['amount'] != 0.00]
  124. bk_filter = self.bookkeep_filter()
  125. period_no = list(bk_filter.keys()).index(filter_to) + 1
  126. # Spalten konvertieren
  127. df_bookings['period'] = df_bookings['Bookkeep Period'].apply(lambda x: bk_filter[x])
  128. logging.info('df_bookings: ' + str(df_bookings.shape))
  129. # Join auf Übersetzung
  130. df_combined = df_bookings.merge(df_translate, how='inner', on='Konto_Nr_Händler')
  131. logging.info('df_combined: ' + str(df_combined.shape))
  132. # Hack für fehlende Markenzuordnung
  133. df_combined['Fremdmarke'] = (df_combined['Marke_HBV'].str.match(r'^0000'))
  134. df_combined['Marke'] = np.where(df_combined['Fremdmarke'], '99', df_combined['Marke'])
  135. df_combined['Standort_egal'] = (df_combined['Standort_HBV'].str.match(r'^\d\d_'))
  136. df_combined['Standort_HBV'] = np.where(df_combined['Fremdmarke'] | df_combined['Standort_egal'], '0000', df_combined['Standort_HBV'])
  137. makes = df_combined[['Marke', 'Marke_HBV']].drop_duplicates().sort_values(by=['Marke'])
  138. sites = df_combined[['Marke', 'Standort', 'Standort_HBV']].drop_duplicates().sort_values(by=['Marke', 'Standort'])
  139. # df_combined.to_csv(account_invalid, decimal=',', sep=';', encoding='latin-1', index=False)
  140. # Gruppieren
  141. # df_grouped = df_combined.groupby(['Konto_Nr_SKR51', 'period']).sum()
  142. df = df_combined.pivot_table(index=['Konto_Nr_SKR51'], columns=['period'], values='amount',
  143. aggfunc=np.sum, margins=True, margins_name='CumulatedYear')
  144. logging.info('df_pivot: ' + str(df.shape))
  145. df = self.extract_acct_info(df)
  146. # df = df_translate.reset_index(drop=True).drop(columns=['Kostenträger_Ebene']).drop_duplicates()
  147. logging.info(df.shape)
  148. logging.info(df.columns)
  149. logging.info(df.head())
  150. # df = df.merge(df_translate, how='inner', on='Konto_Nr_SKR51')
  151. logging.info('df: ' + str(df.shape))
  152. df['Bilanz'] = (df['Konto_Nr'].str.match(r'^[013]'))
  153. df['Kontoart'] = np.where(df['Bilanz'], '1', '2')
  154. df['Kontoart'] = np.where(df['Konto_Nr'].str.contains('_STK'), '3', df['Kontoart'])
  155. df['Kontoart'] = np.where(df['Konto_Nr'].str.match(r'^[9]'), '3', df['Kontoart'])
  156. df['Konto_1'] = (df['Konto_Nr'].str.slice(0, 1))
  157. df_debug = df.drop(columns=['Bilanz'])
  158. logging.info(df_debug.groupby(['Kontoart']).sum())
  159. logging.info(df_debug.groupby(['Kontoart', 'Konto_1']).sum())
  160. logging.info(df_debug.groupby(['Konto_Nr']).sum())
  161. df_debug.groupby(['Konto_Nr']).sum().to_csv(self.base_dir + 'debug.csv', decimal=',', sep=';', encoding='latin-1')
  162. # Bereinigung GW-Kostenträger
  163. df['GW_Verkauf_1'] = (df['Konto_Nr'].str.match(r'^[78]0')) & (df['Kostenstelle'].str.match(r'^[^1]\d'))
  164. df['Kostenstelle'] = np.where(df['GW_Verkauf_1'] == True, '11', df['Kostenstelle'])
  165. df['GW_Verkauf_2'] = (df['Konto_Nr'].str.match(r'^[78]1')) & (df['Kostenstelle'].str.match(r'^[^2]\d'))
  166. df['Kostenstelle'] = np.where(df['GW_Verkauf_2'] == True, '21', df['Kostenstelle'])
  167. df['GW_Verkauf_3'] = (df['Konto_Nr'].str.match(r'^[78]3')) & (df['Kostenstelle'].str.match(r'^[^3]\d'))
  168. df['Kostenstelle'] = np.where(df['GW_Verkauf_3'] == True, '31', df['Kostenstelle'])
  169. df['GW_Verkauf_4'] = (df['Konto_Nr'].str.match(r'^[78]4')) & (df['Kostenstelle'].str.match(r'^[^4]\d'))
  170. df['Kostenstelle'] = np.where(df['GW_Verkauf_4'] == True, '41', df['Kostenstelle'])
  171. df['GW_Verkauf_5'] = (df['Konto_Nr'].str.match(r'^[78]5')) & (df['Kostenstelle'].str.match(r'^[^5]\d'))
  172. df['Kostenstelle'] = np.where(df['GW_Verkauf_5'] == True, '51', df['Kostenstelle'])
  173. df['GW_Verkauf_50'] = (df['Konto_Nr'].str.match(r'^[78]')) & (df['Kostenstelle'].str.match(r'^2'))
  174. df['Kostenträger'] = np.where(df['GW_Verkauf_50'] == True, '52', df['Kostenträger'])
  175. df['Kostenträger'] = np.where((df['GW_Verkauf_50'] == True) & (df['Marke'] == '01'), '50', df['Kostenträger'])
  176. df['GW_Stk_50'] = (df['Konto_Nr'].str.match(r'^9130')) & (df['Kostenstelle'].str.match(r'^2'))
  177. df['Kostenträger'] = np.where(df['GW_Stk_50'] == True, '52', df['Kostenträger'])
  178. df['Kostenträger'] = np.where((df['GW_Stk_50'] == True) & (df['Marke'] == '01'), '50', df['Kostenträger'])
  179. df['Kostenträger'] = np.where(df['Bilanz'] == True, '00', df['Kostenträger'])
  180. df['Konto_5er'] = (df['Konto_Nr'].str.match('^5')) | (df['Konto_Nr'].str.match('^9143'))
  181. df['Absatzkanal'] = np.where(df['Konto_5er'] == True, '99', df['Absatzkanal'])
  182. df['Teile_30_60'] = (df['Konto_Nr'].str.match(r'^[578]')) & \
  183. (df['Kostenstelle'].str.match(r'^[3]')) & \
  184. (df['Kostenträger'].str.match(r'^[^6]'))
  185. df['Kostenträger'] = np.where(df['Teile_30_60'] == True, '60', df['Kostenträger'])
  186. df['Service_40_70'] = (df['Konto_Nr'].str.match(r'^[578]')) & \
  187. (df['Kostenstelle'].str.match(r'^[4]')) & \
  188. (df['Kostenträger'].str.match(r'^[^7]'))
  189. df['Kostenträger'] = np.where(df['Service_40_70'] == True, '70', df['Kostenträger'])
  190. from_label = ['Marke', 'Standort', 'Konto_Nr', 'Kostenstelle', 'Absatzkanal', 'Kostenträger']
  191. to_label = ['Make', 'Site', 'Account', 'Origin', 'SalesChannel', 'CostCarrier']
  192. df = df.rename(columns=dict(zip(from_label, to_label)))
  193. makes = makes.rename(columns=dict(zip(from_label, to_label))).to_dict(orient='records')
  194. sites = sites.rename(columns=dict(zip(from_label, to_label))).to_dict(orient='records')
  195. df['CostAccountingString'] = df['Make'] + df['Site'] + df['Origin'] + \
  196. df['SalesChannel'] + df['CostCarrier']
  197. df['IsNumeric'] = (df['CostAccountingString'].str.isdigit()) & (df['Account'].str.isdigit()) & (df['Account'].str.len() == 4)
  198. df_invalid = df[df['IsNumeric'] == False]
  199. df_invalid.to_csv(self.account_invalid + '.2.csv', decimal=',', sep=';', encoding='latin-1', index=False)
  200. export_csv = self.base_dir + 'export_' + self.current_year + '-' + self.current_month + '.csv'
  201. xmlfile = export_csv[:-4] + '.xml'
  202. df.to_csv(export_csv, decimal=',', sep=';', encoding='latin-1', index=False)
  203. df = df[df['IsNumeric'] != False].groupby(ACCOUNT_INFO, as_index=False).sum()
  204. # Infos ergänzen
  205. df['Decimals'] = 2
  206. df['OpeningBalance'] = 0.0
  207. logging.info(df.shape)
  208. export_file = self.export_xml(df.to_dict(orient='records'), bk_filter, period_no, makes, sites, xmlfile)
  209. # Join auf Übersetzung - nicht zugeordnet
  210. df_ignored = df_bookings.merge(df_translate, how='left', on='Konto_Nr_Händler')
  211. df_ignored = df_ignored[df_ignored['Konto_Nr_SKR51'].isna()] # [['Konto_Nr_Händler', 'Bookkeep Period', 'amount', 'quantity']]
  212. if not df_ignored.empty:
  213. df_ignored = df_ignored.pivot_table(index=['Konto_Nr_Händler'], columns=['period'], values='amount',
  214. aggfunc=np.sum, margins=True, margins_name='CumulatedYear')
  215. df_ignored.to_csv(self.account_ignored, decimal=',', sep=';', encoding='latin-1')
  216. return export_file
  217. def export_xml(self, records, bk_filter, period_no, makes, sites, export_file):
  218. record_elements = ACCOUNT_INFO + ['Decimals', 'OpeningBalance'] + \
  219. list(bk_filter.values())[:period_no] + ['CumulatedYear']
  220. root = ET.Element('HbvData')
  221. h = ET.SubElement(root, 'Header')
  222. for k, v in self.header(makes, sites).items():
  223. ET.SubElement(h, k).text = str(v)
  224. make_list = ET.SubElement(root, 'MakeList')
  225. for m in makes:
  226. e = ET.SubElement(make_list, 'MakeListEntry')
  227. ET.SubElement(e, 'Make').text = m['Make']
  228. ET.SubElement(e, 'MakeCode').text = m['Marke_HBV']
  229. bm_code_list = ET.SubElement(root, 'BmCodeList')
  230. for s in sites:
  231. e = ET.SubElement(bm_code_list, 'BmCodeEntry')
  232. ET.SubElement(e, 'Make').text = s['Make']
  233. ET.SubElement(e, 'Site').text = s['Site']
  234. ET.SubElement(e, 'BmCode').text = s['Standort_HBV']
  235. record_list = ET.SubElement(root, 'RecordList')
  236. for row in records:
  237. record = ET.SubElement(record_list, 'Record')
  238. for e in record_elements:
  239. child = ET.SubElement(record, e)
  240. field = row.get(e, 0.0)
  241. if str(field) == 'nan':
  242. field = '0'
  243. elif type(field) is float:
  244. field = '{:.0f}'.format(field * 100)
  245. child.text = str(field)
  246. with open(export_file, 'w', encoding='utf-8') as fwh:
  247. fwh.write(minidom.parseString(ET.tostring(root)).toprettyxml(indent=' '))
  248. # with open(export_file, 'wb') as fwh:
  249. # fwh.write(ET.tostring(root))
  250. return export_file
  251. def convert_to_row(self, node):
  252. return [child.text for child in node]
  253. def convert_xml_to_csv(self, xmlfile, csvfile):
  254. record_list = ET.parse(xmlfile).getroot().find('RecordList')
  255. header = [child.tag for child in record_list.find('Record')]
  256. bookings = [self.convert_to_row(node) for node in record_list.findall('Record')]
  257. with open(csvfile, 'w') as fwh:
  258. cwh = csv.writer(fwh, delimiter=';')
  259. cwh.writerow(header)
  260. cwh.writerows(bookings)
  261. return True
  262. def convert_csv_to_xml(self, csvfile, xmlfile):
  263. makes = [{'Make': '01', 'Marke_HBV': '1844'}]
  264. sites = [{'Make': '01', 'Site': '01', 'Marke_HBV': '1844'}]
  265. with open(csvfile, 'r', encoding='latin-1') as frh:
  266. csv_reader = csv.DictReader(frh, delimiter=';')
  267. self.export_xml(csv_reader, self.bookkeep_filter(), 1, makes, sites, xmlfile)
  268. if __name__ == '__main__':
  269. # gchr = GCHR('Koenig')
  270. gchr = GCHR('Luchtenberg')
  271. export_file = gchr.export_period('2022', '02')
  272. # convert_xml_to_csv(export_file, export_file[:-4] + '.csv')
  273. # convert_xml_to_csv('DE2119_2105_150621_080944.xml', 'DE2119_2105_150621_080944.csv')
  274. # convert_csv_to_xml(base_dir + '../SKR51/maximum.csv', base_dir + '../maximum_2022-01.xml')