test_anafoauth.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. '''Created 6 Jul 2022 Levi'''
  2. # coding: UTF-8
  3. import platform
  4. import unittest
  5. import os
  6. from datetime import datetime
  7. import ujson
  8. from lxml import etree
  9. from lxml.etree import LxmlSyntaxError
  10. from anafapi.anafoauth import Anafoauth, Efactoauth
  11. from anafapi import utils
  12. from anafapi.en16931 import Invoice
  13. if platform.system() == 'Linux':
  14. token_file_path = '/home/deeejas/git/anafapi/anafapi/{}'
  15. elif platform.system() == 'Windows':
  16. token_file_path = os.path.join(os.path.expanduser('~'), 'git/anafapi/anafapi/{}')
  17. class oauthTest(unittest.TestCase):
  18. anoauth = Anafoauth(
  19. # client_id='16cbef8754bef0bcf015529353427e8a7e3ee71d56879565',
  20. # client_secret='c6aa66d89002f36461f93facd990e6bf5bc706e1df897e8a7e3ee71d56879565',
  21. client_id='312afcb54fae740eaa721aa7364b7e8a7e3ee71d52220c66',
  22. client_secret='3eba7d34e1c516403033bcdf22619ab1942bec0bb0ef7e8a7e3ee71d52220c66',
  23. # redirect_uri='https://www.anaf.ro/oauth2callback',
  24. redirect_uri='https://oauth.pstmn.io/v1/browser-callback',
  25. )
  26. def test_is_valid(self):
  27. self.anoauth.load_token_file(token_file_path.format('efact.json'))
  28. # print(self.anoauth.to)
  29. print(self.anoauth.is_valid)
  30. def test_jwt_props(self):
  31. print(datetime.fromtimestamp(self.anoauth.jwt_props('../anafapi/efact_jwt.json')['exp']).strftime('%d-%m-%Y %H:%M:%S'))
  32. def test_browser_redirect(self):
  33. print(self.anoauth._browser_redirect())
  34. def test_get_token(self):
  35. self.anoauth.get_token()
  36. self.anoauth.save_token(token_file_path.format('efact.json'))
  37. def test_get_jwt_token(self):
  38. # self.anoauth.get_jwt_token()
  39. self.anoauth.get_jwt_token_requests()
  40. # self.anoauth.save_jwt_token(token_file_path.format('efact_jwt.json'))
  41. def test_revive_token(self):
  42. self.anoauth.load_token_file(token_file_path.format('efact.json'))
  43. self.anoauth.revive_token()
  44. self.anoauth.save_token(token_file_path.format('efact_refreshed.json'))
  45. class efactTest(unittest.TestCase):
  46. efactoauth = Efactoauth(
  47. # client_id='16cbef8754bef0bcf015529353427e8a7e3ee71d56879565',
  48. # client_secret='c6aa66d89002f36461f93facd990e6bf5bc706e1df897e8a7e3ee71d56879565',
  49. client_id='312afcb54fae740eaa721aa7364b7e8a7e3ee71d52220c66',
  50. client_secret='3eba7d34e1c516403033bcdf22619ab1942bec0bb0ef7e8a7e3ee71d52220c66',
  51. # redirect_uri='https://www.anaf.ro/oauth2callback',
  52. redirect_uri='https://oauth.pstmn.io/v1/browser-callback'
  53. )
  54. efactoauth.load_token_file(token_file_path.format('efact_jwt.json'))
  55. efactoauth.load_session()
  56. def test_to_erp(self):
  57. # self.efactoauth.getxml_from_zip(path='../efact/3016038776.zip', dest_f='')
  58. # latest = self.efactoauth.get_latest_invoice('efact')
  59. inv_files = utils.get_not_booked('17259191')
  60. # inv_files = [r'C:\Users\Levi\git\anafapi\tests\17259191\FACTURA PRIMITA\2024_05\23\16702141\4290867417.xml',
  61. #
  62. # ]
  63. for latest in inv_files:
  64. if 'booked' not in latest:
  65. inv = self.efactoauth.parse_inv(invoice=latest)
  66. print(inv.seller_party.name, inv.invoice_id, inv.issue_date.date())
  67. # for line in inv.lines:
  68. # print(line.tax)
  69. self.efactoauth.addinvoice_tonextup(invoice=inv,
  70. kind='stock',
  71. template=32,
  72. exp_plan=363,
  73. warehouse_code=23,
  74. generic=True,
  75. generic_value='2209',
  76. send=True)
  77. os.rename(latest, latest.replace('.xml'.lower(), '_booked.xml'))
  78. # os.remove(latest)
  79. def test_validate_invoice(self):
  80. # print(os.listdir('c:/Users/DECEL/FACT1/MZK/2023.01.03/'))
  81. for root, _dir, files in os.walk(r'c:\Users\levi\FACT1\MZK\2024_05_22'):
  82. for file in files:
  83. # print(file)
  84. self.efactoauth.validate_invoice(os.path.join(root, file))
  85. # self.efactoauth.validate_invoice('c:/Users/levi/FACT1/MZK/2024_01_23/MZK241157.xml')
  86. def test_add_invoice(self):
  87. # self.efactoauth.validate_invoice('C:/Users/DECEL/FACT1/MZK/2023_06/MZK2321602.xml', env='prod')
  88. self.efactoauth.add_invoice('17259191', r'C:/Users/DECEL/FACT1/MZK/2023_06/MZK2321602.xml', env='prod')
  89. def test_bulk_add_invoice(self):
  90. for root, _, files in os.walk(r'f:/DECEL/EFACT/KINVEST/2024_01/'):
  91. for file in files:
  92. if file.endswith('.xml'):
  93. inv_file = os.path.join(root, file)
  94. self.efactoauth.add_invoice('31434328', inv_file, env='prod')
  95. def test_transform_to_pdf(self):
  96. self.efactoauth.transform_to_pdf(r'c:/Users/DECEL/FACT1/MZK/2023_01_03/MZK2414.xml')
  97. def test_bulk_transform(self):
  98. for root, _, files in os.walk(r'c:\Users\levi\git\anafapi\tests\17259191\FACTURA PRIMITA\2024_03\20\40628013'):
  99. for file in files:
  100. if file.endswith('.xml'):
  101. inv_file = os.path.join(root, file)
  102. self.efactoauth.transform_to_pdf(inv_file, no_validation=True)
  103. def test_get_all_messages(self, vat_id, days, root_path, env, filter_, extract):
  104. self.efactoauth.get_all_messages(vat_id, days=days, env=env, root_path=root_path, filter_=filter_, extract=extract)
  105. def test_pretty_messages(self):
  106. self.efactoauth.pretty_messages('17259191', env='prod')
  107. def test_download_invoice(self):
  108. self.efactoauth.download_invoice('3105899770', path=r'C:/Users/DECEL/FACT1/MZK/2023_06', env='prod')
  109. def test_getxml(self):
  110. files = [file for file in os.listdir(r'C:\Users\Levi\git\anafapi\tests\17259191\FACTURA PRIMITA\2024_05\24\9845734') if '.zip' in file]
  111. # print(files)
  112. for file in files:
  113. self.efactoauth.getxml_from_zip(path=os.path.join(r'C:\Users\Levi\git\anafapi\tests\17259191\FACTURA PRIMITA\2024_05\24\9845734', file), dest_f=r'C:\Users\Levi\git\anafapi\tests\17259191\FACTURA PRIMITA\2024_05\24\9845734')
  114. def test_partner_code(self):
  115. with open(r'C:/Users/Levi/git/ciel_rest_api/parts.json') as partner_file:
  116. partners = ujson.load(partner_file)
  117. invoice = Invoice.from_xml(r'C:\Users\Levi\git\anafapi\tests\17259191\FACTURA PRIMITA\2024_04\08\16702141\4238612905_booked.xml')
  118. tax_code = invoice.seller_party.tax_scheme_id.replace('ro'.upper(), '')
  119. for partner in partners:
  120. if tax_code == partner['TaxCode']:
  121. print(partner['Code'], partner['Name'])
  122. break
  123. def test_verify_invoice(self):
  124. self.efactoauth.verify_invoice('4075641152', env='prod')
  125. def test_isvalid(self):
  126. self.efactoauth.load_token_file(token_file_path.format(r'efact.json'))
  127. print(self.efactoauth.is_valid)
  128. def test_get_latest_invoice(self):
  129. latest = self.efactoauth.get_latest_invoice('efact')
  130. print(latest)
  131. # os.replace(latest, latest.replace('.xml'.lower(), '_booked.xml'))
  132. def test_rename_all(self, dir_path, kind: str): # @UndefinedVariable
  133. if kind == 'seller':
  134. account = 'AccountingCustomerParty'
  135. # print(os.path.basename(dir_path))
  136. # dir_path = os.path.join(dir_path, os.path.basename(dir_path))
  137. else:
  138. account = 'AccountingSupplierParty'
  139. # next_subfolder = next(os.walk(dir_path))[1][0]
  140. for root_f, _dirs, files in os.walk(dir_path):
  141. for file in files:
  142. # print(root_f.split('/'))
  143. # print(os.path.basename(dir_path))
  144. # print(root_f, file)
  145. if file.endswith('.xml') and file.count('_') < 2 and 'cif error' not in root_f:
  146. # print(os.path.join(root_f, file))
  147. try:
  148. tree = etree.parse(os.path.join(root_f, file))
  149. root = tree.getroot()
  150. inv_id = root.xpath('//cbc:ID', namespaces={'cbc': 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2'})
  151. inv_id = inv_id[0].text # noqa
  152. parties = root.xpath('//cbc:RegistrationName', namespaces={'cbc': 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2'})
  153. for partie in parties: # noqa
  154. parent_p_type = partie.getparent().getparent().getparent() # noqa
  155. if etree.QName(parent_p_type).localname == account: # @UndefinedVariable
  156. # print(partie.text)
  157. file_partie = partie.text # noqa
  158. is_date = root.xpath('//cbc:IssueDate', namespaces={'cbc': 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2'})
  159. is_date = is_date[0].text # noqa
  160. partie_ids = root.xpath('//cbc:CompanyID', namespaces={'cbc': 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2'})
  161. for partie_id in partie_ids: # noqa
  162. parent_p_type = partie_id.getparent().getparent().getparent() # noqa
  163. parent_t_type = partie_id.getparent() # noqa
  164. # print(parent_t_type)
  165. if etree.QName(parent_t_type).localname == 'PartyTaxScheme' and etree.QName(parent_p_type).localname == account: # @UndefinedVariable
  166. # print(partie_id.text)
  167. file_partn_id = partie_id.text # noqa
  168. new_name = '{}_{}_{}_{}.xml'.format(file.replace('.xml', ''), inv_id, file_partie, is_date)
  169. current_path = os.path.join(root_f, file)
  170. new_path = os.path.join(root_f, new_name)
  171. #
  172. # !This will rename all files
  173. #
  174. os.rename(current_path, new_path)
  175. print(new_name)
  176. except LxmlSyntaxError as exc_:
  177. print(f'{root_f}/{file} not valid')
  178. print(str(exc_))
  179. else:
  180. print('Nothing to rename')
  181. def test_parse_inv(self):
  182. # inv = self.efactoauth.parse_inv('C:/Users/Levi/git/anafapi/tests/17259191/8262600/FACTURA PRIMITA/01_2024/31/4154212674_booked.xml')
  183. # print(self.efactoauth._get_series(inv.invoice_id))
  184. inv_files = utils.get_not_booked('17259191')
  185. print(inv_files)
  186. if __name__ == "__main__":
  187. # unittest.main()
  188. # efactTest().test_add_invoice()
  189. efactTest().test_get_all_messages('17259191', 2, '17259191', 'prod', 'P', True)
  190. # efactTest().test_rename_all(os.path.join(os.path.expanduser('~'), 'git/anafapi/tests/17259191/FACTURA TRIMISA'), kind='seller')
  191. # efactTest().test_rename_all(os.path.join(os.path.expanduser('~'), 'git/anafapi/tests/17259191/FACTURA PRIMITA'), kind='buyer')
  192. # anoauth.get_token()