antrag.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. #
  2. # Sample Antrag class definition
  3. #
  4. from flask import url_for, current_app
  5. from polzybackend.mediators import Antrag
  6. from polzybackend.models import File
  7. from polzybackend.utils import date_format
  8. from pms.fast_offer import get_fast_offer, get_value_lists
  9. from functools import reduce
  10. from time import sleep
  11. import json
  12. import os
  13. import zipfile
  14. from datetime import datetime
  15. class SampleAntrag(Antrag):
  16. def initialize(self):
  17. #
  18. # initializes antrag instance within Policy Management System
  19. #
  20. result = get_fast_offer(self.product_name)
  21. if result:
  22. # expand result
  23. result.update({
  24. 'id': self.id,
  25. 'status': 'Neu',
  26. 'product_line': {
  27. 'name': self.product_name,
  28. 'attributes': {
  29. 'Produkt': "Auto Insurance Ultra",
  30. }
  31. }
  32. })
  33. self.instance = result
  34. self.set_documents()
  35. return
  36. raise Exception(f'No offer available for product {self.product_name}')
  37. def get(self):
  38. #
  39. # returns antrag instance as json object to front-end
  40. #
  41. return self.instance
  42. def get_field_by_name(self, name):
  43. #
  44. # find antrag field by name
  45. #
  46. get_field = lambda field_list: next(filter(lambda field: field['name'] == name, field_list), None)
  47. # build list of field groups
  48. field_sets = reduce(
  49. lambda result, group: [*result, group['name']],
  50. self.instance['field_groups'],
  51. ['fields', 'field_groups'],
  52. )
  53. # search for field
  54. for fs in field_sets:
  55. target_field = get_field(self.instance[fs])
  56. if target_field:
  57. return target_field
  58. def getValueList(self, valueListName):
  59. #
  60. # returns value-list with given name
  61. #
  62. # emulate delay
  63. sleep(2)
  64. return get_value_lists(valueListName)
  65. def update_auto_brands(self):
  66. #
  67. # update auto brands based on vehicle type
  68. #
  69. mapVechicleToList = {
  70. 'Car': 'carBrand',
  71. 'Light Truck': 'lightTruckBrand',
  72. 'Heavy Truck': 'heavyTruckBrand',
  73. 'Motorcycle': 'motorcycleBrand',
  74. 'Tractor': 'tractorBrand',
  75. 'Bus': 'busBrand',
  76. }
  77. if self.instance['product_line'].get('name') == 'Automobile':
  78. vehicle_type = self.get_field_by_name('VehicleType').get('value')
  79. brand_field = self.get_field_by_name('Brand')
  80. brand_field['inputRange'] = ['async', mapVechicleToList[vehicle_type]]
  81. #brand_field['value'] = None
  82. def update_attachments(self):
  83. #
  84. # updates files in attachment activity
  85. #
  86. # get documents activity
  87. document_activity = next(filter(
  88. lambda activity: activity.get('name') == "Documents",
  89. self.instance['possible_activities'],
  90. ), None)
  91. print('Document Activity:')
  92. print(document_activity)
  93. if document_activity is None:
  94. raise Exception('Document Activity not found')
  95. # get attachment field
  96. attachments = next(filter(
  97. lambda field: field.get('name') == "Attachments",
  98. document_activity['fields']
  99. ), None)
  100. print('Document Activity:')
  101. print(document_activity)
  102. if attachments is None:
  103. raise Exception('Attachment Field not found')
  104. # get files from db
  105. antrag_files = File.query.filter_by(parent_id=self.id).all()
  106. attachments['value'] = [
  107. {
  108. "id": file.id,
  109. "name": file.filename,
  110. "created": file.created.strftime(date_format),
  111. "type": file.type,
  112. "actions": [
  113. "edit",
  114. "delete",
  115. ]
  116. } for index, file in enumerate(antrag_files)
  117. ]
  118. def set_documents(self):
  119. #
  120. # updates files in attachment activity
  121. #
  122. # get documents activity
  123. document_activity = next(filter(
  124. lambda activity: activity.get('name') == "Documents",
  125. self.instance['possible_activities'],
  126. ), None)
  127. if document_activity is None:
  128. raise Exception('Document Activity not found')
  129. # get documents field
  130. documents = next(filter(
  131. lambda field: field.get('name') == "Documents",
  132. document_activity['fields']
  133. ), None)
  134. # create field if not exist
  135. if documents is None:
  136. documents = {
  137. "fieldVisibilityType": 2,
  138. "name": "Documents",
  139. "brief": "Documents",
  140. "tooltip": "Here you can manage the documents",
  141. "fieldDataType": "Documents",
  142. }
  143. document_activity['fields'].append(documents)
  144. # get files from db
  145. antrag_docs = File.query.filter_by(type="document").group_by(File.filename).all()
  146. documents['value'] = [
  147. {
  148. "id": file.id,
  149. "name": file.filename,
  150. "created": file.created.strftime(date_format),
  151. "signed": "Yes" if file.processed else "No",
  152. } for file in antrag_docs
  153. ]
  154. def updateFields(self, data):
  155. #
  156. # updates antrag fields based on data
  157. #
  158. print('\n*** UPDATE FIELDS')
  159. print(json.dumps(data, indent=2))
  160. booleans = {
  161. True: "True",
  162. False: "False",
  163. }
  164. for key, value in data['values'].items():
  165. field = self.get_field_by_name(key)
  166. if field and (field['fieldVisibilityType'] == 1):
  167. field['value'] = booleans.get(value) or value
  168. if field.get("fieldDataType") == "FlagWithOptions" and field.get("relatedFields"):
  169. for sub_field in field['relatedFields']:
  170. sub_field['value'] = data['values'].get(sub_field['name'])
  171. self.update_auto_brands()
  172. self.update_attachments()
  173. self.set_documents()
  174. def executeActivity(self, data):
  175. #
  176. # executes antrag activity defined in data
  177. #
  178. # emulate delay
  179. sleep(1)
  180. # update fields
  181. self.updateFields(data)
  182. # execute activity
  183. if data['activity'] == 'Berechnen':
  184. premium = self.get_field_by_name('premium')
  185. premium['value'] = 1347
  186. self.instance['status'] = 'Calculated'
  187. return self.get()
  188. if data['activity'] == 'Print':
  189. from AntragDrucken import AntragDrucken
  190. lPrint = AntragDrucken(antrag=self)
  191. lPrint.executeActivity()
  192. return {
  193. "link": url_for(
  194. 'end-points.downloads',
  195. filename=lPrint.getFolderAndPath(),
  196. _external=True,
  197. ),
  198. }
  199. if data['activity'] == 'Fields':
  200. print('\n*** Fields Updated:')
  201. print(json.dumps(data, indent=2))
  202. return self.get()
  203. raise Exception(f'Logic for activity {data["activity"]} is not defined')
  204. def getRemoteDocuments(self, documents_id: list):
  205. #
  206. # returns path to fetched remote document
  207. #
  208. files = []
  209. for file_id in documents_id:
  210. file = File.query.get(file_id)
  211. ext = file.filename.split('.')[-1]
  212. files.append({
  213. 'name': file.filename,
  214. 'path': os.path.join(current_app.config['UPLOADS'], f'{file_id}.{ext}'),
  215. })
  216. if len(files) == 1:
  217. return files[0]['path']
  218. # zip files
  219. path_to_zip = os.path.join(
  220. current_app.config['UPLOADS'],
  221. f'polzy_documents_{datetime.now().strftime("%Y%m%d_%H%M%S")}.zip',
  222. )
  223. ziped_documents = zipfile.ZipFile(path_to_zip, 'w')
  224. for file in files:
  225. ziped_documents.write(file['path'], arcname=file['name'])
  226. ziped_documents.close()
  227. return path_to_zip