gchr.py 15 KB

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