gc-server3 пре 1 година
родитељ
комит
3805eee880
3 измењених фајлова са 243 додато и 173 уклоњено
  1. 144 104
      mazda_upload.py
  2. 26 25
      mazda_webservice.py
  3. 73 44
      nasa_upload.py

+ 144 - 104
mazda_upload.py

@@ -20,157 +20,197 @@ class MazdaConfig:
 
 
 cfg = MazdaConfig(
-    domain='https://mappsacc.mazdaeur.com',
-    webservice='/dogma-restapi-dms/api',
-    module='/vehicles/workshop/order-report',
-    auth_url='/oauth/authorize',
-    token_url='/oauth/token',
-    client_id='E7FC943B-B73F-F48E-B71A-419EA4CD4AC7',
-    client_secret='^bH=rk@c58zrr^Apc#9fzy$c',
-    username='mmd88888.cdk',
-    password='MazdaCX30',
-    dealer_number='88888/MMD'
+    domain="https://mappsacc.mazdaeur.com",
+    webservice="/dogma-restapi-dms/api",
+    module="/vehicles/workshop/order-report",
+    auth_url="/oauth/authorize",
+    token_url="/oauth/token",
+    client_id="E7FC943B-B73F-F48E-B71A-419EA4CD4AC7",
+    client_secret="^bH=rk@c58zrr^Apc#9fzy$c",
+    username="mmd88888.cdk",
+    password="MazdaCX30",
+    dealer_number="88888/MMD",
 )
 
-redirect_uri = 'https://localhost/'
-base_dir = '/home/robert/projekte/mazda/'
+redirect_uri = "https://localhost/"
+base_dir = "/home/robert/projekte/mazda/"
 
 
 def date_format(d: datetime):
     if d == 0:
-        return ''     # '0000-00-00T00:00:00.000Z'
-    date_str = d.isoformat(sep='T')
+        return ""  # '0000-00-00T00:00:00.000Z'
+    date_str = d.isoformat(sep="T")
     if len(date_str) == 19:
-        return date_str + '.000Z'
-    return date_str[:-3] + 'Z'
+        return date_str + ".000Z"
+    return date_str[:-3] + "Z"
 
 
 def convert_csv(import_csv, export_json, year, month):
     date_min = datetime(year, month, 1, 0, 0, 0)
     date_max = datetime(year, month + 1, 1, 0, 0, 0)
 
-    date_cols = ['invoiceDate', 'orderDate', 'orderCompletionDate', 'vehicleIntakeDate', 'nextMotDueDate']
-    df = pd.read_csv(import_csv, encoding='latin-1', decimal=',', sep=';', parse_dates=date_cols)
-    df = df.fillna(0)[(df['invoiceDate'] >= date_min) & (df['invoiceDate'] <= date_max)]
-    df = df.sort_values(by=['invoiceDate', 'invoiceNumber', 'orderNumber', 'lineNumber'])
-    df['vin'] = np.where(df['vin'] == 0, '0' * 17, df['vin'])
+    date_cols = ["invoiceDate", "orderDate", "orderCompletionDate", "vehicleIntakeDate", "nextMotDueDate"]
+    df = pd.read_csv(import_csv, encoding="latin-1", decimal=",", sep=";", parse_dates=date_cols)
+    df = df.fillna(0)[(df["invoiceDate"] >= date_min) & (df["invoiceDate"] <= date_max)]
+    df = df.sort_values(by=["invoiceDate", "invoiceNumber", "orderNumber", "lineNumber"])
+    df["vin"] = np.where(df["vin"] == 0, "0" * 17, df["vin"])
     # print(df[['currency','documentType','invoiceCategory','invoiceDate','invoiceNumber']].drop_duplicates().info())
-    invoices_filter = ['currency', 'documentType', 'invoiceCategory', 'invoiceDate', 'invoiceNumber']
-    invoices = df[invoices_filter].drop_duplicates().to_dict('records')
-    invoice_items_filter = ['invoiceNumber', 'orderLineNumber', 'orderNumber', 'amount', 'discount', 'portion', 'unitPrice']
-    invoice_items = df[invoice_items_filter].groupby('invoiceNumber')
+    invoices_filter = ["currency", "documentType", "invoiceCategory", "invoiceDate", "invoiceNumber"]
+    invoices = df[invoices_filter].drop_duplicates().to_dict("records")
+    invoice_items_filter = [
+        "invoiceNumber",
+        "orderLineNumber",
+        "orderNumber",
+        "amount",
+        "discount",
+        "portion",
+        "unitPrice",
+    ]
+    invoice_items = df[invoice_items_filter].groupby("invoiceNumber")
 
     for invoice in invoices:
-        invoice['invoiceDate'] = date_format(invoice['invoiceDate'])
-        items = invoice_items.get_group(invoice['invoiceNumber'])
-        items.pop('invoiceNumber')
-        invoice['invoiceItems'] = items.to_dict('records')
-
-    orders = df[['orderNumber', 'orderDate', 'orderCompletionDate', 'vehicleIntakeDate']].drop_duplicates().to_dict('records')
-    orders_vehicle_filter = ['orderNumber', 'licensePlate', 'nextMotDueDate', 'odometer', 'odometerUnit', 'vin']
-    orders_vehicle = df[orders_vehicle_filter].drop_duplicates().groupby('orderNumber')
-    orders_items = df[[
-        'orderNumber', 'lineNumber', 'orderItemType',
-        'category', 'descriptionOperation', 'hours', 'operationCode', 'standardHours',
-        'descriptionOther', 'type',
-        'descriptionPart', 'isDamageCausal', 'manufacturer', 'partNumber', 'quantity', 'serialNumber', 'unit',
-        'company', 'descriptionPurchase', 'invoiceCode', 'invoiceDate', 'invoiceNumber'
-    ]].drop_duplicates().groupby('orderNumber')
+        invoice["invoiceDate"] = date_format(invoice["invoiceDate"])
+        items = invoice_items.get_group(invoice["invoiceNumber"])
+        items.pop("invoiceNumber")
+        invoice["invoiceItems"] = items.to_dict("records")
+
+    orders = (
+        df[["orderNumber", "orderDate", "orderCompletionDate", "vehicleIntakeDate"]]
+        .drop_duplicates()
+        .to_dict("records")
+    )
+    orders_vehicle_filter = ["orderNumber", "licensePlate", "nextMotDueDate", "odometer", "odometerUnit", "vin"]
+    orders_vehicle = df[orders_vehicle_filter].drop_duplicates().groupby("orderNumber")
+    orders_items = (
+        df[
+            [
+                "orderNumber",
+                "lineNumber",
+                "orderItemType",
+                "category",
+                "descriptionOperation",
+                "hours",
+                "operationCode",
+                "standardHours",
+                "descriptionOther",
+                "type",
+                "descriptionPart",
+                "isDamageCausal",
+                "manufacturer",
+                "partNumber",
+                "quantity",
+                "serialNumber",
+                "unit",
+                "company",
+                "descriptionPurchase",
+                "invoiceCode",
+                "invoiceDate",
+                "invoiceNumber",
+            ]
+        ]
+        .drop_duplicates()
+        .groupby("orderNumber")
+    )
 
     for order in orders:
-        order['vehicle'] = orders_vehicle.get_group(order['orderNumber']).to_dict('records')[0]
-        order['vehicle']['nextMotDueDate'] = date_format(order['vehicle']['nextMotDueDate'])
+        order["vehicle"] = orders_vehicle.get_group(order["orderNumber"]).to_dict("records")[0]
+        order["vehicle"]["nextMotDueDate"] = date_format(order["vehicle"]["nextMotDueDate"])
 
-        order['orderDate'] = date_format(order['orderDate'])
-        order['orderCompletionDate'] = date_format(order['orderCompletionDate'])
-        order['vehicleIntakeDate'] = date_format(order['vehicleIntakeDate'])
+        order["orderDate"] = date_format(order["orderDate"])
+        order["orderCompletionDate"] = date_format(order["orderCompletionDate"])
+        order["vehicleIntakeDate"] = date_format(order["vehicleIntakeDate"])
 
-        items = orders_items.get_group(order['orderNumber']).to_dict('records')
-        order['items'] = []
+        items = orders_items.get_group(order["orderNumber"]).to_dict("records")
+        order["items"] = []
         for item in items:
-            if item['orderItemType'] == 'operation':
-                order['items'].append({
-                    'lineNumber': item['lineNumber'],
-                    'operation': {
-                        'category': item['category'],
-                        'description': item['descriptionOperation'],
-                        'hours': item['hours'],
-                        'operationCode': item['operationCode'],
-                        'standardHours': item['standardHours']
+            if item["orderItemType"] == "operation":
+                order["items"].append(
+                    {
+                        "lineNumber": item["lineNumber"],
+                        "operation": {
+                            "category": item["category"],
+                            "description": item["descriptionOperation"],
+                            "hours": item["hours"],
+                            "operationCode": item["operationCode"],
+                            "standardHours": item["standardHours"],
+                        },
                     }
-                })
-            elif item['orderItemType'] == 'part':
-                order['items'].append({
-                    'lineNumber': item['lineNumber'],
-                    'part': {
-                        'description': item['descriptionPart'],
-                        'isDamageCausal': item['isDamageCausal'],
-                        'manufacturer': item['manufacturer'],
-                        'partNumber': item['partNumber'],
-                        'quantity': item['quantity'],
-                        'serialNumber': item['serialNumber'],
-                        'unit': item['unit']
+                )
+            elif item["orderItemType"] == "part":
+                order["items"].append(
+                    {
+                        "lineNumber": item["lineNumber"],
+                        "part": {
+                            "description": item["descriptionPart"],
+                            "isDamageCausal": item["isDamageCausal"],
+                            "manufacturer": item["manufacturer"],
+                            "partNumber": item["partNumber"],
+                            "quantity": item["quantity"],
+                            "serialNumber": item["serialNumber"],
+                            "unit": item["unit"],
+                        },
                     }
-                })
-            elif item['orderItemType'] == 'other':
-                order['items'].append({
-                    'lineNumber': item['lineNumber'],
-                    'other': {
-                        'description': item['descriptionOther'],
-                        'type': item['type']
+                )
+            elif item["orderItemType"] == "other":
+                order["items"].append(
+                    {
+                        "lineNumber": item["lineNumber"],
+                        "other": {"description": item["descriptionOther"], "type": item["type"]},
                     }
-                })
+                )
             else:
-                order['items'].append({
-                    'lineNumber': item['lineNumber'],
-                    'purchaseInvoice': {
-                        'company': item['company'],
-                        'description': item['descriptionPurchase'],
-                        'invoiceCode': item['invoiceCode'],
-                        'invoiceDate': date_format(item['invoiceDate']),
-                        'invoiceNumber': item['invoiceNumber']
+                order["items"].append(
+                    {
+                        "lineNumber": item["lineNumber"],
+                        "purchaseInvoice": {
+                            "company": item["company"],
+                            "description": item["descriptionPurchase"],
+                            "invoiceCode": item["invoiceCode"],
+                            "invoiceDate": date_format(item["invoiceDate"]),
+                            "invoiceNumber": item["invoiceNumber"],
+                        },
                     }
-                })
+                )
 
     res = {
-        'creationDate': date_format(datetime.now()),
-        'invoices': invoices,
-        'orders': orders,
-        'timeRangeBegin': date_format(date_min),
-        'timeRangeEnd': date_format(date_max)
+        "creationDate": date_format(datetime.now()),
+        "invoices": invoices,
+        "orders": orders,
+        "timeRangeBegin": date_format(date_min),
+        "timeRangeEnd": date_format(date_max),
     }
 
-    json.dump(res, open(export_json, 'w'), indent=2)
+    json.dump(res, open(export_json, "w"), indent=2)
     return res
 
 
 def upload(oauth, data):
     headers = {
-        'accept': 'application/vnd.mazdaeur.dms.v4+json',
-        'x-mme-organisation': cfg.dealer_number,
-        'X-mazda-org': cfg.dealer_number,
-        'Content-Type': 'application/json',
+        "accept": "application/vnd.mazdaeur.dms.v4+json",
+        "x-mme-organisation": cfg.dealer_number,
+        "X-mazda-org": cfg.dealer_number,
+        "Content-Type": "application/json",
         # 'Authorization': 'Bearer ' + token
     }
 
-    invoices = data['invoices']
-    orders = data['orders']
-    data['orders'] = []
+    invoices = data["invoices"]
+    orders = data["orders"]
+    data["orders"] = []
     for i in invoices:
-        data['invoices'] = [i]
-        order_no = [item['orderNumber'] for item in i['invoiceItems']]
-        data['orders'] = [o for o in orders if o['orderNumber'] in order_no]
+        data["invoices"] = [i]
+        order_no = [item["orderNumber"] for item in i["invoiceItems"]]
+        data["orders"] = [o for o in orders if o["orderNumber"] in order_no]
         r = oauth.post(cfg.domain + cfg.webservice + cfg.module, json.dumps(data), headers=headers)
         print(f"{i['invoiceNumber']} => {r.status_code}")
-        with open(base_dir + f"logs/invoice_{i['invoiceNumber']}.log", 'w') as fwh:
+        with open(base_dir + f"logs/invoice_{i['invoiceNumber']}.log", "w") as fwh:
             fwh.write(r.text)
 
 
 def main():
-    data = convert_csv(base_dir + 'data/Workshop_Order_Report.csv', base_dir + 'temp/mazda_export.json', 2021, 6)
+    data = convert_csv(base_dir + "data/Workshop_Order_Report.csv", base_dir + "temp/mazda_export.json", 2021, 6)
     # data = json.load(open(base_dir + 'mazda_export.json', 'r'))
     upload(None, data)
 
 
-if __name__ == '__main__':
+if __name__ == "__main__":
     main()

+ 26 - 25
mazda_webservice.py

@@ -28,30 +28,30 @@ class Token:
 app = Flask(__name__)
 
 cfg: mazda_upload.MazdaConfig = mazda_upload.cfg
-base_dir = '/home/robert/projekte/mazda/'
+base_dir = "/home/robert/projekte/mazda/"
 
 
 def token_save(token):
-    session['oauth_token'] = token
-    with open(base_dir + 'temp/token.json', 'w') as fwh:
+    session["oauth_token"] = token
+    with open(base_dir + "temp/token.json", "w") as fwh:
         json.dump(token, fwh, indent=2)
 
 
 def token_load() -> Token:
     try:
-        with open(base_dir + 'temp/token.json', 'r') as frh:
+        with open(base_dir + "temp/token.json", "r") as frh:
             return json.load(frh)
     except FileNotFoundError:
         return None
 
 
 def get_token() -> Token:
-    if session.get('oauth_token') is None:
-        session['oauth_token'] = token_load()
+    if session.get("oauth_token") is None:
+        session["oauth_token"] = token_load()
 
-        if session['oauth_token'] is not None and session['oauth_token']['expires_at'] < datetime.now().timestamp():
-            session['oauth_token'] = None
-    return session['oauth_token']
+        if session["oauth_token"] is not None and session["oauth_token"]["expires_at"] < datetime.now().timestamp():
+            session["oauth_token"] = None
+    return session["oauth_token"]
 
 
 @app.route("/")
@@ -60,47 +60,48 @@ def demo():
     oauth = OAuth2Session(cfg.client_id, token=get_token())
 
     if oauth.authorized:
-        return redirect('/profile')
+        return redirect("/profile")
 
-    redirect_uri = request.base_url + 'callback'
+    redirect_uri = request.base_url + "callback"
     print(redirect_uri)
     oauth = OAuth2Session(cfg.client_id, redirect_uri=redirect_uri)
     authorization_url, state = oauth.authorization_url(cfg.domain + cfg.auth_url)
-    session['oauth_state'] = state
+    session["oauth_state"] = state
     return redirect(authorization_url)
 
 
 @app.route("/callback", methods=["GET"])
 def callback():
-    state = session.get('oauth_state')
+    state = session.get("oauth_state")
     if state is None:
-        return redirect('/')
+        return redirect("/")
     print(state)
     redirect_uri = request.base_url
     print(redirect_uri)
     oauth = OAuth2Session(cfg.client_id, state=state, redirect_uri=redirect_uri)
     try:
-        token = oauth.fetch_token(cfg.domain + cfg.token_url, client_secret=cfg.client_secret, authorization_response=request.url)
+        token = oauth.fetch_token(
+            cfg.domain + cfg.token_url, client_secret=cfg.client_secret, authorization_response=request.url
+        )
         token_save(token)
-        session['oauth_token'] = token
-        return redirect('/profile')
+        session["oauth_token"] = token
+        return redirect("/profile")
     except OAuth2Error as e:
         print(e)
-        return redirect('/')
+        return redirect("/")
 
 
 @app.route("/profile", methods=["GET"])
 def profile():
-    oauth = OAuth2Session(cfg.client_id, token=session.get('oauth_token'))
-    data = mazda_upload.convert_csv(base_dir + 'data/Workshop_Order_Report.csv', base_dir + 'temp/mazda_export.json', 2021, 6)
-    mazda_upload.upload(oauth, data)
-    return app.response_class(
-        response=json.dumps(data, indent=2),
-        mimetype='application/json'
+    oauth = OAuth2Session(cfg.client_id, token=session.get("oauth_token"))
+    data = mazda_upload.convert_csv(
+        base_dir + "data/Workshop_Order_Report.csv", base_dir + "temp/mazda_export.json", 2021, 6
     )
+    mazda_upload.upload(oauth, data)
+    return app.response_class(response=json.dumps(data, indent=2), mimetype="application/json")
 
 
 if __name__ == "__main__":
     # os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"
     app.secret_key = os.urandom(24)
-    app.run(host='0.0.0.0', port='8085', ssl_context=('config/cert/cert.pem', 'config/cert/key.pem'), debug=True)
+    app.run(host="0.0.0.0", port="8085", ssl_context=("config/cert/cert.pem", "config/cert/key.pem"), debug=True)

+ 73 - 44
nasa_upload.py

@@ -9,47 +9,56 @@ from suds.client import Client
 from cryptography.fernet import Fernet
 
 # Konfiguration
-fernet_key = b'YBckeKYt-8g7LFvpG7XqAAcEbsYESnI-yl8by9rjeQQ='
+fernet_key = b"YBckeKYt-8g7LFvpG7XqAAcEbsYESnI-yl8by9rjeQQ="
 fernet = Fernet(fernet_key)
 
-if path.exists('nasa_config.json'):
-    with open('nasa_config.json', 'r') as f:
+if path.exists("nasa_config.json"):
+    with open("nasa_config.json", "r") as f:
         config = json.load(f)
-    with open('nasa_config.crypt', 'wb') as f:
+    with open("nasa_config.crypt", "wb") as f:
         f.write(fernet.encrypt(json.dumps(config).encode()))
 else:
-    with open('nasa_config.crypt', 'rb') as f:
+    with open("nasa_config.crypt", "rb") as f:
         config = json.loads(fernet.decrypt(f.read()).decode())
 
-args = ['2020', '05']
+args = ["2020", "05"]
 # args = []
 if len(args) >= 2:
-    config['selected_year'] = args[0]
-    config['selected_month'] = args[1]
+    config["selected_year"] = args[0]
+    config["selected_month"] = args[1]
 else:
     curr_date = date.today() - relativedelta(months=+1)
-    config['selected_year'] = curr_date.strftime('%Y')
-    config['selected_month'] = curr_date.strftime('%m')
-
-
-select_befehl_auftraege = "SELECT * FROM [Auftraege_NASA_gruppiert] WHERE Periode = '" + \
-                          config['selected_year'] + config['selected_month'] + "'"
-select_befehl_mitarbeiter = "SELECT * FROM [Mitarbeiter_NASA] WHERE Periode = '" + \
-                            config['selected_year'] + "-" + config['selected_month'] + "'"
-source_auftraege = 'nasa/Auftraege_NASA_gruppiert.csv'
-source_mitarbeiter = 'nasa/Mitarbeiter_NASA.csv'
+    config["selected_year"] = curr_date.strftime("%Y")
+    config["selected_month"] = curr_date.strftime("%m")
+
+
+select_befehl_auftraege = (
+    "SELECT * FROM [Auftraege_NASA_gruppiert] WHERE Periode = '"
+    + config["selected_year"]
+    + config["selected_month"]
+    + "'"
+)
+select_befehl_mitarbeiter = (
+    "SELECT * FROM [Mitarbeiter_NASA] WHERE Periode = '"
+    + config["selected_year"]
+    + "-"
+    + config["selected_month"]
+    + "'"
+)
+source_auftraege = "nasa/Auftraege_NASA_gruppiert.csv"
+source_mitarbeiter = "nasa/Mitarbeiter_NASA.csv"
 
 
 header = {
-    'HaendlerNr': config['client_id'],
-    'Filiale': "1",
-    'Jahr': config['selected_year'],
-    'Monat': config['selected_month'],
-    'Fabrikat': 'Mazda',
-    'AnzahlMitarbeiter': '0',
-    'AnzahlProduktiv': '0.0',
-    'WerkstattDurchlaeufe': '0',
-    'Token': config['credentials']['token']
+    "HaendlerNr": config["client_id"],
+    "Filiale": "1",
+    "Jahr": config["selected_year"],
+    "Monat": config["selected_month"],
+    "Fabrikat": "Mazda",
+    "AnzahlMitarbeiter": "0",
+    "AnzahlProduktiv": "0.0",
+    "WerkstattDurchlaeufe": "0",
+    "Token": config["credentials"]["token"],
 }
 
 
@@ -58,34 +67,54 @@ def conn_string(dsn):
 
 
 # Datenbankverbindung
-source_db = create_engine(conn_string(config['source_dsn']))
+source_db = create_engine(conn_string(config["source_dsn"]))
 
 # Abfrage in Array speichern
 df = pd.read_sql(select_befehl_auftraege, con=source_db)
 # df = pd.read_csv(source_auftraege, sep=";", encoding="latin-1", decimal=",")
-df.to_csv("mazda/export/" + config['selected_year'] + "-" + config['selected_month'] + "_auftraege.csv",
-          sep=";", encoding="latin-1", decimal=",", index=False)
+df.to_csv(
+    "mazda/export/" + config["selected_year"] + "-" + config["selected_month"] + "_auftraege.csv",
+    sep=";",
+    encoding="latin-1",
+    decimal=",",
+    index=False,
+)
 
 # Array in gewünschtes Format bringen
 auftragsart = ["Inspektion", "Karosseriearbeit", "Lackierung", "Verschleißteile", "Sonstiges"]
-columns = ["AuftragsArt", "AuftragsArtId", "TeileUmsatz", "LohnUmsatz", "SonstigeUmsatz", "GesamtUmsatz", "AnzahlAuftraege"]
+columns = [
+    "AuftragsArt",
+    "AuftragsArtId",
+    "TeileUmsatz",
+    "LohnUmsatz",
+    "SonstigeUmsatz",
+    "GesamtUmsatz",
+    "AnzahlAuftraege",
+]
 
 df = df[columns]
-header['WerkstattDurchlaeufe'] = df['AnzahlAuftraege'].sum()
-header['AfterSalesPositionen'] = df.to_dict("records")
+header["WerkstattDurchlaeufe"] = df["AnzahlAuftraege"].sum()
+header["AfterSalesPositionen"] = df.to_dict("records")
 
 # Mitarbeiter gesamt und produktiv
 df = pd.read_sql(select_befehl_mitarbeiter, con=source_db)
 # df = pd.read_csv(source_mitarbeiter, sep=";", encoding="latin-1", decimal=",")
 
-df.to_csv("mazda/export/" + config['selected_year'] + "-" + config['selected_month'] + '_mitarbeiter.csv',
-          sep=';', encoding='latin-1', decimal=',', index=False)
+df.to_csv(
+    "mazda/export/" + config["selected_year"] + "-" + config["selected_month"] + "_mitarbeiter.csv",
+    sep=";",
+    encoding="latin-1",
+    decimal=",",
+    index=False,
+)
 
-header['AnzahlMitarbeiter'] = df.shape[0]
-header['AnzahlProduktiv'] = df['Prod'].sum()
+header["AnzahlMitarbeiter"] = df.shape[0]
+header["AnzahlProduktiv"] = df["Prod"].sum()
 
 # SOAP-Verbindung
-client = Client(config['service_url'], username=config['credentials']['username'], password=config['credentials']['password'])
+client = Client(
+    url=config["service_url"], username=config["credentials"]["username"], password=config["credentials"]["password"]
+)
 
 try:
     result = client.service.MeldeAfterSalesDaten(header)
@@ -95,12 +124,12 @@ except Exception as e:
 
 # Erfolg/Fehler protokollieren
 
-print('Periode: ' + config['selected_year'] + "-" + config['selected_month'])
-if len(header['AfterSalesPositionen']) == result:
-    print('Erfolgreich ' + str(result) + ' Datensätze übertragen')
+print("Periode: " + config["selected_year"] + "-" + config["selected_month"])
+if len(header["AfterSalesPositionen"]) == result:
+    print("Erfolgreich " + str(result) + " Datensätze übertragen")
 else:
-    print('Übertragung der Datensätze Fehlgeschlagen.')
+    print("Übertragung der Datensätze Fehlgeschlagen.")
     if result == -1:
-        print('Fehler! Es waren keine Datensätze vorhanden.')
+        print("Fehler! Es waren keine Datensätze vorhanden.")
     else:
-        print(str(len(header['AfterSalesPositionen']) - result) + ' Datensätze nicht verarbeitet')
+        print(str(len(header["AfterSalesPositionen"]) - result) + " Datensätze nicht verarbeitet")