mazda-upload.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import pandas as pd
  2. import json
  3. import requests
  4. # import requests
  5. from requests_oauthlib import OAuth2Session
  6. from oauthlib.oauth2 import BackendApplicationClient
  7. from datetime import datetime
  8. domain = 'https://mappsacc.mazdaeur.com'
  9. # domain = 'https://mapps.mazdaeur.com' # Production Server
  10. webservice = domain + '/dogma-restapi-dms/api'
  11. module = '/vehicles/workshop/order-report'
  12. auth_url = domain + '/oauth/authorize'
  13. token_url = domain + '/oauth/token'
  14. redirect_uri = 'https://localhost/'
  15. client_id = 'E7FC943B-B73F-F48E-B71A-419EA4CD4AC7'
  16. client_secret = '^bH=rk@c58zrr^Apc#9fzy$c'
  17. username = 'mmd88888.cdk'
  18. password = 'MazdaCX30' # 'Der neue MX-30'
  19. dealer_number = '88888/MMD' # '11197/MMD' # Example '10030/MMD'
  20. # token = 'MDDq3CUd9ix0iSqR'
  21. base_dir = '/home/robert/projekte/python/mazda/'
  22. def date_format(d: datetime):
  23. date_str = d.isoformat(sep='T')
  24. if len(date_str) == 19:
  25. return date_str + '.000Z'
  26. return date_str[:-3] + 'Z'
  27. def convert_csv(csv_file, json_file, year, month):
  28. date_min = datetime(year, month, 1, 0, 0, 0)
  29. date_max = datetime(year, month + 1, 1, 0, 0, 0)
  30. date_cols = ['invoiceDate', 'orderDate', 'orderCompletionDate', 'vehicleIntakeDate', 'nextMotDueDate']
  31. df = pd.read_csv(csv_file, encoding='latin-1', decimal=',', sep=';', parse_dates=date_cols)
  32. # print(df[['currency','documentType','invoiceCategory','invoiceDate','invoiceNumber']].drop_duplicates().info())
  33. invoices = df[['currency', 'documentType', 'invoiceCategory', 'invoiceDate', 'invoiceNumber']].drop_duplicates().to_dict('records')
  34. invoice_items = df[['invoiceNumber', 'orderLineNumber', 'orderNumber', 'amount', 'discount', 'portion', 'unitPrice']].groupby('invoiceNumber')
  35. for invoice in invoices:
  36. invoice['invoiceDate'] = date_format(invoice['invoiceDate'])
  37. items = invoice_items.get_group(invoice['invoiceNumber'])
  38. items.pop('invoiceNumber')
  39. invoice['invoiceItems'] = items.to_dict('records')
  40. orders = df[['orderNumber', 'orderDate', 'orderCompletionDate', 'vehicleIntakeDate']].drop_duplicates().to_dict('records')
  41. orders_vehicle = df[['orderNumber', 'licensePlate', 'nextMotDueDate', 'odometer', 'odometerUnit', 'vin']].drop_duplicates().groupby('orderNumber')
  42. orders_items = df[[
  43. 'orderNumber', 'lineNumber', 'orderItemType',
  44. 'category', 'descriptionOperation', 'hours', 'operationCode', 'standardHours',
  45. 'descriptionOther', 'type',
  46. 'descriptionPart', 'isDamageCausal', 'manufacturer', 'partNumber', 'quantity', 'serialNumber', 'unit',
  47. 'company', 'descriptionPurchase', 'invoiceCode', 'invoiceDate', 'invoiceNumber'
  48. ]].drop_duplicates().groupby('orderNumber')
  49. for order in orders:
  50. order['vehicle'] = orders_vehicle.get_group(order['orderNumber']).to_dict('records')[0]
  51. order['vehicle']['nextMotDueDate'] = date_format(order['vehicle']['nextMotDueDate'])
  52. order['orderDate'] = date_format(order['orderDate'])
  53. order['orderCompletionDate'] = date_format(order['orderCompletionDate'])
  54. order['vehicleIntakeDate'] = date_format(order['vehicleIntakeDate'])
  55. items = orders_items.get_group(order['orderNumber']).to_dict('records')
  56. order['items'] = []
  57. for item in items:
  58. if item['orderItemType'] == 'operation':
  59. order['items'].append({
  60. 'lineNumber': item['lineNumber'],
  61. 'operation': {
  62. 'category': item['category'],
  63. 'description': item['descriptionOperation'],
  64. 'hours': item['hours'],
  65. 'operationCode': item['operationCode'],
  66. 'standardHours': item['standardHours']
  67. }
  68. })
  69. elif item['orderItemType'] == 'part':
  70. order['items'].append({
  71. 'lineNumber': item['lineNumber'],
  72. 'part': {
  73. 'description': item['descriptionPart'],
  74. 'isDamageCausal': item['isDamageCausal'],
  75. 'manufacturer': item['manufacturer'],
  76. 'partNumber': item['partNumber'],
  77. 'quantity': item['quantity'],
  78. 'serialNumber': item['serialNumber'],
  79. 'unit': item['unit']
  80. }
  81. })
  82. elif item['orderItemType'] == 'other':
  83. order['items'].append({
  84. 'lineNumber': item['lineNumber'],
  85. 'other': {
  86. 'description': item['descriptionOther'],
  87. 'type': item['type']
  88. }
  89. })
  90. else:
  91. order['items'].append({
  92. 'lineNumber': item['lineNumber'],
  93. 'purchaseInvoice': {
  94. 'company': item['company'],
  95. 'description': item['descriptionPurchase'],
  96. 'invoiceCode': item['invoiceCode'],
  97. 'invoiceDate': date_format(item['invoiceDate']),
  98. 'invoiceNumber': item['invoiceNumber']
  99. }
  100. })
  101. res = {
  102. 'creationDate': date_format(datetime.now()),
  103. 'invoices': invoices,
  104. 'orders': orders,
  105. 'timeRangeBegin': date_min,
  106. 'timeRangeEnd': date_max
  107. }
  108. json.dump(res, open(json_file, 'w'), indent=2)
  109. return res
  110. def upload(data):
  111. headers = {
  112. 'accept': 'application/vnd.mazdaeur.dms.v4+json',
  113. 'x-mme-organisation': dealer_number,
  114. 'X-mazda-org': dealer_number,
  115. 'Content-Type': 'application/json',
  116. # 'Authorization': 'Bearer ' + token
  117. }
  118. # client = BackendApplicationClient(client_id=client_id)
  119. oauth = OAuth2Session(client_id, redirect_uri=redirect_uri)
  120. authorization_url, state = oauth.authorization_url(auth_url)
  121. print('Please go here and authorize: ' + authorization_url)
  122. redirect_response = input('Paste the full redirect URL here:')
  123. token = oauth.fetch_token(token_url, client_secret=client_secret, authorization_response=redirect_response)
  124. # print(token)
  125. r = oauth.post(webservice + module, json.dumps(data), headers=headers)
  126. with open(base_dir + 'post_error.log', 'w') as fwh:
  127. fwh.write(r.text)
  128. def main():
  129. data = convert_csv(base_dir + 'Workshop_Order_Report.csv', base_dir + 'mazda_export.json', 2021, 6)
  130. # data = json.load(open(base_dir + 'mazda_export.json', 'r'))
  131. upload(data)
  132. if __name__ == '__main__':
  133. main()