Exemplo n.º 1
0
    def post(self, request, *args, **kwargs):
        """Deletes entitlement request from API"""
        api = API(self.request.session.get('obp'))

        try:
            urlpath = '/users/{}/entitlements'.format(kwargs['user_id'])
            payload = {
                'bank_id': request.POST.get('bank_id', '<undefined>'),
                'role_name': request.POST.get('role_name', '<undefined>'),
            }
            api.post(urlpath, payload=payload)
            msg = 'Entitlement with role {} has been added.'.format(
                request.POST.get('role_name', '<undefined>'))
            messages.success(request, msg)
        except APIError as err:
            messages.error(request, err)

        try:
            urlpath = '/entitlement-requests/{}'.format(
                request.POST.get('entitlement_request_id', '<undefined>'))
            api.delete(urlpath)
            msg = 'Entitlement Request with role {} has been deleted.'.format(
                request.POST.get('role_name', '<undefined>'))
            messages.success(request, msg)
        except APIError as err:
            messages.error(request, err)

        redirect_url = request.POST.get('next',
                                        reverse('entitlementrequests-index'))
        return HttpResponseRedirect(redirect_url)
Exemplo n.º 2
0
def methodrouting_save(request):
    method_name = request.POST.get('method_name')
    connector_name = request.POST.get('connector_name')
    bank_id_pattern = request.POST.get('bank_id_pattern')
    is_bank_id_exact_match = request.POST.get('is_bank_id_exact_match')
    parameters = request.POST.get('parameters')
    method_routing_id = request.POST.get('method_routing_id')
    parameters_Json_editor = request.POST.get('parameters_Json_editor')
    payload = {
        'method_name': method_name,
        'connector_name': connector_name,
        'is_bank_id_exact_match': (is_bank_id_exact_match == "True"),
        'bank_id_pattern': bank_id_pattern,
        'parameters': eval(parameters_Json_editor),
        'method_routing_id': method_routing_id
    }

    api = API(request.session.get('obp'))
    if ("" == method_routing_id
        ):  # if method_routing_id=="". we will create a new method routing .
        urlpath = '/management/method_routings'
        result = api.post(urlpath, payload=payload)
    else:  # if method_routing_id not empty. we will update the current method routing ..
        urlpath = '/management/method_routings/{}'.format(method_routing_id)
        result = api.put(urlpath, payload=payload)
    return result
Exemplo n.º 3
0
    def form_valid(self, form):
        """Posts api collection endpoint data to API"""
        try:
            data = form.cleaned_data
            api = API(self.request.session.get('obp'))
            api_collection_id = super(
                DetailView,
                self).get_context_data()['view'].kwargs['api_collection_id']

            urlpath = '/my/api-collection-ids/{}/api-collection-endpoints'.format(
                api_collection_id)
            payload = {'operation_id': data['operation_id']}
            api_collection_endpoint = api.post(urlpath, payload=payload)
        except APIError as err:
            messages.error(self.request, err)
            return super(DetailView, self).form_invalid(form)
        except:
            messages.error(self.request, 'Unknown Error')
            return super(DetailView, self).form_invalid(form)
        if 'code' in api_collection_endpoint and api_collection_endpoint[
                'code'] >= 400:
            messages.error(self.request, api_collection_endpoint['message'])
            return super(DetailView, self).form_invalid(form)
        else:
            msg = 'Operation Id {} has been added.'.format(
                data['operation_id'])
            messages.success(self.request, msg)
            self.success_url = self.request.path
            return super(DetailView, self).form_valid(form)
Exemplo n.º 4
0
def methodrouting_save(request):
    method_name = request.POST.get('method_name')
    connector_name = request.POST.get('connector_name')
    bank_id_pattern = request.POST.get('bank_id_pattern')
    is_bank_id_exact_match = request.POST.get('is_bank_id_exact_match')
    parameters = request.POST.get('parameters')
    method_routing_id = request.POST.get('method_routing_id')
    parameters_Json_editor = request.POST.get('parameters_Json_editor')
    #from sonarcloud: Dynamic code execution should not be vulnerable to injection attacks
    exec("import json" % json.loads(parameters_Json_editor)
         )  # Compliant; module is safely cast to json object
    payload = {
        'method_name': method_name,
        'connector_name': connector_name,
        'is_bank_id_exact_match': (is_bank_id_exact_match == "True"),
        'bank_id_pattern': bank_id_pattern,
        'parameters': json.loads(parameters_Json_editor),
        'method_routing_id': method_routing_id
    }

    api = API(request.session.get('obp'))
    if ("" == method_routing_id
        ):  # if method_routing_id=="". we will create a new method routing .
        urlpath = '/management/method_routings'
        result = api.post(urlpath, payload=payload)
    else:  # if method_routing_id not empty. we will update the current method routing ..
        urlpath = '/management/method_routings/{}'.format(method_routing_id)
        result = api.put(urlpath, payload=payload)
    return result
Exemplo n.º 5
0
def apicollections_save(request):
    api = API(request.session.get('obp'))
    urlpath = '/my/api-collections'
    payload = {
        'api_collection_name': request.POST.get('api_collection_name').strip(),
        'is_sharable': bool(request.POST.get('api_collection_is_sharable')),
        'description': request.POST.get('api_collection_description').strip()
    }
    result = api.post(urlpath, payload=payload)
    return result
Exemplo n.º 6
0
class DetailView(LoginRequiredMixin, FormView):
    """Detail view for a user"""
    form_class = AddEntitlementForm
    template_name = 'users/detail.html'

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(DetailView, self).dispatch(request, *args, **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(DetailView, self).get_form(*args, **kwargs)
        try:
            form.fields['bank_id'].choices = self.api.get_bank_id_choices()
        except APIError as err:
            messages.error(self.request, err)
        return form

    def form_valid(self, form):
        """Posts entitlement data to API"""
        try:
            data = form.cleaned_data
            urlpath = '/users/{}/entitlements'.format(data['user_id'])
            payload = {
                'bank_id': data['bank_id'],
                'role_name': data['role_name'],
            }
            entitlement = self.api.post(urlpath, payload=payload)
        except APIError as err:
            messages.error(self.request, err)
            return super(DetailView, self).form_invalid(form)

        msg = 'Entitlement with role {} has been added.'.format(
            entitlement['role_name'])
        messages.success(self.request, msg)
        self.success_url = self.request.path
        return super(DetailView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        # NOTE: assuming there is just one user with that email address
        # The API needs a call 'get user by id'!
        user = {}
        try:
            urlpath = '/users/user_id/{}'.format(self.kwargs['user_id'])
            user = self.api.get(urlpath)
            context['form'].fields['user_id'].initial = user['user_id']
        except APIError as err:
            messages.error(self.request, err)

        context.update({
            'apiuser': user,  # 'user' is logged-in user in template context
        })
        return context
Exemplo n.º 7
0
def webui_save(request):
    web_ui_props_name = request.POST.get('web_ui_props_name')
    web_ui_props_value = request.POST.get('web_ui_props_value')

    payload = {
        'name': web_ui_props_name,
        'value': web_ui_props_value
    }
    api = API(request.session.get('obp'))
    urlpath = '/management/webui_props'
    response = api.post(urlpath, payload=payload)
    
    return response
Exemplo n.º 8
0
class IndexView(LoginRequiredMixin, FormView):
    """Index view for config"""
    template_name = "webui/index.html"
    form_class = WebuiForm
    success_url = reverse_lazy('webui-index')

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(IndexView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)

        return context

    def get_form(self, *args, **kwargs):
        form = super(IndexView, self).get_form(*args, **kwargs)
        # Cannot add api in constructor: super complains about unknown kwarg
        fields = form.fields
        form.api = self.api
        try:
            fields['webui_props'].initial = ""

        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, "Unknown Error")

        return form

    def form_valid(self, form):
        try:
            data = form.cleaned_data
            urlpath = '/management/webui_props'
            payload = {
                "name": "webui_api_explorer_url",
                "value": data["webui_props"]
            }
            result = self.api.post(urlpath, payload=payload)
        except APIError as err:
            error_once_only(self.request, err)
            return super(IndexView, self).form_invalid(form)
        except Exception as err:
            error_once_only(self.request, "Unknown Error")
            return super(IndexView, self).form_invalid(form)
        if 'code' in result and result['code'] >= 400:
            error_once_only(self.request, result['message'])
            return super(IndexView, self).form_valid(form)
        msg = 'Submission successfully!'
        messages.success(self.request, msg)
        return super(IndexView, self).form_valid(form)
Exemplo n.º 9
0
def methodrouting_save(request):
    method_name = request.POST.get('method_name')
    connector_name = request.POST.get('connector_name')
    bank_id_pattern = request.POST.get('bank_id_pattern')
    is_bank_id_exact_match = request.POST.get('is_bank_id_exact_match')
    parameters = request.POST.get('parameters')
    method_routing_id = request.POST.get('method_routing_id')

    payload = {
        'method_name': method_name,
        'connector_name': connector_name,
        'is_bank_id_exact_match': (is_bank_id_exact_match == "True"),
        'bank_id_pattern': bank_id_pattern,
        'parameters': eval(parameters),
        'method_routing_id': method_routing_id
    }

    api = API(request.session.get('obp'))
    try:
        if (
                "" == method_routing_id
        ):  # if method_routing_id=="". we will create a new method routing .
            urlpath = '/management/method_routings'
            result = api.post(urlpath, payload=payload)
        else:  # if method_routing_id not empty. we will update the current method routing ..
            urlpath = '/management/method_routings/{}'.format(
                method_routing_id)
            result = api.put(urlpath, payload=payload)
    except APIError as err:
        error_once_only(
            request,
            APIError(
                Exception(
                    "The OBP-API server is not running or does not respond properly."
                    "Please check OBP-API server.   Details: " + str(err))))
    except Exception as err:
        error_once_only(request, "Unknown Error. Details: " + str(err))
    if 'code' in result and result['code'] >= 400:
        error_once_only(request, result['message'])
        msg = 'Submission successfully!'
        messages.success(request, msg)
    return JsonResponse({'state': True})
Exemplo n.º 10
0
def webui_save(request):
    webui_props_name = request.POST.get('webui_props_name')
    webui_props_value = request.POST.get('webui_props_value')

    payload = {
        'name': webui_props_name,
        'value': webui_props_value
    }

    api = API(request.session.get('obp'))
    try:
        urlpath = '/management/webui_props'
        result = api.post(urlpath, payload=payload)
    except APIError as err:
        error_once_only(request, APIError(Exception("The OBP-API server is not running or does not respond properly."
                                                    "Please check OBP-API server.   Details: " + str(err))))
    except Exception as err:
        error_once_only(request, "Unknown Error. Details: " + str(err))
    if 'code' in result and result['code'] >= 400:
        error_once_only(request, result['message'])
        msg = 'Submission successfully!'
        messages.success(request, msg)
    return JsonResponse({'state': True})
Exemplo n.º 11
0
def dynamicendpoints_save(request):
    parameters_Json_editor = request.POST.get('parameters_Json_editor')
    api = API(request.session.get('obp'))
    urlpath = '/management/dynamic-endpoints'
    result = api.post(urlpath, payload=json.loads(parameters_Json_editor) )
    return result
Exemplo n.º 12
0
class IndexAtmsView(LoginRequiredMixin, FormView):
    """Index view for ATMs"""
    template_name = "atms/index.html"
    form_class = CreateAtmForm
    success_url = reverse_lazy('atms_list')

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(IndexAtmsView, self).dispatch(request, *args, **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(IndexAtmsView, self).get_form(*args, **kwargs)
        # Cannot add api in constructor: super complains about unknown kwarg
        form.api = self.api
        fields = form.fields
        try:
            fields['bank_id'].choices = self.api.get_bank_id_choices()
            fields['is_accessible'].choices = [('', 'Choose...'), (True, True),
                                               (False, False)]
            fields['has_deposit_capability'].choices = [('', 'Choose...'),
                                                        (True, True),
                                                        (False, False)]
            fields['supported_languages'].choices = [('', 'Choose...'),
                                                     ("en", "en"),
                                                     ("fr", "fr"),
                                                     ("de", "de")]
            fields['notes'].choices = [('', 'Choose...'),
                                       ("String1", "String1"),
                                       ("String2", "String2")]
            fields['supported_currencies'].choices = [('', 'Choose...'),
                                                      ("EUR", "EUR"),
                                                      ("MXN", "MXN"),
                                                      ("USD", "USD")]
            fields['location_categories'].choices = [('', 'Choose...'),
                                                     ("ATBI", "ATBI"),
                                                     ("ATBE", "ATBE")]
            fields['lobby'].initial = json.dumps(
                {
                    "monday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "tuesday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "wednesday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "thursday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "friday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "saturday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "sunday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }]
                },
                indent=4)

            fields['address'].initial = json.dumps(
                {
                    "line_1": "No 1 the Road",
                    "line_2": "The Place",
                    "line_3": "The Hill",
                    "city": "Berlin",
                    "county": "String",
                    "state": "Brandenburg",
                    "postcode": "13359",
                    "country_code": "DE"
                },
                indent=4)
        except APIError as err:
            messages.error(self.request, err)
        except Exception as err:
            messages.error(self.request, err)

        return form

    def form_valid(self, form):
        try:
            data = form.cleaned_data
            urlpath = '/banks/{}/atms'.format(data['bank_id'])
            payload = {
                "id":
                data["atm_id"],
                "bank_id":
                data["bank_id"],
                "name":
                data["name"],
                "address":
                json.loads(data['address']),
                "location": {
                    "latitude":
                    float(data["location_latitude"])
                    if data["location_latitude"] is not None else 37.0,
                    "longitude":
                    float(data["location_longitude"])
                    if data["location_longitude"] is not None else 110.0
                },
                "meta": {
                    "license": {
                        "id":
                        "PDDL",
                        "name":
                        data["meta_license_name"]
                        if data["meta_license_name"] != "" else "license name"
                    }
                },
                "monday": {
                    "opening_time": "10:00",
                    "closing_time": "18:00"
                },
                "tuesday": {
                    "opening_time": "10:00",
                    "closing_time": "18:00"
                },
                "wednesday": {
                    "opening_time": "10:00",
                    "closing_time": "18:00"
                },
                "thursday": {
                    "opening_time": "10:00",
                    "closing_time": "18:00"
                },
                "friday": {
                    "opening_time": "10:00",
                    "closing_time": "18:00"
                },
                "saturday": {
                    "opening_time": "10:00",
                    "closing_time": "18:00"
                },
                "sunday": {
                    "opening_time": "10:00",
                    "closing_time": "18:00"
                },
                "is_accessible":
                data["is_accessible"]
                if data["is_accessible"] != "" else "false",
                "located_at":
                data["located_at"] if data["located_at"] != "" else "false",
                "more_info":
                data["more_info"] if data["more_info"] != "" else "false",
                "has_deposit_capability":
                data["has_deposit_capability"]
                if data["has_deposit_capability"] != "" else "false",
                "supported_languages": [data["supported_languages"]],
                "services": [data["services"]],
                "accessibility_features": [data["accessibility_features"]],
                "supported_currencies": [data["supported_currencies"]],
                "notes": [data["notes"]],
                "location_categories": [data["location_categories"]],
                "minimum_withdrawal":
                data["minimum_withdrawal"]
                if data["minimum_withdrawal"] != "" else "false",
                "branch_identification":
                data["branch_identification"]
                if data["branch_identification"] != "" else "false",
                "site_identification":
                data["site_identification"]
                if data["site_identification"] != "" else "false",
                "site_name":
                data["site_name"] if data["site_name"] != "" else "false",
                "cash_withdrawal_national_fee":
                data["cash_withdrawal_national_fee"]
                if data["cash_withdrawal_national_fee"] != "" else "false",
                "cash_withdrawal_international_fee":
                data["cash_withdrawal_international_fee"] if
                data["cash_withdrawal_international_fee"] != "" else "false",
                "balance_inquiry_fee":
                data["balance_inquiry_fee"]
                if data["balance_inquiry_fee"] != "" else "false",
            }
            result = self.api.post(urlpath, payload=payload)
        except APIError as err:
            messages.error(self.request, "Unknown Error")
            return super(IndexAtmsView, self).form_invalid(form)
        except Exception as err:
            messages.error(self.request, "Unknown Error")
            return super(IndexAtmsView, self).form_invalid(form)
        if 'code' in result and result['code'] >= 400:
            messages.error(self.request, result['message'])
            return super(IndexAtmsView, self).form_valid(form)
        msg = 'atm {} for Bank {} has been created successfully!'.format(
            result["id"], result['bank_id'])
        messages.success(self.request, msg)
        return super(IndexAtmsView, self).form_valid(form)

    def get_banks(self):
        api = API(self.request.session.get('obp'))
        try:
            urlpath = '/banks'
            result = api.get(urlpath)
            if 'banks' in result:
                return [
                    bank['id']
                    for bank in sorted(result['banks'], key=lambda d: d['id'])
                ]
            else:
                return []
        except APIError as err:
            messages.error(self.request, err)
            return []

    def get_atms(self, context):

        api = API(self.request.session.get('obp'))
        try:
            self.bankids = self.get_banks()
            atms_list = []
            for bank_id in self.bankids:
                urlpath = '/banks/{}/atms'.format(bank_id)

                result = api.get(urlpath)
                if 'atms' in result:
                    atms_list.extend(result['atms'])
        except APIError as err:
            messages.error(self.request, err)
            return []
        except Exception as inst:
            messages.error(self.request,
                           "Unknown Error {}".format(type(inst).__name__))
            return []

        return atms_list

    def get_context_data(self, **kwargs):
        context = super(IndexAtmsView, self).get_context_data(**kwargs)
        atms_list = self.get_atms(context)
        context.update({'atms_list': atms_list, 'bankids': self.bankids})
        return context
Exemplo n.º 13
0
class IndexBranchesView(LoginRequiredMixin, FormView):
    """Index view for branches"""
    template_name = "branches/index.html"
    form_class = CreateBranchForm
    success_url = reverse_lazy('branches_list')

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(IndexBranchesView, self).dispatch(request, *args,
                                                       **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(IndexBranchesView, self).get_form(*args, **kwargs)
        # Cannot add api in constructor: super complains about unknown kwarg
        form.api = self.api
        fields = form.fields
        try:
            fields['bank_id'].choices = self.api.get_bank_id_choices()
            fields['is_accessible'].choices = [('', 'Choose...'), (True, True),
                                               (False, False)]
            fields['drive_up'].initial = json.dumps(
                {
                    "monday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "tuesday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "wednesday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "thursday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "friday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "saturday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "sunday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }
                },
                indent=4)

            fields['lobby'].initial = json.dumps(
                {
                    "monday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "tuesday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "wednesday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "thursday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "friday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "saturday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "sunday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }]
                },
                indent=4)

            fields['address'].initial = json.dumps(
                {
                    "line_1": "No 1 the Road",
                    "line_2": "The Place",
                    "line_3": "The Hill",
                    "city": "Berlin",
                    "county": "String",
                    "state": "Brandenburg",
                    "postcode": "13359",
                    "country_code": "DE"
                },
                indent=4)

        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, "Unknown Error")

        return form

    def form_valid(self, form):
        try:
            data = form.cleaned_data
            urlpath = '/banks/{}/branches'.format(data['bank_id'])
            payload = {
                "id":
                data["branch_id"],
                "bank_id":
                data["bank_id"],
                "name":
                data["name"],
                "address":
                json.loads(data['address']),
                "location": {
                    "latitude":
                    float(data["location_latitude"])
                    if data["location_latitude"] is not None else 37.0,
                    "longitude":
                    float(data["location_longitude"])
                    if data["location_longitude"] is not None else 110.0
                },
                "meta": {
                    "license": {
                        "id":
                        "PDDL",
                        "name":
                        data["meta_license_name"]
                        if data["meta_license_name"] != "" else "license name"
                    }
                },
                "lobby":
                json.loads(data['lobby']),
                "drive_up":
                json.loads(data["drive_up"]),
                "branch_routing": {
                    "scheme":
                    data["branch_routing_scheme"]
                    if data["branch_routing_scheme"] != "" else "license name",
                    "address":
                    data["branch_routing_address"]
                    if data["branch_routing_address"] != "" else "license name"
                },
                "is_accessible":
                data["is_accessible"]
                if data["is_accessible"] != "" else "false",
                "accessibleFeatures":
                data["accessibleFeatures"] if data["accessibleFeatures"] != ""
                else "accessible features name",
                "branch_type":
                data["branch_type"]
                if data["branch_type"] != "" else "branch type",
                "more_info":
                data["more_info"] if data["more_info"] != "" else "more info",
                "phone_number":
                data["phone_number"]
                if data["phone_number"] != "" else "phone number"
            }
            result = self.api.post(urlpath, payload=payload)
        except APIError as err:
            error_once_only(self.request, err)
            return super(IndexBranchesView, self).form_invalid(form)
        except Exception as err:
            error_once_only(self.request, "Unknown Error")
            return super(IndexBranchesView, self).form_invalid(form)
        if 'code' in result and result['code'] >= 400:
            error_once_only(self.request, result['message'])
            return super(IndexBranchesView, self).form_valid(form)
        msg = 'Branch {} for Bank {} has been created successfully!'.format(
            result['id'], result['bank_id'])
        messages.success(self.request, msg)
        return super(IndexBranchesView, self).form_valid(form)

    def get_banks(self):
        api = API(self.request.session.get('obp'))
        try:
            urlpath = '/banks'
            result = api.get(urlpath)
            if 'banks' in result:
                return [
                    bank['id']
                    for bank in sorted(result['banks'], key=lambda d: d['id'])
                ]
            else:
                return []
        except APIError as err:
            messages.error(self.request, err)
            return []

    def get_branches(self, context):

        api = API(self.request.session.get('obp'))
        try:
            self.bankids = self.get_banks()
            branches_list = []
            for bank_id in self.bankids:
                urlpath = '/banks/{}/branches'.format(bank_id)

                result = api.get(urlpath)
                if 'branches' in result:
                    branches_list.extend(result['branches'])
        except APIError as err:
            messages.error(self.request, err)
            return []
        except Exception as inst:
            messages.error(self.request,
                           "Unknown Error {}".format(type(inst).__name__))
            return []

        return branches_list

    def get_context_data(self, **kwargs):
        context = super(IndexBranchesView, self).get_context_data(**kwargs)
        branches_list = self.get_branches(context)
        context.update({
            'branches_list': branches_list,
            'bankids': self.bankids
        })
        return context
Exemplo n.º 14
0
class CreateView(LoginRequiredMixin, FormView):
    """View to create a customer"""
    form_class = CreateCustomerForm
    template_name = 'customers/create.html'
    success_url = reverse_lazy('customers-create')

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(CreateView, self).dispatch(request, *args, **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(CreateView, self).get_form(*args, **kwargs)
        # Cannot add api in constructor: super complains about unknown kwarg
        form.api = self.api
        fields = form.fields
        try:
            fields['bank_id'].choices = self.api.get_bank_id_choices()
        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, "Unknown Error")
        fields['last_ok_date'].initial =\
            datetime.datetime.now().strftime(settings.API_DATETIMEFORMAT)
        return form

    def form_valid(self, form):
        data = form.cleaned_data
        urlpath = '/banks/{}/customers'.format(data['bank_id'])
        payload = {
            'user_id':
            data['user_id'],
            'customer_number':
            data['customer_number'],
            'legal_name':
            data['legal_name'],
            'mobile_phone_number':
            data['mobile_phone_number'],
            'email':
            data['email'],
            'face_image': {
                'url': data['face_image_url'],
                'date': data['face_image_date'],
            },
            'date_of_birth':
            data['date_of_birth'],
            'relationship_status':
            data['relationship_status'],
            'dependants':
            data['dependants'],
            'dob_of_dependants':
            data['dob_of_dependants'],
            'credit_rating': {
                'rating': data['credit_rating_rating'],
                'source': data['credit_rating_source'],
            },
            'credit_limit': {
                'currency': data['credit_limit_currency'],
                'amount': data['credit_limit_amount'],
            },
            'highest_education_attained':
            data['highest_education_attained'],
            'employment_status':
            data['employment_status'],
            'kyc_status':
            data['kyc_status'],
            'last_ok_date':
            data['last_ok_date'].strftime(settings.API_DATETIMEFORMAT),
        }
        try:
            result = self.api.post(urlpath, payload=payload)
        except APIError as err:
            messages.error(self.request, err)
            return super(CreateView, self).form_invalid(form)
        except:
            messages.error(self.request, "Unknown Error")
            return super(CreateView, self).form_invalid(form)
        msg = 'Customer number {} for user {} has been created successfully!'.format(  # noqa
            result['customer_number'], data['username'])
        messages.success(self.request, msg)
        return super(CreateView, self).form_valid(form)
Exemplo n.º 15
0
class InvitationView(LoginRequiredMixin, FormView):
    """View to create a User Invitation"""
    form_class = CreateInvitationForm
    template_name = 'users/invitation.html'
    success_url = reverse_lazy('my-user-invitation')

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(InvitationView, self).dispatch(request, *args, **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(InvitationView, self).get_form(*args, **kwargs)
        form.api = self.api
        fields = form.fields
        try:
            fields['bank_id'].choices = self.api.get_bank_id_choices()
        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, "Unknown Error")
        return form

    def form_valid(self, form, **kwargs):
        data = form.cleaned_data
        post_url_path = '/banks/{}/user-invitation'.format(data['bank_id'])
        get_url_path = '/banks/{}/user-invitations'.format(data['bank_id'])
        invitations = []
        payload = {
            'first_name': data['first_name'],
            'last_name': data['last_name'],
            'email': data['email'],
            'company': data['company'],
            'country': data['country'],
            'purpose': 'DEVELOPER'
        }
        context = self.get_context_data(**kwargs)
        try:
            result = self.api.post(post_url_path, payload=payload)
            if 'code' in result and result['code'] >= 400:
                messages.error(self.request, result['message'])
                return super(InvitationView, self).form_valid(form)
            else:
                self.get_invitations(context, get_url_path, invitations)
                msg = 'User Invitation ({}) at Bank({}) has been {}!'.format(
                    result['first_name'], data['bank_id'], result['status'])
                messages.success(self.request, msg)
                return self.render_to_response(context)
        except APIError as err:
            messages.error(self.request, err)
            return super(InvitationView, self).form_invalid(form)
        except Exception as err:
            messages.error(self.request, "Unknown Error:{}".format(str(err)))
            return super(InvitationView, self).form_invalid(form)

    def get_invitations(self, context, get_url_path, invitations):
        response = self.api.get(get_url_path)
        if 'code' in response and response['code'] >= 400:
            messages.error(self.request, response['message'])
        else:
            invitations = invitations + response['user_invitations']
        context.update({
            'invitations': invitations,
        })