anafapi.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. '''Created Dec 3, 2021 Levi'''
  2. import os
  3. import platform
  4. import subprocess as sp
  5. import time
  6. from json import JSONDecodeError
  7. from urllib.parse import urljoin
  8. import requests
  9. import xlsxwriter as xlsw
  10. from .writer import Writer
  11. def insert_keys(dict_, obj, pos):
  12. return {k: v for k, v in (list(dict_.items())[:pos] + list(obj.items()) + list(dict_.items())[pos:])}
  13. class anafAPI(object):
  14. '''classdocs
  15. '''
  16. BASEURL = 'https://webservicesp.anaf.ro/'
  17. VATURL = 'PlatitorTvaRest/api/v6/ws/tva'
  18. REPURL = 'bilant?an={}&cui={}'
  19. CULTURL = 'RegCult/api/v2/ws/cult'
  20. AGRURL = 'RegAgric/api/v2/ws/agric'
  21. def __init__(self):
  22. '''Constructor
  23. '''
  24. self.session = requests.Session()
  25. def parse_list(self, file_name=None, list_=None, excl_=[], ):
  26. if file_name:
  27. with open(file_name, 'r') as fiscal_codes, open("lista_cf_new.txt", "w") as fileout:
  28. for code in fiscal_codes:
  29. if code[0:2] != 'HU' and code[0:2] != 'DE' and code[0:2] != 'GB' and code[0:2] != 'EL' and code[0:2] != 'LT' and 'SK' and code not in excl_:
  30. fileout.write(code)
  31. with open("lista_cf_new.txt", "r") as newfile:
  32. self.lista_cf_ro = ' '.join(newfile).replace(',', '').split()
  33. if list_:
  34. lista_cf_ro = list_
  35. print('items in list', len(lista_cf_ro))
  36. return self.lista_cf_ro
  37. def get_vat(self, cui):
  38. url = urljoin(self.BASEURL, self.VATURL)
  39. payload = [{"cui": cui.replace('RO', ''), "data": time.strftime('%Y-%m-%d')}]
  40. result = self.session.post(url, json=payload, headers={'Content-Type': 'application/json'})
  41. try:
  42. resp_dict = result.json()['found'][0]
  43. random_keys = ['telefon', 'fax', 'codPostal', 'act', 'stare_inregistrare']
  44. pos = 5
  45. for random_key in random_keys:
  46. if random_key not in resp_dict.keys():
  47. resp_dict = insert_keys(resp_dict, {random_key: 'Nan'}, pos)
  48. pos += 1
  49. new_dict = {resp_dict['cui']: self._dict_to_list(resp_dict, 0)}
  50. except (KeyError, JSONDecodeError):
  51. pass
  52. time.sleep(1.1)
  53. return new_dict, resp_dict
  54. def get_cult(self, cui):
  55. url = urljoin(self.BASEURL, self.CULTURL)
  56. payload = [{"cui": cui.replace('RO', ''), "data": time.strftime('%Y-%m-%d')}]
  57. result = self.session.post(url, json=payload)
  58. try:
  59. resp_dict = result.json()['found'][0]
  60. new_dict = {resp_dict['cui']: self._dict_to_list(resp_dict, 0)}
  61. except (KeyError, JSONDecodeError):
  62. pass
  63. time.sleep(1.1)
  64. return new_dict, resp_dict
  65. def get_rep(self, cui, year):
  66. url = urljoin(self.BASEURL, self.REPURL.format(year, cui))
  67. result = self.session.get(url)
  68. resp_dict = result.json()
  69. # print(resp_dict)
  70. vals = [resp_dict[val] for val in resp_dict if val != 'i']
  71. indicators = resp_dict['i']
  72. for adict in indicators:
  73. # print(adict['indicator'])
  74. adict['indicator'] = int(adict['indicator'].replace('I', ''))
  75. # print(adict['indicator'])
  76. indicators = sorted(indicators, key=lambda d: d['indicator'])
  77. vals2 = [val["val_indicator"] for val in indicators]
  78. headers = [key for key in resp_dict if key != 'i']
  79. headers2 = ['{}-{}'.format(val['indicator'], val["val_den_indicator"]) for val in indicators]
  80. headers.extend(headers2)
  81. vals.extend(vals2)
  82. time.sleep(1.1)
  83. return headers, vals
  84. def to_excel(self, type_, cui=None, func=None, year=None, range_=None):
  85. types = {
  86. 'to_rep': Writer(f'{type_}.xlsx').to_rep,
  87. 'to_vat': Writer(f'{type_}.xlsx').to_vat,
  88. 'to_cult': Writer(f'{type_}.xlsx').to_cult
  89. }
  90. types[type_](cui, func, year, range_)
  91. self.type_ = type_
  92. # if type_ == 'to_rep':
  93. # Writer(f'{type_}.xlsx').to_rep(cui, func, year, range_)
  94. # elif type_ == 'to_vat':
  95. # Writer(f'{type_}.xlsx').to_vat(cui, func)
  96. def open(self, file_name=None):
  97. file_name = file_name or f'{self.type_}.xlsx'
  98. abs_path = os.path.abspath(file_name)
  99. if platform.system() == 'Windows':
  100. sp.run(f'start {abs_path}', shell=True)
  101. elif platform.system() == 'Linux':
  102. sp.run(['xdg-open', f'{abs_path}'])
  103. else:
  104. raise NotImplementedError
  105. def _dict_to_list(self, s_dict, from_ind=None):
  106. if from_ind is None: n_list = [s_dict[i] for i in s_dict]
  107. else:
  108. n_list = [s_dict[i] for i in s_dict]
  109. n_list.pop(from_ind)
  110. return n_list