c11_export.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. from pathlib import Path
  2. from cognos11.c11_api import c11_api
  3. import config
  4. import json
  5. import logging
  6. import os
  7. from datetime import datetime
  8. class c11_export:
  9. api: c11_api
  10. cfg: config.Config = None
  11. def __init__(self, cfg=None, api=None):
  12. self.cfg = cfg
  13. if cfg is None:
  14. self.cfg = config.Config()
  15. self.api = api
  16. if api is None:
  17. self.api = c11_api(cfg).login()
  18. now = datetime.now().strftime("%Y%m%d_%H%M%S")
  19. prot_file = f"{self.cfg.cognos11.logs_dir}/error_{now}.log"
  20. os.makedirs(self.cfg.cognos11.logs_dir, exist_ok=True)
  21. logging.basicConfig(
  22. filename=prot_file,
  23. filemode="w",
  24. encoding="utf-8",
  25. level=logging.DEBUG,
  26. force=True,
  27. )
  28. def get_folder(self, folder, format="PDF"):
  29. if folder == "":
  30. folder = "Team Content" if format == "XML" else "Team Content/ReportOutput"
  31. elif not folder.startswith("Team Content"):
  32. folder = "Team Content/ReportOutput/" + folder
  33. return folder
  34. def export_folder(self, folder="", format="PDF") -> None:
  35. folder = self.get_folder(folder, format)
  36. reports = self.api.get_reports_in_folder(folder, True)
  37. for r in reports:
  38. print(r["name"])
  39. if format == "PDF":
  40. self.export_pdf(r["id"], folder)
  41. if format == "XML":
  42. self.export_unstubbed(r["id"])
  43. def export_unstubbed(self, report_id):
  44. report = self.api.get_report(report_id)
  45. unstubbed_report = self.api.request_unstubbed(report_id)
  46. if unstubbed_report:
  47. filename = (
  48. f"{self.cfg.cognos11.specs_dir}/{report['path']}/{report['name']}.xml"
  49. )
  50. os.makedirs(os.path.dirname(filename), exist_ok=True)
  51. with open(filename, "w") as f:
  52. f.write(unstubbed_report)
  53. def export_pdf(self, report_id, folder=None):
  54. report = self.api.get_report(report_id)
  55. if "meta" not in report:
  56. logging.warning(report["name"] + " is not accessible!")
  57. return False
  58. params = {}
  59. if len(report["meta"]["required"]) > 0:
  60. if set(report["meta"]["required"].keys()) != {"p_Von", "p_Bis"}:
  61. return False
  62. params["p_Von"] = {"2022-10-12": "12.10.2022"}
  63. params["p_Bis"] = {"2022-10-12": "12.10.2022"}
  64. params["p_Zeitraum"] = {"Einzelne Monate": "Einzelne Monate"}
  65. for k, v in report["meta"]["optional"].items():
  66. if k in ["p_Zeit", "p_Auswahl_Monate", "p_12_Monate"]:
  67. for k1, v1 in reversed(v.items()):
  68. if v1 != "Invalid Dates":
  69. params[k] = {k1: v1}
  70. continue # use last element only
  71. if len(report["params"]) == 0:
  72. filename = report["filename"]
  73. self.request_and_save_file(report["id"], params, filename, report["format"])
  74. return True
  75. if len(report["params"]) == 1:
  76. filename = report["filename"].format("_1")
  77. self.request_and_save_file(report["id"], params, filename, report["format"])
  78. key1 = report["params"][0]
  79. for k1, v1 in report["meta"]["optional"][key1].items():
  80. filename = report["filename"].format(v1)
  81. params[key1] = {k1: v1}
  82. self.request_and_save_file(
  83. report["id"], params, filename, report["format"]
  84. )
  85. return True
  86. if len(report["params"]) == 2:
  87. key1, key2 = report["params"]
  88. for k1, v1 in report["meta"]["optional"][key1].items():
  89. for k2, v2 in report["meta"]["optional"][key2].items():
  90. filename = report["filename"].format(v1, v2)
  91. params[key1] = {k1: v1}
  92. params[key2] = {k2: v2}
  93. self.request_and_save_file(
  94. report["id"], params, filename, report["format"]
  95. )
  96. return True
  97. def request_and_save_file(self, report_id, params, filename, format="PDF"):
  98. logging.debug(filename)
  99. logging.debug(params)
  100. status_code, content = self.api.request_file(report_id, params, format)
  101. if status_code == 200:
  102. os.makedirs(os.path.dirname(filename), exist_ok=True)
  103. with open(filename, "wb") as f:
  104. f.write(content)
  105. else:
  106. logging.warning(content)
  107. def export_errors(self):
  108. reports = self.api.get_reports_in_folder(
  109. "Team Content", recursive=True, specs=True
  110. )
  111. errors = [r for r in reports if "error" in r]
  112. filename = self.cfg.cognos11.logs_dir + "/c11_report_errors.json"
  113. json.dump(errors, open(filename, "w"), indent=2)
  114. def mail_template(self, folder: str):
  115. current_dir = Path(self.cfg.cognos11.reportoutput_dir + "\\" + folder)
  116. subfolders = set(
  117. [f.name for f in current_dir.glob("*") if f.is_dir()]
  118. ).difference([".", "..", "leer"])
  119. folder2 = folder + "\\" if folder != "" else ""
  120. export_files = [
  121. f"{folder2}{f.name};"
  122. for f in current_dir.glob("*.*")
  123. if f.suffix in [".pdf", ".xls"]
  124. ]
  125. if len(export_files) > 0:
  126. folder2 = folder.replace("\\", "_") if folder != "" else "Versand"
  127. template_file = Path(
  128. self.cfg.cognos11.config_dir + "\\" + folder2 + ".template.csv"
  129. )
  130. print(template_file)
  131. with template_file.open("w") as fwh:
  132. fwh.write("Report;Empfaenger\n")
  133. fwh.write("\n".join(export_files))
  134. for f in subfolders:
  135. subfolder = folder + "\\" + f if folder != "" else f
  136. self.mail_template(subfolder)
  137. if __name__ == "__main__":
  138. api = c11_api()
  139. api.login()
  140. pdf = c11_export(None, api)
  141. # pdf.export_folder('Team Content/Verkauf/1. Gesamtverkauf', 'PDF')
  142. # pdf.export_folder('Team Content/Aftersales/1. Service')
  143. pdf.export_errors()