Browse Source

Partner's Policy Search: adjusted for front-end update

aguryev 3 years ago
parent
commit
87ec6a61b9
3 changed files with 200 additions and 5 deletions
  1. 0 3
      app.py
  2. 75 2
      endpoints/routes.py
  3. 125 0
      pms/customers.py

+ 0 - 3
app.py

@@ -5,7 +5,6 @@ from endpoints import bp as ep_bp
 from pathlib import Path
 
 
-
 class Config(object):
 
     SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(os.path.abspath(os.path.dirname(__file__)), 'polzy.db')
@@ -29,8 +28,6 @@ class Config(object):
     PDF = str(Path(os.path.abspath(__file__)).parent.joinpath("pdfoutput"))
 
 
-
-
 app = create_app(Config)
 app.register_blueprint(clauses_bp)
 app.register_blueprint(ep_bp)

+ 75 - 2
endpoints/routes.py

@@ -1,6 +1,8 @@
 from flask import jsonify, request, current_app, send_file, abort
-from . import bp
+from endpoints import bp
 import os
+from pms.customers import Customers
+import json
 
 #
 # Default Logo
@@ -12,6 +14,11 @@ default_logo = {
     "antrag": "POLZY_LeZyTOR LIGHT.png",    # new antrag card
 }
 
+#
+# generate customers
+#
+customers = Customers()
+
 
 @bp.route('/logo/<string:filename>')
 @bp.route('/logo/default/<string:target>')
@@ -73,4 +80,70 @@ def images(filename):
     return send_file(
         path_to_file,
         attachment_filename=filename,
-    )
+    )
+
+@bp.route('/search', methods=['POST'])
+def search():
+    #
+    # search end-point
+    #
+
+    # get post data
+    data = request.get_json()
+    print(json.dumps(data, indent=2))
+
+    if data.get('activity') == 'partner':
+        #
+        # search for partners
+        #
+
+        try:
+            partners = customers.filter(data.get('value'))
+            result = [{
+                **item,
+                'label': ' '.join({key: value for key, value in item.items() if not key in [
+                    'partnerNumber',
+                    'gender',
+                    'email',
+                    'phone',
+                ]}.values()),
+            } for item in partners]
+            return jsonify(result), 200
+        except Exception as e:
+            current_app.logger.warning(f"Failed to execute search activity 'partner': {e}")
+            return {'error': 'Bad request'}, 4000
+
+    if data.get('activity') == 'partnerDetails':
+        #
+        # search for partner's policies
+        #
+
+        try:
+            result = customers.get_policies(data.get('value'))
+            return jsonify(result), 200
+        except Exception as e:
+            current_app.logger.warning(f"Failed to execute search activity 'partnerDetails': {e}")
+            return {'error': 'Bad request'}, 400
+
+    
+    current_app.logger.warning(f"Search activity {data.get('activity')} is not implemented")
+    return {'error': f'Search in {data.get("activity")} is not supported'}, 400
+
+
+@bp.route('/policies/<string:partner>')
+def partner_policies(partner):
+    #
+    # returns a customer with policies
+    #
+    print(json.dumps(customers.all[0], indent=2))
+
+    try:
+        customer, policies = customers.get_policies(partner)
+        result = {
+            **customer,
+            'policies': policies,
+        }
+        return jsonify(result), 200
+    except Exception as e:
+        return {'error': str(e)}, 400
+

+ 125 - 0
pms/customers.py

@@ -0,0 +1,125 @@
+import requests
+import json
+import random
+from time import sleep
+
+class Customers:
+    #
+    # random customers generator
+    #
+    policy_columns = [
+        {
+            "label": "Policy",
+            "isKey": True,
+            "type": "string",
+            "filter": False,
+        },
+        {
+            "label": "Status",
+            "type": "string",
+            "filter": False,
+        },
+        {
+            "label": "Product",
+            "type": "string",
+            "filter": False,
+        },
+        {
+            "label": "Effective Date",
+            "type": "string",
+            "filter": False,
+        },
+    ]
+
+    def __init__(self, quantity=1000):
+        user_url = f'https://randomuser.me/api/?seed=polzy&results={quantity}&nat=ch,de,dk,es,fi,fr,gb,ie,nl,no,tr&exc=login,id,picture'
+        r = requests.get(user_url)
+        if r.status_code != 200:
+            raise Exception(f'Unable fetch random users:\n{r.status_code}\n{r.text}')
+
+        # reshape fetched users to polzy customers
+        try:
+            self.all = [
+                {
+                    'partnerNumber': ''.join([_ for _ in user['registered'].get('date') if _.isdigit()]),
+                    'firstName': user['name'].get('first'),
+                    'lastName': user['name'].get('last'),
+                    'birthDate': user['dob'].get('date')[:10],
+                    'gender': user['gender'],
+                    'email': user['email'],
+                    'phone': user['phone'],
+                    'postCode': str(user['location'].get('postcode')),
+                    'country': user['location'].get('country'),
+                    'city': user['location'].get('city'),
+                    'street': user['location'].get('street')['name'],
+                    'houseNumber': str(user['location'].get('street')['number']),
+                } for user in r.json().get('results')
+            ]
+        except Exception as e:
+            raise Exception(f'Unable generate customers: {e}')
+        
+
+    def filter(self, search_string=None):
+        #
+        # filter customers by search string's words
+        #
+
+        if not search_string:
+            return self.all
+
+        # filter customers
+        strings = search_string.lower().split()
+        search_fields = [
+            'firstName',
+            'lastName',
+            'email',
+            'city',
+            'street'
+        ]
+
+        filtered_users = filter(
+            lambda user: any(s in ':'.join((user[field].lower() for field in search_fields)) for s in strings),
+            self.all,
+        )
+
+        return list(filtered_users)
+
+    def get_policies(self, partner):
+        #
+        # returns random policies for the specified partner
+        #
+
+        # dalay
+        sleep(2)
+
+        # get customer
+        try:
+            customer = next(filter(
+                lambda user: user['partnerNumber'] == partner,
+                self.all,
+            ))
+        except Exception:
+            raise Exception(f'Partner Number {partner} not found')
+
+        # load policies
+        from pms import POLICY_DATASET
+        with open(POLICY_DATASET, 'r') as f:
+            all_policies = [[
+                p.get('number'),
+                p.get('status'),
+                p['product_line'].get('name'),
+                p.get('effective_date'),
+            ] for p in json.load(f)]
+        policies = random.sample(all_policies, random.randrange(10))
+
+        return {
+            'partner': partner,
+            'policies': {
+                'columns': self.policy_columns,
+                'rows': policies,
+            },
+        }
+
+
+
+