Browse Source

C11.exe mit "mailtemplate"

gc-server6 1 year ago
parent
commit
fa69aa35ae
6 changed files with 162 additions and 104 deletions
  1. 10 7
      c11.py
  2. 37 33
      c11.spec
  3. 21 15
      cognos11/c11_create.py
  4. 86 48
      cognos11/c11_export.py
  5. BIN
      dist/c11.exe
  6. 8 1
      requirements.txt

+ 10 - 7
c11.py

@@ -11,20 +11,20 @@ class ExportFormat(Enum):
 
 
 class C11:
-    commands = ['export', 'reportoutput', 'errors', 'create']
+    commands = ["export", "reportoutput", "errors", "create", "mailtemplate"]
 
     def __init__(self):
         self.cfg = config.Config()
 
-    def export(self, folder='', format='XML'):
+    def export(self, folder="", format="XML"):
         exp = cognos11.c11_export(self.cfg)
         exp.export_folder(folder, format)
 
-    def reportoutput(self, folder=''):
+    def reportoutput(self, folder=""):
         exp = cognos11.c11_export(self.cfg)
         folder2 = exp.get_folder(folder)
-        exp.export_folder(folder, 'PDF')
-        pdf_test.missing_data(self.cfg.cognos11.reportoutput_dir + '/' + folder)
+        exp.export_folder(folder, "PDF")
+        pdf_test.missing_data(self.cfg.cognos11.reportoutput_dir + "/" + folder)
         pdf_merge.merge_reports_in_folder(self.cfg, folder2)
 
     def errors(self):
@@ -34,7 +34,10 @@ class C11:
     def create(self, path: str):
         cognos11.c11_create(self.cfg).create_path(path)
 
+    def mailtemplate(self):
+        exp = cognos11.c11_export(self.cfg)
+        exp.mail_template("")
+
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     plac.Interpreter.call(C11)
-    # C11().reportoutput()

+ 37 - 33
c11.spec

@@ -4,37 +4,41 @@
 block_cipher = None
 
 
-a = Analysis(['c11.py'],
-             pathex=['C:\\Projekte\\tools\\'],
-             binaries=[],
-             datas=[],
-             hiddenimports=[],
-             hookspath=[],
-             hooksconfig={},
-             runtime_hooks=[],
-             excludes=[],
-             win_no_prefer_redirects=False,
-             win_private_assemblies=False,
-             cipher=block_cipher,
-             noarchive=False)
-pyz = PYZ(a.pure, a.zipped_data,
-             cipher=block_cipher)
+a = Analysis(
+    ['c11.py'],
+    pathex=['C:\\Projekte\\tools\\'],
+    binaries=[],
+    datas=[],
+    hiddenimports=[],
+    hookspath=[],
+    hooksconfig={},
+    runtime_hooks=[],
+    excludes=[],
+    win_no_prefer_redirects=False,
+    win_private_assemblies=False,
+    cipher=block_cipher,
+    noarchive=False,
+)
+pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
 
-exe = EXE(pyz,
-          a.scripts,
-          a.binaries,
-          a.zipfiles,
-          a.datas,  
-          [],
-          name='c11',
-          debug=False,
-          bootloader_ignore_signals=False,
-          strip=False,
-          upx=True,
-          upx_exclude=[],
-          runtime_tmpdir=None,
-          console=True,
-          disable_windowed_traceback=False,
-          target_arch=None,
-          codesign_identity=None,
-          entitlements_file=None )
+exe = EXE(
+    pyz,
+    a.scripts,
+    a.binaries,
+    a.zipfiles,
+    a.datas,
+    [],
+    name='c11',
+    debug=False,
+    bootloader_ignore_signals=False,
+    strip=False,
+    upx=True,
+    upx_exclude=[],
+    runtime_tmpdir=None,
+    console=True,
+    disable_windowed_traceback=False,
+    argv_emulation=False,
+    target_arch=None,
+    codesign_identity=None,
+    entitlements_file=None,
+)

+ 21 - 15
cognos11/c11_create.py

@@ -15,32 +15,32 @@ class c11_create:
         self.config = cfg
         self.api = api
         if api is None:
-            self.api = c11_api().login()
+            self.api = c11_api(self.config).login()
 
-        now = datetime.now().strftime('%Y%m%d_%H%M%S')
+        now = datetime.now().strftime("%Y%m%d_%H%M%S")
         prot_file = f"{self.log_dir}/create_{now}.log"
         os.makedirs(self.log_dir, exist_ok=True)
         logging.basicConfig(
             filename=prot_file,
-            filemode='w',
-            encoding='utf-8',
+            filemode="w",
+            encoding="utf-8",
             level=logging.DEBUG,
-            force=True
+            force=True,
         )
 
     def create_path(self, path, recursive=False):
-        if path.startswith('Team Content'):
+        if path.startswith("Team Content"):
             fullpath = f"{self.spec_dir}/{path}"
         else:
-            pos = path.find('Team Content')
+            pos = path.find("Team Content")
             fullpath = path
             path = fullpath[pos:]
 
         fullpath = os.path.abspath(fullpath)
-        path = path.replace('\\', '/')
+        path = path.replace("\\", "/")
 
         if not os.path.exists(fullpath):
-            logging.error(fullpath + ' does not exist!')
+            logging.error(fullpath + " does not exist!")
             return False
 
         folder = path if os.path.isdir(fullpath) else os.path.dirname(path)
@@ -49,13 +49,15 @@ class c11_create:
             self.create_report(folder_id, folder, fullpath)
 
     def create_folders(self, folder):
-        folder_split = folder.split('/')
-        folder_parents = ['/'.join(folder_split[:i]) for i in range(1, len(folder_split) + 1)]
+        folder_split = folder.split("/")
+        folder_parents = [
+            "/".join(folder_split[:i]) for i in range(1, len(folder_split) + 1)
+        ]
         print(folder_parents)
         folders = self.api.get_folders()
         last_id = None
         for parent in folder_parents:
-            parent_id = [f['id'] for f in folders if f['name'] == parent]
+            parent_id = [f["id"] for f in folders if f["name"] == parent]
             if len(parent_id) > 0:
                 last_id = parent_id.pop()
             else:
@@ -64,15 +66,19 @@ class c11_create:
 
     def create_report(self, folder_id, folder_name, fullpath):
         report_name = os.path.basename(fullpath)[:-4]
-        reports = [r for r in self.api.get_reports_in_folder(folder_name) if r['name'] == report_name]
+        reports = [
+            r
+            for r in self.api.get_reports_in_folder(folder_name)
+            if r["name"] == report_name
+        ]
         if len(reports) == 0:
             self.api.create_report(folder_id, fullpath)
         else:
             self.api.update_report(reports[0], fullpath)
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     create_api = c11_create()
     # pdf.export_folder('Team Content/Verkauf/1. Gesamtverkauf', 'PDF')
     # pdf.export_folder('Team Content/Aftersales/1. Service')
-    create_api.create_path('Team Content/ReportOutput/Forderungen')
+    create_api.create_path("Team Content/ReportOutput/Forderungen")

+ 86 - 48
cognos11/c11_export.py

@@ -1,3 +1,4 @@
+from pathlib import Path
 from cognos11.c11_api import c11_api
 import config
 import json
@@ -18,88 +19,94 @@ class c11_export:
         if api is None:
             self.api = c11_api(cfg).login()
 
-        now = datetime.now().strftime('%Y%m%d_%H%M%S')
+        now = datetime.now().strftime("%Y%m%d_%H%M%S")
         prot_file = f"{self.cfg.cognos11.logs_dir}/error_{now}.log"
         os.makedirs(self.cfg.cognos11.logs_dir, exist_ok=True)
         logging.basicConfig(
             filename=prot_file,
-            filemode='w',
-            encoding='utf-8',
+            filemode="w",
+            encoding="utf-8",
             level=logging.DEBUG,
-            force=True
+            force=True,
         )
 
-    def get_folder(self, folder, format='PDF'):
-        if folder == '':
-            folder = 'Team Content' if format == 'XML' else 'Team Content/ReportOutput'
-        elif not folder.startswith('Team Content'):
-            folder = 'Team Content/ReportOutput/' + folder
+    def get_folder(self, folder, format="PDF"):
+        if folder == "":
+            folder = "Team Content" if format == "XML" else "Team Content/ReportOutput"
+        elif not folder.startswith("Team Content"):
+            folder = "Team Content/ReportOutput/" + folder
         return folder
 
-    def export_folder(self, folder='', format='PDF') -> None:
+    def export_folder(self, folder="", format="PDF") -> None:
         folder = self.get_folder(folder, format)
         reports = self.api.get_reports_in_folder(folder, True)
         for r in reports:
-            print(r['name'])
-            if format == 'PDF':
-                self.export_pdf(r['id'], folder)
-            if format == 'XML':
-                self.export_unstubbed(r['id'])
+            print(r["name"])
+            if format == "PDF":
+                self.export_pdf(r["id"], folder)
+            if format == "XML":
+                self.export_unstubbed(r["id"])
 
     def export_unstubbed(self, report_id):
         report = self.api.get_report(report_id)
         unstubbed_report = self.api.request_unstubbed(report_id)
         if unstubbed_report:
-            filename = f"{self.cfg.cognos11.specs_dir}/{report['path']}/{report['name']}.xml"
+            filename = (
+                f"{self.cfg.cognos11.specs_dir}/{report['path']}/{report['name']}.xml"
+            )
             os.makedirs(os.path.dirname(filename), exist_ok=True)
             with open(filename, "w") as f:
                 f.write(unstubbed_report)
 
     def export_pdf(self, report_id, folder=None):
         report = self.api.get_report(report_id)
-        if 'meta' not in report:
-            logging.warning(report['name'] + ' is not accessible!')
+        if "meta" not in report:
+            logging.warning(report["name"] + " is not accessible!")
             return False
         params = {}
-        if len(report['meta']['required']) > 0:
-            if set(report['meta']['required'].keys()) != {'p_Von', 'p_Bis'}:
+        if len(report["meta"]["required"]) > 0:
+            if set(report["meta"]["required"].keys()) != {"p_Von", "p_Bis"}:
                 return False
-            params['p_Von'] = {'2022-10-12': '12.10.2022'}
-            params['p_Bis'] = {'2022-10-12': '12.10.2022'}
-            params['p_Zeitraum'] = {'Einzelne Monate': 'Einzelne Monate'}
+            params["p_Von"] = {"2022-10-12": "12.10.2022"}
+            params["p_Bis"] = {"2022-10-12": "12.10.2022"}
+            params["p_Zeitraum"] = {"Einzelne Monate": "Einzelne Monate"}
 
-            for k, v in report['meta']['optional'].items():
-                if k in ['p_Zeit', 'p_Auswahl_Monate', 'p_12_Monate']:
+            for k, v in report["meta"]["optional"].items():
+                if k in ["p_Zeit", "p_Auswahl_Monate", "p_12_Monate"]:
                     for k1, v1 in reversed(v.items()):
-                        if v1 != 'Invalid Dates':
+                        if v1 != "Invalid Dates":
                             params[k] = {k1: v1}
                             continue  # use last element only
 
-        if len(report['params']) == 0:
-            filename = report['filename']
-            self.request_and_save_file(report['id'], params, filename, report['format'])
+        if len(report["params"]) == 0:
+            filename = report["filename"]
+            self.request_and_save_file(report["id"], params, filename, report["format"])
             return True
-        if len(report['params']) == 1:
-            filename = report['filename'].format('_1')
-            self.request_and_save_file(report['id'], params, filename, report['format'])
+        if len(report["params"]) == 1:
+            filename = report["filename"].format("_1")
+            self.request_and_save_file(report["id"], params, filename, report["format"])
 
-            key1 = report['params'][0]
-            for k1, v1 in report['meta']['optional'][key1].items():
-                filename = report['filename'].format(v1)
+            key1 = report["params"][0]
+            for k1, v1 in report["meta"]["optional"][key1].items():
+                filename = report["filename"].format(v1)
                 params[key1] = {k1: v1}
-                self.request_and_save_file(report['id'], params, filename, report['format'])
+                self.request_and_save_file(
+                    report["id"], params, filename, report["format"]
+                )
             return True
-        if len(report['params']) == 2:
-            key1, key2 = report['params']
-            for k1, v1 in report['meta']['optional'][key1].items():
-                for k2, v2 in report['meta']['optional'][key2].items():
-                    filename = report['filename'].format(v1, v2)
+        if len(report["params"]) == 2:
+            key1, key2 = report["params"]
+            for k1, v1 in report["meta"]["optional"][key1].items():
+                for k2, v2 in report["meta"]["optional"][key2].items():
+                    filename = report["filename"].format(v1, v2)
                     params[key1] = {k1: v1}
                     params[key2] = {k2: v2}
-                    self.request_and_save_file(report['id'], params, filename, report['format'])
+                    self.request_and_save_file(
+                        report["id"], params, filename, report["format"]
+                    )
             return True
 
-    def request_and_save_file(self, report_id, params, filename, format='PDF'):
+    def request_and_save_file(self, report_id, params, filename, format="PDF"):
         logging.debug(filename)
         logging.debug(params)
         status_code, content = self.api.request_file(report_id, params, format)
@@ -111,13 +118,44 @@ class c11_export:
             logging.warning(content)
 
     def export_errors(self):
-        reports = self.api.get_reports_in_folder('Team Content', recursive=True, specs=True)
-        errors = [r for r in reports if 'error' in r]
-        filename = self.cfg.cognos11.logs_dir + '/c11_report_errors.json'
-        json.dump(errors, open(filename, 'w'), indent=2)
+        reports = self.api.get_reports_in_folder(
+            "Team Content", recursive=True, specs=True
+        )
+        errors = [r for r in reports if "error" in r]
+        filename = self.cfg.cognos11.logs_dir + "/c11_report_errors.json"
+        json.dump(errors, open(filename, "w"), indent=2)
+
+    def mail_template(self, folder: str):
+        current_dir = Path(self.cfg.cognos11.reportoutput_dir + "\\" + folder)
+
+        subfolders = set(
+            [f.name for f in current_dir.glob("*") if f.is_dir()]
+        ).difference([".", "..", "leer"])
+
+        folder2 = folder + "\\" if folder != "" else ""
+
+        export_files = [
+            f"{folder2}{f.name};"
+            for f in current_dir.glob("*.*")
+            if f.suffix in [".pdf", ".xls"]
+        ]
+
+        if len(export_files) > 0:
+            folder2 = folder.replace("\\", "_") if folder != "" else "Versand"
+            template_file = Path(
+                self.cfg.cognos11.config_dir + "\\" + folder2 + ".template.csv"
+            )
+            print(template_file)
+            with template_file.open("w") as fwh:
+                fwh.write("Report;Empfaenger\n")
+                fwh.write("\n".join(export_files))
+
+        for f in subfolders:
+            subfolder = folder + "\\" + f if folder != "" else f
+            self.mail_template(subfolder)
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     api = c11_api()
     api.login()
     pdf = c11_export(None, api)

BIN
dist/c11.exe


+ 8 - 1
requirements.txt

@@ -1,7 +1,14 @@
-Flask>=2.2.0
+flask>=2.2.0
 beautifulsoup4
+jinja2
+lxml
 numpy
 pandas
+pdfplumber
 plac
+pyinstaller
 pyodbc
+pypdf2
+requests
+requests_toolbelt
 sqlalchemy