def operator_login(request):
    username = request.data.get("username")
    password = request.data.get("password")
    if username is None or password is None:
        return Response({'error': 'Incorrect email address or password.'},
                        status=HTTP_400_BAD_REQUEST,
                        content_type="application/json")

    try:
        operator = Operators.objects.get(operator_username=username)
    except (TypeError, ValueError, OverflowError, Operators.DoesNotExist):
        return Response({'error': 'Email Id not found.'},
                        status=HTTP_404_NOT_FOUND,
                        content_type="application/json")

    if not check_password(password, operator.operator_password_hash):
        return Response({'error': 'Incorrect email id or password.'},
                        status=HTTP_400_BAD_REQUEST,
                        content_type="application/json")
    else:
        Operators.login(request, operator)
        token = request.session.get(Operators.HASH_SESSION_KEY, None)
        if token is None:
            return Response({'error': 'Not able to create API Token.'},
                            status=HTTP_400_BAD_REQUEST)
        return Response({'token': token},
                        status=HTTP_200_OK,
                        content_type="application/json")
Exemple #2
0
def backup_restore_select_multiple(request):
    if request.is_ajax():
        operator = Operators.login_required(request)
        if operator is None:
            # Operators.set_redirect_field_name(request, request.path)
            # return redirect(reverse("operators_signin"))
            return HttpResponse('signin', content_type='text/plain')
        else:
            auth_permissions = Operators.get_auth_permissions(operator)
            action = request.POST['action']
            ids = request.POST['ids']
            try:
                ids = ids.split(",")
            except (TypeError, ValueError, OverflowError):
                ids = None
            if action != '' and ids is not None:
                if action == 'delete':
                    if settings.ACCESS_PERMISSION_SETTINGS_VIEW in auth_permissions.values(
                    ):
                        for id in ids:
                            try:
                                print(action + ' ' + id)
                            except (TypeError, ValueError, OverflowError):
                                continue
                        messages.success(request, 'Deleted successfully.')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')

                return HttpResponse('success', content_type='text/plain')
            else:
                return HttpResponseBadRequest('Bad Request',
                                              content_type='text/plain')
    else:
        return HttpResponseForbidden('Forbidden', content_type='text/plain')
Exemple #3
0
def select_single(request):
    if request.is_ajax():
        operator = Operators.login_required(request)
        if operator is None:
            # Operators.set_redirect_field_name(request, request.path)
            # return redirect(reverse("operators_signin"))
            return HttpResponse('signin', content_type='text/plain')
        else:
            auth_permissions = Operators.get_auth_permissions(operator)
            action = request.POST['action']
            row_id = request.POST['id']
            if action != '' and row_id is not None:
                if action == 'delete':
                    if settings.ACCESS_PERMISSION_LOG_DELETE in auth_permissions.values(
                    ):
                        try:
                            model = Operator_Logs.objects.get(
                                operator_log_id=row_id)
                            model.delete()
                            messages.success(request, 'Deleted successfully.')
                        except (TypeError, ValueError, OverflowError,
                                Operator_Logs.DoesNotExist):
                            return HttpResponseBadRequest(
                                'Bad Request', content_type='text/plain')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')

                return HttpResponse('success', content_type='text/plain')
            else:
                return HttpResponseBadRequest('Bad Request',
                                              content_type='text/plain')
    else:
        return HttpResponseForbidden('Forbidden', content_type='text/plain')
def json_notifications(request):
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        objects = Notifications.objects.filter(notification_to_id=operator.operator_id)
        return HttpResponse(serializers.serialize("json", objects),
                            content_type="application/json")
Exemple #5
0
def temp_upload(request):
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        if request.POST:
            file_path = settings.MEDIA_ROOT + '/temp/' + request.POST['name']
            image_data = request.POST['data']
            Utils.save_image_base64(image_data, file_path)
            return HttpResponse('success')
        else:
            return HttpResponseBadRequest('no data')
Exemple #6
0
def json_operator_logs(request):
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_LOG_VIEW in auth_permissions.values():
            return HttpResponse(serializers.serialize(
                "json", Operator_Logs.objects.all()),
                                content_type="application/json")
        else:
            return HttpResponseForbidden('Forbidden',
                                         content_type='text/plain')
Exemple #7
0
def index(request):
    template_url = 'settings/index.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        return render(
            request, template_url, {
                'section': settings.BACKEND_SECTION_SETTINGS,
                'title': 'Settings',
                'name': 'settings',
                'operator': operator,
                'auth_permissions': auth_permissions,
            })
def operators(request):
    api_token = request.META.get('HTTP_AUTHORIZATION')
    session_token = "Bearer " + str(
        request.session.get(Operators.HASH_SESSION_KEY, None))
    if api_token != session_token:
        return Response({'error': 'Invalid API Token.'},
                        status=HTTP_400_BAD_REQUEST,
                        content_type="application/json")
    else:
        operator = Operators.login_required(request)
    if operator is None:
        return Response({'error': 'Session expired.'},
                        status=HTTP_400_BAD_REQUEST,
                        content_type="application/json")
    else:
        objects = Operators.objects.all()
        data = json.dumps([{
            'username': o.operator_username,
            'type': o.operator_type,
            'name': o.operator_name,
            'gender': o.operator_gender,
            'status': o.operator_status,
        } for o in objects])
        return Response(json.loads(data),
                        status=HTTP_200_OK,
                        content_type="application/json")
Exemple #9
0
def view_product_request_items(request, pk):
    template_url = 'product-request-items/index.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_ORDER_VIEW in auth_permissions.values():
            try:
                model = Product_Requests.objects.get(product_request_id=pk)

                search_form = ProductRequestItemSearchIndexForm(request.POST or None)
                objects = Product_Request_Items.objects.filter(
                    product_requests_product_request_id=model.product_request_id)

                if request.method == 'POST' and search_form.is_valid():
                    display_search = True
                    table = ProductRequestItemsTable(objects)
                else:
                    display_search = False
                    table = ProductRequestItemsTable(objects)

                table.set_auth_permissions(auth_permissions)
                return render(
                    request, template_url,
                    {
                        'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,
                        'title': Product_Requests.TITLE,
                        'name': Product_Requests.NAME,
                        'operator': operator,
                        'auth_permissions': auth_permissions,
                        'table': table,
                        'search_form': search_form,
                        'display_search': display_search,
                        'index_url': reverse("product_request_items_index", kwargs={'pk': pk}),
                        'select_multiple_url': reverse("product_request_items_select_multiple"),
                        'model': model,
                        'item_index_url': reverse("product_requests_view", kwargs={'pk': pk}),
                    }
                )

            except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):
                return HttpResponseNotFound('Not Found', content_type='text/plain')
        else:
            return HttpResponseForbidden('Forbidden', content_type='text/plain')
def select_single(request):
    if request.is_ajax():
        operator = Operators.login_required(request)
        if operator is None:
            # Operators.set_redirect_field_name(request, request.path)
            # return redirect(reverse("operators_signin"))
            return HttpResponse('signin', content_type='text/plain')
        else:
            auth_permissions = Operators.get_auth_permissions(operator)
            action = request.POST['action']
            id = request.POST['id']
            if action != '' and id is not None:
                if action == 'delete':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values(
                    ):
                        try:
                            model = Product_Request_Items.objects.get(
                                product_request_item_id=id)
                            product_request = Product_Requests.objects.get(
                                product_request_id=model.
                                product_requests_product_request_id)

                            Product_Request_Items.delete_product_request_item(
                                request, model, operator)

                            Product_Requests.update_grand_total(
                                request, product_request, operator)

                            messages.success(request,
                                             'Item removed successfully.')
                        except (TypeError, ValueError, OverflowError,
                                Product_Request_Items.DoesNotExist):
                            return HttpResponseBadRequest(
                                'Bad Request', content_type='text/plain')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')
                return HttpResponse('success', content_type='text/plain')
            else:
                return HttpResponseBadRequest('Bad Request',
                                              content_type='text/plain')
    else:
        return HttpResponseForbidden('Forbidden', content_type='text/plain')
def index_assets(request):
    template_url = 'products/index-assets.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_PRODUCT_VIEW in auth_permissions.values(
        ):
            search_form = ProductSearchIndexForm(request.POST or None)
            if request.method == 'POST' and search_form.is_valid():
                display_search = True
                objects = Products.objects.filter(
                    product_type=Products.TYPE_ASSET).order_by(
                        'product_tag', 'product_title')
                table = ProductAssetsTable(objects)
            else:
                display_search = False
                objects = Products.objects.filter(
                    product_type=Products.TYPE_ASSET).order_by(
                        'product_tag', 'product_title')
                table = ProductAssetsTable(objects)

            table.set_auth_permissions(auth_permissions)
            return render(
                request, template_url, {
                    'section': settings.BACKEND_SECTION_STOCK_ALL_ASSETS,
                    'title': Products.TITLE,
                    'name': Products.NAME,
                    'operator': operator,
                    'auth_permissions': auth_permissions,
                    'table': table,
                    'search_form': search_form,
                    'display_search': display_search,
                    'index_url': reverse("products_index_assets"),
                    'select_multiple_url': '#',
                })
        else:
            return HttpResponseForbidden('Forbidden',
                                         content_type='text/plain')
Exemple #12
0
def view(request, pk):
    template_url = 'operator_logs/view.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_LOG_VIEW in auth_permissions.values():
            try:
                model = Operator_Logs.objects.get(operator_log_id=pk)
                model.operator_log_updated_at = Utils.get_convert_datetime(
                    model.operator_log_updated_at, settings.TIME_ZONE,
                    settings.APP_CONSTANT_DISPLAY_TIME_ZONE
                ) + ' ' + settings.APP_CONSTANT_DISPLAY_TIME_ZONE_INFO
                return render(
                    request, template_url, {
                        'section':
                        settings.BACKEND_SECTION_OPERATOR_LOGS,
                        'title':
                        Operator_Logs.TITLE,
                        'name':
                        Operator_Logs.NAME,
                        'operator':
                        operator,
                        'auth_permissions':
                        auth_permissions,
                        'model':
                        model,
                        'index_url':
                        reverse("operator_logs_index"),
                        'select_single_url':
                        reverse("operator_logs_select_single"),
                    })
            except (TypeError, ValueError, OverflowError,
                    Operator_Logs.DoesNotExist):
                return HttpResponseNotFound('Not Found',
                                            content_type='text/plain')
        else:
            return HttpResponseForbidden('Forbidden',
                                         content_type='text/plain')
Exemple #13
0
def select_multiple(request):
    if request.is_ajax():
        operator = Operators.login_required(request)
        if operator is None:
            # Operators.set_redirect_field_name(request, request.path)
            # return redirect(reverse("operators_signin"))
            return HttpResponse('signin', content_type='text/plain')
        else:
            auth_permissions = Operators.get_auth_permissions(operator)
            action = request.POST['action']
            ids = request.POST['ids']
            try:
                ids = ids.split(",")
            except(TypeError, ValueError, OverflowError):
                ids = None
            if action != '' and ids is not None:
                return HttpResponse('success', content_type='text/plain')
            else:
                return HttpResponseBadRequest('Bad Request', content_type='text/plain')
    else:
        return HttpResponseForbidden('Forbidden', content_type='text/plain')
def index(request):
    template_url = 'notifications/index.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        search_form = NotificationSearchIndexForm(request.POST or None)
        if request.method == 'POST' and search_form.is_valid():
            display_search = True
            objects = Notifications.objects.filter(notification_to_id=operator.operator_id).order_by(
                '-notification_created_at')
            objects = Operators.objects.order_by('operator_name').all()

            table = NotificationsTable(objects)
        else:
            display_search = False
            objects = Notifications.objects.filter(notification_to_id=operator.operator_id).order_by(
                '-notification_created_at')
            table = NotificationsTable(objects)

        table.set_auth_permissions(auth_permissions)
        return render(
            request, template_url,
            {
                'section': settings.BACKEND_SECTION_NOTIFICATIONS,
                'title': Notifications.TITLE,
                'name': Notifications.NAME,
                'operator': operator,
                'auth_permissions': auth_permissions,
                'table': table,
                'search_form': search_form,
                'display_search': display_search,
                'index_url': reverse("notifications_index"),
            }
        )
Exemple #15
0
def index(request):
    template_url = 'operator_logs/index.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_LOG_VIEW in auth_permissions.values():
            table = OperatorLogsTable(
                Operator_Logs.objects.all().order_by('-operator_log_id')[:100],
                Operators.get_auth_permissions(operator))
            # [:1000]
            table.set_auth_permissions(auth_permissions)
            return render(
                request, template_url, {
                    'section':
                    settings.BACKEND_SECTION_OPERATOR_LOGS,
                    'title':
                    Operator_Logs.TITLE,
                    'name':
                    Operator_Logs.NAME,
                    'operator':
                    operator,
                    'auth_permissions':
                    auth_permissions,
                    'table':
                    table,
                    'index_url':
                    reverse("operator_logs_index"),
                    'select_multiple_url':
                    reverse("operator_logs_select_multiple"),
                })
        else:
            return HttpResponseForbidden('Forbidden',
                                         content_type='text/plain')
Exemple #16
0
def update(request, pk):
    template_url = 'product-requests/update.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():
            try:
                model = Product_Requests.objects.get(product_request_id=pk)
                if request.method == 'POST':

                    form = ProductRequestUpdateForm(request.POST)

                    # noinspection PyArgumentList
                    if form.is_valid():
                        model.product_request_project = form.cleaned_data['product_request_project']
                        model.product_request_details = form.cleaned_data['product_request_details']

                        model.product_request_updated_at = Utils.get_current_datetime_utc()
                        model.product_request_updated_id = operator.operator_id
                        model.product_request_updated_by = operator.operator_name
                        model.product_request_updated_department = operator.operator_department
                        model.product_request_updated_role = operator.operator_role
                        model.save()

                        messages.success(request, 'Updated successfully.')
                        return redirect(reverse("product_requests_view", args=[model.product_request_id]))
                    else:
                        return render(
                            request, template_url,
                            {
                                'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,
                                'title': Product_Requests.TITLE,
                                'name': Product_Requests.NAME,
                                'operator': operator,
                                'auth_permissions': auth_permissions,
                                'form': form,
                                'model': model,
                                'index_url': reverse("product_requests_index"),
                            }
                        )
                else:
                    form = ProductRequestUpdateForm(
                        initial={
                            'product_request_project': model.product_request_project,
                            'product_request_details': model.product_request_details,
                        }
                    )

                return render(
                    request, template_url,
                    {
                        'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,
                        'title': Product_Requests.TITLE,
                        'name': Product_Requests.NAME,
                        'operator': operator,
                        'auth_permissions': auth_permissions,
                        'form': form,
                        'model': model,
                        'index_url': reverse("product_requests_index"),
                    }
                )
            except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):
                return HttpResponseNotFound('Not Found', content_type='text/plain')
        else:
            return HttpResponseForbidden('Forbidden', content_type='text/plain')
def create(request, order_id):
    template_url = 'order-items/create.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_ORDER_CREATE in auth_permissions.values(
        ):
            # try:
            order = Orders.objects.get(order_id=order_id)
            if request.method == 'POST':

                form = OrderItemCreateForm(request.POST)
                # noinspection PyArgumentList
                if form.is_valid():
                    model = Order_Items()
                    model.orders_order_id = order_id

                    title = 'unknown'
                    type = form.cleaned_data['type']
                    model.order_item_type_id = 0
                    if type == 'service':
                        title = form.cleaned_data['title_service']
                    if type == 'goods':
                        type_id = form.cleaned_data['title_goods']
                        model.order_item_type_id = type_id
                        product = Products.objects.get(product_id=type_id)
                        title = product.product_title
                    if type == 'asset':
                        type_id = form.cleaned_data['title_asset']
                        model.order_item_type_id = type_id
                        product = Products.objects.get(product_id=type_id)
                        title = product.product_title

                    model.order_item_type = type
                    model.order_item_title = title
                    model.order_item_sub_title = ''
                    model.order_item_quantity_ordered = form.cleaned_data[
                        'quantity_ordered']
                    model.order_item_quantity_unit = form.cleaned_data[
                        'quantity_unit']
                    model.order_item_unit_price = form.cleaned_data[
                        'unit_price']
                    model.order_item_total_price = model.order_item_quantity_ordered * model.order_item_unit_price
                    model.order_item_usaid_approval = 0

                    model.order_item_created_at = Utils.get_current_datetime_utc(
                    )
                    model.order_item_created_id = operator.operator_id
                    model.order_item_created_by = operator.operator_name
                    model.order_item_created_department = operator.operator_department
                    model.order_item_created_role = operator.operator_role

                    model.order_item_updated_at = Utils.get_current_datetime_utc(
                    )
                    model.order_item_updated_id = operator.operator_id
                    model.order_item_updated_by = operator.operator_name
                    model.order_item_updated_department = operator.operator_department
                    model.order_item_updated_role = operator.operator_role

                    model.order_item_received_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
                    model.order_item_received_id = ''
                    model.order_item_received_by = ''
                    model.order_item_received_department = ''
                    model.order_item_received_role = ''

                    model.order_item_status = Orders.STATUS_PENDING
                    # noinspection PyCallByClass,PyTypeChecker
                    model.save('Created')

                    Orders.update_grand_total(request, order, operator)

                    messages.success(request, 'Item added successfully.')
                    return redirect(reverse("orders_view", args=[order_id]))
                else:
                    error_string = ' '.join([
                        ' '.join(x for x in l)
                        for l in list(form.errors.values())
                    ])
                    messages.error(request, '' + error_string)
                    return redirect(reverse("orders_view", args=[order_id]))

            else:
                form = OrderItemCreateForm(
                    initial={
                        'order_id': order.order_code,
                        'title': '',
                        'duration': 0,
                        'unit_price': 0,
                        'currency': Order_Items.CURRENCY_RWF,
                        'quantity_ordered': 0,
                        'quantity_unit': '',
                    })

            return render(
                request, template_url, {
                    'section':
                    settings.BACKEND_SECTION_PROCUREMENT_ALL_REQUESTS,
                    'title': Order_Items.TITLE,
                    'name': Order_Items.NAME,
                    'operator': operator,
                    'auth_permissions': auth_permissions,
                    'form': form,
                })
        # except(TypeError, ValueError, OverflowError, Orders.DoesNotExist, Order_Items.DoesNotExist):
        #     return HttpResponseNotFound('Not Found', content_type='text/plain')
        else:
            return HttpResponseForbidden('Forbidden',
                                         content_type='text/plain')
def create(request, id):
    template_url = 'product-request-items/create.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_ORDER_CREATE in auth_permissions.values(
        ):
            try:
                product_request = Product_Requests.objects.get(
                    product_request_id=id)
                if request.method == 'POST':

                    form = ProductRequestItemCreateForm(request.POST)
                    # noinspection PyArgumentList
                    if form.is_valid():
                        model = Product_Request_Items()
                        model.product_requests_product_request_id = product_request.product_request_id
                        model.products_product_id = form.cleaned_data[
                            'products_product_id']

                        product = Products.objects.get(
                            product_id=model.products_product_id)

                        model.product_request_item_product_type = product.product_type
                        model.product_request_item_product_code = product.product_code
                        model.product_request_item_product_tag = product.product_tag
                        model.product_request_item_product_category = product.product_category
                        model.product_request_item_product_title = product.product_title
                        model.product_request_item_product_sub_title = product.product_sub_title
                        model.product_request_item_product_quantity_initial = 0
                        model.product_request_item_product_quantity_ordered = form.cleaned_data[
                            'product_request_item_product_quantity_ordered']
                        model.product_request_item_product_quantity_balance = 0
                        model.product_request_item_product_quantity_unit = product.product_quantity_unit

                        model.product_request_item_created_at = Utils.get_current_datetime_utc(
                        )
                        model.product_request_item_created_id = operator.operator_id
                        model.product_request_item_created_by = operator.operator_name
                        model.product_request_item_created_department = operator.operator_department
                        model.product_request_item_created_role = operator.operator_role

                        model.product_request_item_updated_at = Utils.get_current_datetime_utc(
                        )
                        model.product_request_item_updated_id = operator.operator_id
                        model.product_request_item_updated_by = operator.operator_name
                        model.product_request_item_updated_department = operator.operator_department
                        model.product_request_item_updated_role = operator.operator_role

                        model.product_request_item_received_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
                        model.product_request_item_received_id = ''
                        model.product_request_item_received_by = ''
                        model.product_request_item_received_department = ''
                        model.product_request_item_received_role = ''

                        model.product_request_item_status = Product_Requests.STATUS_PENDING
                        # noinspection PyCallByClass,PyTypeChecker
                        model.save('Created')

                        Product_Requests.update_grand_total(
                            request, product_request, operator)

                        messages.success(request, 'Item added successfully.')
                        return redirect(
                            reverse("product_requests_view",
                                    args=[product_request.product_request_id]))
                    else:
                        error_string = ' '.join([
                            ' '.join(x for x in l)
                            for l in list(form.errors.values())
                        ])
                        messages.error(request, '' + error_string)
                        return redirect(
                            reverse("product_requests_view",
                                    args=[product_request.product_request_id]))

                else:
                    form = ProductRequestItemCreateForm(
                        initial={
                            'product_request_id':
                            product_request.product_request_code,
                            'products_product_id': '',
                            'product_request_item_product_quantity_ordered': 0,
                        })

                return render(
                    request, template_url, {
                        'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,
                        'title': Product_Request_Items.TITLE,
                        'name': Product_Request_Items.NAME,
                        'operator': operator,
                        'auth_permissions': auth_permissions,
                        'form': form,
                    })
            except (TypeError, ValueError, OverflowError,
                    Product_Requests.DoesNotExist,
                    Product_Request_Items.DoesNotExist):
                return HttpResponseNotFound('Not Found',
                                            content_type='text/plain')
        else:
            return HttpResponseForbidden('Forbidden',
                                         content_type='text/plain')
Exemple #19
0
def backup_restore(request):
    template_url = 'settings/backup-restore.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_SETTINGS_VIEW in auth_permissions.values(
        ):

            objects = []
            files = []
            for filename in os.listdir('backups'):
                filepath = os.path.join(settings.BASE_DIR,
                                        'backups/') + filename
                f = open(filepath, 'r')
                file = File(f)
                (mode, ino, dev, nlink, uid, gid, size, atime, mtime,
                 ctime) = os.stat(filepath)
                filename, file_extension = os.path.splitext(filepath)
                files.append(file)
                print(mode, ino, dev, nlink, uid, gid, size, atime, mtime,
                      ctime)
                print("last modified: %s" % time.ctime(mtime))
                print("size: %s" % os.path.getsize(filepath))
                f.close()
                if file_extension == '.bz2':
                    objects.append(
                        Backups(
                            backup_file_name=os.path.basename(filepath),
                            backup_file_size=Utils.bytes_2_human_readable(
                                os.path.getsize(filepath)),
                            backup_file_created_at=mtime,
                            backup_file_updated_at=mtime,
                        ))

            table = BackupsTable(objects)

            table.set_auth_permissions(auth_permissions)
            return render(
                request, template_url, {
                    'section':
                    settings.BACKEND_SECTION_SETTINGS,
                    'title':
                    Backups.TITLE,
                    'name':
                    Backups.NAME,
                    'operator':
                    operator,
                    'auth_permissions':
                    auth_permissions,
                    'table':
                    table,
                    'index_url':
                    reverse("backup_restore"),
                    'select_single_url':
                    reverse("backup_restore_select_single"),
                    'select_multiple_url':
                    reverse("backup_restore_select_multiple"),
                })
        else:
            return HttpResponseForbidden('Forbidden',
                                         content_type='text/plain')
def select_multiple(request):
    if request.is_ajax():
        operator = Operators.login_required(request)
        if operator is None:
            # Operators.set_redirect_field_name(request, request.path)
            # return redirect(reverse("operators_signin"))
            return HttpResponse('signin', content_type='text/plain')
        else:
            auth_permissions = Operators.get_auth_permissions(operator)
            action = request.POST['action']
            ids = request.POST['ids']
            try:
                ids = ids.split(",")
            except (TypeError, ValueError, OverflowError):
                ids = None
            if action != '' and ids is not None:
                if action == 'order-item-received':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values(
                    ):
                        for id in ids:
                            try:
                                model = Product_Request_Items.objects.get(
                                    product_request_item_id=id)
                                if model.product_request_item_status == Product_Request_Items.STATUS_PENDING:
                                    try:
                                        product = Products.objects.get(
                                            product_id=model.
                                            products_product_id)

                                        model.product_request_item_product_quantity_initial = product.product_quantity_available

                                        product.product_quantity_available = product.product_quantity_available - model.product_request_item_product_quantity_ordered

                                        model.product_request_item_product_quantity_balance = product.product_quantity_available

                                        product.product_updated_at = Utils.get_current_datetime_utc(
                                        )
                                        product.product_updated_id = operator.operator_id
                                        product.product_updated_by = operator.operator_name
                                        product.product_updated_department = operator.operator_department
                                        product.product_updated_role = operator.operator_role
                                        product.save()
                                    except (Product_Requests.DoesNotExist,
                                            Products.DoesNotExist):
                                        print(
                                            'Product Request does not exist.')

                                    model.product_request_item_received_at = Utils.get_current_datetime_utc(
                                    )
                                    model.product_request_item_received_id = operator.operator_id
                                    model.product_request_item_received_by = operator.operator_name
                                    model.product_request_item_received_department = operator.operator_department
                                    model.product_request_item_received_role = operator.operator_role
                                    model.product_request_item_status = Product_Request_Items.STATUS_RECEIVED
                                    model.save()

                            except (TypeError, ValueError, OverflowError,
                                    Product_Request_Items.DoesNotExist):
                                continue
                        messages.success(request, 'Updated successfully.')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')
                if action == 'order-item-pending':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values(
                    ):
                        for id in ids:
                            try:
                                model = Product_Request_Items.objects.get(
                                    product_request_item_id=id)
                                if model.product_request_item_status == Product_Request_Items.STATUS_RECEIVED:
                                    try:
                                        product = Products.objects.get(
                                            product_id=model.
                                            products_product_id)

                                        model.product_request_item_product_quantity_initial = 0

                                        product.product_quantity_available = product.product_quantity_available + model.product_request_item_product_quantity_ordered

                                        model.product_request_item_product_quantity_balance = 0

                                        product.product_updated_at = Utils.get_current_datetime_utc(
                                        )
                                        product.product_updated_id = operator.operator_id
                                        product.product_updated_by = operator.operator_name
                                        product.product_updated_department = operator.operator_department
                                        product.product_updated_role = operator.operator_role
                                        product.save()
                                    except (Product_Requests.DoesNotExist,
                                            Products.DoesNotExist):
                                        print('Product Request not exist.')

                                    model.product_request_item_received_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
                                    model.product_request_item_received_id = ''
                                    model.product_request_item_received_by = ''
                                    model.product_request_item_received_department = ''
                                    model.product_request_item_received_role = ''
                                    model.product_request_item_status = Product_Request_Items.STATUS_PENDING
                                    model.save()

                            except (TypeError, ValueError, OverflowError,
                                    Product_Request_Items.DoesNotExist):
                                continue
                        messages.success(request, 'Updated successfully.')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')

                return HttpResponse('success', content_type='text/plain')
            else:
                return HttpResponseBadRequest('Bad Request',
                                              content_type='text/plain')
    else:
        return HttpResponseForbidden('Forbidden', content_type='text/plain')
def import_excel(request):
    template_url = 'products/import-excel.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_OPERATOR_UPDATE in auth_permissions.values(
        ):
            if operator.operator_type != Operators.TYPE_SUPER_ADMIN:
                return HttpResponseForbidden('Forbidden',
                                             content_type='text/plain')
            else:
                if request.method == 'POST':
                    form = ProductExcelImportForm(request.POST, request.FILES)
                    if form.is_valid():
                        if 'excel_file' in request.FILES and \
                                request.FILES['excel_file']:
                            excel_file = form.cleaned_data['excel_file']
                            import pandas as pd
                            df = pd.read_excel(excel_file)
                            matrix = df.values
                            df = pd.DataFrame(df)
                            error = ''
                            success = 0
                            failed = 0
                            for index, row in df.iterrows():
                                print(index, row)
                                try:
                                    type = row['type']
                                    tag = row['tag']
                                    title = row['title']
                                    category = row['category']

                                    fail = False

                                    try:
                                        product = Products.objects.get(
                                            product_tag=tag)
                                    except Products.DoesNotExist:
                                        product = None

                                    if product is None:
                                        product = Products()
                                        product.product_code = Products.generate_random_number(
                                            'product_code', 8)
                                        product.product_sub_title = ''
                                        product.product_quantity_available = 0
                                        product.product_quantity_unit = ''

                                    product.product_type = type
                                    product.product_tag = tag
                                    product.product_category = category
                                    product.product_title = title

                                    product.product_updated_at = Utils.get_current_datetime_utc(
                                    )
                                    product.product_updated_id = operator.operator_id
                                    product.product_updated_by = operator.operator_name
                                    product.product_updated_department = operator.operator_department
                                    product.product_updated_role = operator.operator_role
                                    product.save()

                                    success = success + 1

                                except Exception as e:
                                    failed = failed + 1
                                    error = error + " <br> " + 'Error - [Row: ' + str(
                                        index) + '] ' + str(e)

                            message = 'Success: ' + str(
                                success) + ', Failed: ' + str(failed)
                            message = message + error
                            messages.warning(request, message)

                            form = ProductExcelImportForm()

                            return render(
                                request, template_url, {
                                    'section':
                                    settings.BACKEND_SECTION_SETTINGS,
                                    'title': Products.TITLE,
                                    'name': Products.NAME,
                                    'operator': operator,
                                    'auth_permissions': auth_permissions,
                                    'form': form,
                                })
                        else:
                            messages.error(
                                request, 'Error: Select excel file to import.')
                            return render(
                                request, template_url, {
                                    'section':
                                    settings.BACKEND_SECTION_SETTINGS,
                                    'title': Products.TITLE,
                                    'name': Products.NAME,
                                    'operator': operator,
                                    'auth_permissions': auth_permissions,
                                    'form': form,
                                })
                    else:
                        messages.error(request, 'Error: invalid form inputs.')
                        return render(
                            request, template_url, {
                                'section': settings.BACKEND_SECTION_SETTINGS,
                                'title': Products.TITLE,
                                'name': Products.NAME,
                                'operator': operator,
                                'auth_permissions': auth_permissions,
                                'form': form,
                            })
                else:
                    form = ProductExcelImportForm()

                return render(
                    request, template_url, {
                        'section': settings.BACKEND_SECTION_SETTINGS,
                        'title': Products.TITLE,
                        'name': Products.NAME,
                        'operator': operator,
                        'auth_permissions': auth_permissions,
                        'form': form,
                    })
        else:
            return HttpResponseForbidden('Forbidden',
                                         content_type='text/plain')
def index_inventory_assets(request):
    template_url = 'products/index-inventory-assets.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_INVENTORY_VIEW in auth_permissions.values(
        ):
            search_form = ProductInventorySearchIndexForm(request.POST or None)
            if request.method == 'POST' and search_form.is_valid():
                display_search = True
                objects = Products.objects.all()
                objects = objects.filter(product_type=Products.TYPE_ASSET)
                objects = objects.order_by('product_tag', 'product_title')

                results = []
                for item in objects:
                    item.product_quantity_initial = 0

                    item.product_quantity_in = 0
                    inventory_items = Inventory_Items.objects.filter(
                        products_product_id=item.product_id)
                    for inventory_item in inventory_items:
                        item.product_quantity_in = item.product_quantity_in + inventory_item.inventory_item_product_quantity_ordered

                    item.product_quantity_out = 0
                    product_request_items = Product_Request_Items.objects.all()
                    product_request_items = product_request_items.filter(
                        products_product_id=item.product_id,
                        product_request_item_status=Product_Request_Items.
                        STATUS_RECEIVED)
                    for product_request_item in product_request_items:
                        item.product_quantity_out = item.product_quantity_out + product_request_item.product_request_item_product_quantity_ordered

                    item.product_quantity_final = item.product_quantity_available
                    results.append(item)

                table = ProductAssetsInventoryTable(objects)
            else:
                display_search = False
                objects = Products.objects.all()
                objects = objects.filter(product_type=Products.TYPE_ASSET)
                objects = objects.order_by('product_tag', 'product_title')

                results = []
                for item in objects:
                    item.product_quantity_initial = 0

                    item.product_quantity_in = 0
                    inventory_items = Inventory_Items.objects.filter(
                        products_product_id=item.product_id)
                    for inventory_item in inventory_items:
                        item.product_quantity_in = item.product_quantity_in + inventory_item.inventory_item_product_quantity_ordered

                    item.product_quantity_out = 0
                    product_request_items = Product_Request_Items.objects.all()
                    product_request_items = product_request_items.filter(
                        products_product_id=item.product_id,
                        product_request_item_status=Product_Request_Items.
                        STATUS_RECEIVED)
                    for product_request_item in product_request_items:
                        item.product_quantity_out = item.product_quantity_out + product_request_item.product_request_item_product_quantity_ordered

                    item.product_quantity_final = item.product_quantity_available
                    results.append(item)

                table = ProductAssetsInventoryTable(results)

            table.set_auth_permissions(auth_permissions)
            return render(
                request, template_url, {
                    'section': settings.BACKEND_SECTION_INVENTORY_ASSETS,
                    'title': Products.TITLE,
                    'name': Products.NAME,
                    'operator': operator,
                    'auth_permissions': auth_permissions,
                    'table': table,
                    'search_form': search_form,
                    'display_search': display_search,
                    'index_url': reverse("products_index_inventory_assets"),
                    'select_multiple_url': '#',
                })
        else:
            return HttpResponseForbidden('Forbidden',
                                         content_type='text/plain')
Exemple #23
0
def backup_restore_select_single(request):
    if request.is_ajax():
        operator = Operators.login_required(request)
        if operator is None:
            # Operators.set_redirect_field_name(request, request.path)
            # return redirect(reverse("operators_signin"))
            return HttpResponse('signin', content_type='text/plain')
        else:
            auth_permissions = Operators.get_auth_permissions(operator)
            action = request.POST['action']
            id = request.POST['id']
            if action != '' and id is not None:
                if action == 'backup':
                    if settings.ACCESS_PERMISSION_SETTINGS_VIEW in auth_permissions.values(
                    ):
                        try:
                            call_command('archive')
                            messages.success(request,
                                             'Backup taken successfully.')
                        except (TypeError, ValueError, OverflowError):
                            return HttpResponseBadRequest(
                                'Bad Request', content_type='text/plain')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')
                if action == 'delete':
                    if settings.ACCESS_PERMISSION_SETTINGS_VIEW in auth_permissions.values(
                    ):
                        print(action + '-' + id)
                        filepath = os.path.join(settings.BASE_DIR,
                                                'backups/') + id
                        print(filepath)
                        if os.path.isfile(filepath):
                            os.remove(filepath)
                        messages.success(request,
                                         'Backup file deleted successfully.')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')

                return HttpResponse('success', content_type='text/plain')
            else:
                return HttpResponseBadRequest('Bad Request',
                                              content_type='text/plain')
    else:
        operator = Operators.login_required(request)
        if operator is None:
            Operators.set_redirect_field_name(request, request.path)
            return redirect(reverse("operators_signin"))
        else:
            auth_permissions = Operators.get_auth_permissions(operator)
            action = request.POST['action']
            id = request.POST['id']
            if action != '' and id is not None:
                if action == 'download':
                    if settings.ACCESS_PERMISSION_SETTINGS_VIEW in auth_permissions.values(
                    ):
                        print(action + '-' + id)
                        filepath = os.path.join(settings.BASE_DIR,
                                                'backups/') + id
                        print(filepath)
                        filename, file_extension = os.path.splitext(filepath)
                        if file_extension == '.bz2' and os.path.exists(
                                filepath):
                            with open(filepath, 'rb') as fh:
                                response = HttpResponse(
                                    fh.read(),
                                    content_type="application/x-gzip")
                                response[
                                    'Content-Disposition'] = 'inline; filename=' + os.path.basename(
                                        filepath)
                                return response
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')
                return HttpResponse('success', content_type='text/plain')
            else:
                return HttpResponseBadRequest('Bad Request',
                                              content_type='text/plain')
Exemple #24
0
def select_single(request):
    if request.is_ajax():
        operator = Operators.login_required(request)
        if operator is None:
            # Operators.set_redirect_field_name(request, request.path)
            # return redirect(reverse("operators_signin"))
            return HttpResponse('signin', content_type='text/plain')
        else:
            auth_permissions = Operators.get_auth_permissions(operator)
            action = request.POST['action']
            id = request.POST['id']
            if action != '' and id is not None:
                if action == 'order-request':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():
                        try:
                            model = Product_Requests.objects.get(product_request_id=id)
                            if model.product_request_created_id == str(operator.operator_id):
                                model.product_request_requested_at = Utils.get_current_datetime_utc()
                                model.product_request_requested_id = operator.operator_id
                                model.product_request_requested_by = operator.operator_name
                                model.product_request_requested_department = operator.operator_department
                                model.product_request_requested_role = operator.operator_role
                                model.product_request_status = Product_Requests.STATUS_REQUESTED
                                model.save()

                                # sending notification to COP
                                operators = Operators.objects.filter(operator_role=Operators.ROLE_STOCK_ADMIN)
                                for item in operators:
                                    Notifications.add_notification(
                                        Notifications.TYPE_OPERATOR,
                                        operator.operator_id,
                                        Notifications.TYPE_OPERATOR,
                                        item.operator_id,
                                        Notifications.TYPE_PRODUCT_REQUEST,
                                        model.product_request_id,
                                        "A stock request has been sent for approval.",
                                        "/backend/product-requests/view/" + str(
                                            model.product_request_id) + "/"
                                    )

                                messages.success(request, 'Stock requested successfully.')
                            else:
                                messages.success(request, 'Forbidden')
                        except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):
                            return HttpResponseBadRequest('Bad Request', content_type='text/plain')
                    else:
                        return HttpResponseForbidden('Forbidden', content_type='text/plain')
                if action == 'order-review':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():
                        try:
                            model = Product_Requests.objects.get(product_request_id=id)
                            model.product_request_reviewed_at = Utils.get_current_datetime_utc()
                            model.product_request_reviewed_id = operator.operator_id
                            model.product_request_reviewed_by = operator.operator_name
                            model.product_request_reviewed_department = operator.operator_department
                            model.product_request_reviewed_role = operator.operator_role
                            model.product_request_status = Product_Requests.STATUS_REVIEWED
                            model.save()

                            # sending notification
                            operators = Operators.objects.filter(operator_id=model.product_request_requested_id)
                            for item in operators:
                                Notifications.add_notification(
                                    Notifications.TYPE_OPERATOR,
                                    operator.operator_id,
                                    Notifications.TYPE_OPERATOR,
                                    item.operator_id,
                                    Notifications.TYPE_PRODUCT_REQUEST,
                                    model.product_request_id,
                                    "Your stock request has been reviewed.",
                                    "/backend/product-requests/view/" + str(
                                        model.product_request_id) + "/"
                                )

                            messages.success(request, 'Stock reviewed successfully.')

                        except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):
                            return HttpResponseBadRequest('Bad Request', content_type='text/plain')
                    else:
                        return HttpResponseForbidden('Forbidden', content_type='text/plain')
                if action == 'order-approve':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():
                        try:
                            model = Product_Requests.objects.get(product_request_id=id)
                            model.product_request_approved_updated_at = Utils.get_current_datetime_utc()
                            model.product_request_approved_updated_id = operator.operator_id
                            model.product_request_approved_updated_by = operator.operator_name
                            model.product_request_approved_updated_department = operator.operator_department
                            model.product_request_approved_updated_role = operator.operator_role
                            model.product_request_status = Product_Requests.STATUS_APPROVED
                            model.save()

                            # sending notification
                            operators = Operators.objects.filter(operator_id=model.product_request_requested_id)
                            for item in operators:
                                Notifications.add_notification(
                                    Notifications.TYPE_OPERATOR,
                                    operator.operator_id,
                                    Notifications.TYPE_OPERATOR,
                                    item.operator_id,
                                    Notifications.TYPE_PRODUCT_REQUEST,
                                    model.product_request_id,
                                    "Your stock request has been approved.",
                                    "/backend/product-requests/view/" + str(
                                        model.product_request_id) + "/"
                                )

                            messages.success(request, 'Stock approved successfully.')

                        except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):
                            return HttpResponseBadRequest('Bad Request', content_type='text/plain')
                    else:
                        return HttpResponseForbidden('Forbidden', content_type='text/plain')
                if action == 'order-reject':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values():
                        try:
                            model = Product_Requests.objects.get(product_request_id=id)
                            model.product_request_approved_updated_at = Utils.get_current_datetime_utc()
                            model.product_request_approved_updated_id = operator.operator_id
                            model.product_request_approved_updated_by = operator.operator_name
                            model.product_request_approved_updated_department = operator.operator_department
                            model.product_request_approved_updated_role = operator.operator_role
                            model.product_request_status = Product_Requests.STATUS_REVIEWED
                            model.save()

                            # sending notification
                            operators = Operators.objects.filter(operator_id=model.product_request_requested_id)
                            for item in operators:
                                Notifications.add_notification(
                                    Notifications.TYPE_OPERATOR,
                                    operator.operator_id,
                                    Notifications.TYPE_OPERATOR,
                                    item.operator_id,
                                    Notifications.TYPE_PRODUCT_REQUEST,
                                    model.product_request_id,
                                    "Your stock request has been rejected.",
                                    "/backend/product-requests/view/" + str(
                                        model.product_request_id) + "/"
                                )

                            messages.success(request, 'Stock rejected successfully.')

                        except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):
                            return HttpResponseBadRequest('Bad Request', content_type='text/plain')
                    else:
                        return HttpResponseForbidden('Forbidden', content_type='text/plain')
                return HttpResponse('success', content_type='text/plain')
            else:
                return HttpResponseBadRequest('Bad Request', content_type='text/plain')
    else:
        return HttpResponseForbidden('Forbidden', content_type='text/plain')
def select_multiple(request):
    if request.is_ajax():
        operator = Operators.login_required(request)
        if operator is None:
            # Operators.set_redirect_field_name(request, request.path)
            # return redirect(reverse("operators_signin"))
            return HttpResponse('signin', content_type='text/plain')
        else:
            auth_permissions = Operators.get_auth_permissions(operator)
            action = request.POST['action']
            ids = request.POST['ids']
            try:
                ids = ids.split(",")
            except (TypeError, ValueError, OverflowError):
                ids = None
            if action != '' and ids is not None:
                if action == 'usaid-approve-yes':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values(
                    ):
                        for id in ids:
                            try:
                                model = Order_Items.objects.get(
                                    order_item_id=id)
                                model.order_item_usaid_approval = True
                                model.save()
                            except (TypeError, ValueError, OverflowError,
                                    Order_Items.DoesNotExist):
                                continue
                        messages.success(request, 'Updated successfully.')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')
                if action == 'usaid-approve-no':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values(
                    ):
                        for id in ids:
                            try:
                                model = Order_Items.objects.get(
                                    order_item_id=id)
                                model.order_item_usaid_approval = False
                                model.save()
                            except (TypeError, ValueError, OverflowError,
                                    Order_Items.DoesNotExist):
                                continue
                        messages.success(request, 'Updated successfully.')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')
                if action == 'order-item-received':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values(
                    ):
                        for id in ids:
                            try:
                                model = Order_Items.objects.get(
                                    order_item_id=id)
                                if model.order_item_status == Order_Items.STATUS_PENDING:
                                    if model.order_item_type == Order_Items.TYPE_SERVICE:
                                        model.order_item_received_at = Utils.get_current_datetime_utc(
                                        )
                                        model.order_item_received_id = operator.operator_id
                                        model.order_item_received_by = operator.operator_name
                                        model.order_item_received_department = operator.operator_department
                                        model.order_item_received_role = operator.operator_role
                                        model.order_item_status = Order_Items.STATUS_RECEIVED
                                        model.save()
                            except (TypeError, ValueError, OverflowError,
                                    Order_Items.DoesNotExist):
                                continue
                        messages.success(request, 'Updated successfully.')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')
                if action == 'order-item-pending':
                    if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values(
                    ):
                        for id in ids:
                            try:
                                model = Order_Items.objects.get(
                                    order_item_id=id)
                                if model.order_item_status == Order_Items.STATUS_RECEIVED:
                                    if model.order_item_type != Order_Items.TYPE_SERVICE:
                                        try:
                                            order = Orders.objects.get(
                                                order_id=model.orders_order_id)
                                            inventory = Inventory.objects.get(
                                                inventory_order_purchase_no=
                                                order.order_purchase_no)
                                            inventory_items = Inventory_Items.objects.filter(
                                                inventory_inventory_id=inventory
                                                .inventory_id)
                                            for inventory_item in inventory_items:
                                                try:
                                                    product = Products.objects.get(
                                                        product_id=inventory_item
                                                        .products_product_id)
                                                    product.product_quantity_available = product.product_quantity_available - inventory_item.inventory_item_product_quantity_ordered
                                                    product.product_updated_at = Utils.get_current_datetime_utc(
                                                    )
                                                    product.product_updated_id = operator.operator_id
                                                    product.product_updated_by = operator.operator_name
                                                    product.product_updated_department = operator.operator_department
                                                    product.product_updated_role = operator.operator_role
                                                    product.save()
                                                    inventory_item.delete()
                                                except Products.DoesNotExist:
                                                    inventory_item.delete()
                                                    continue
                                        except (Orders.DoesNotExist,
                                                Inventory.DoesNotExist):
                                            print(
                                                'Order or inventory does not exist.'
                                            )
                                    model.order_item_received_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
                                    model.order_item_received_id = ''
                                    model.order_item_received_by = ''
                                    model.order_item_received_department = ''
                                    model.order_item_received_role = ''
                                    model.order_item_status = Order_Items.STATUS_PENDING
                                    model.save()

                            except (TypeError, ValueError, OverflowError,
                                    Order_Items.DoesNotExist):
                                continue
                        messages.success(request, 'Updated successfully.')
                    else:
                        return HttpResponseForbidden('Forbidden',
                                                     content_type='text/plain')

                return HttpResponse('success', content_type='text/plain')
            else:
                return HttpResponseBadRequest('Bad Request',
                                              content_type='text/plain')
    else:
        return HttpResponseForbidden('Forbidden', content_type='text/plain')
Exemple #26
0
def create(request):
    template_url = 'product-requests/create.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_ORDER_CREATE in auth_permissions.values():
            if request.method == 'POST':

                form = ProductRequestCreateForm(request.POST)
                # noinspection PyArgumentList
                if form.is_valid():
                    model = Product_Requests()
                    model.product_request_code = Product_Requests.generate_random_number('product_request_code', 8)

                    model.product_request_project = form.cleaned_data['product_request_project']
                    model.product_request_details = form.cleaned_data['product_request_details']

                    model.product_request_no_of_items = 0

                    model.product_request_created_at = Utils.get_current_datetime_utc()
                    model.product_request_created_id = operator.operator_id
                    model.product_request_created_by = operator.operator_name
                    model.product_request_created_department = operator.operator_department
                    model.product_request_created_role = operator.operator_role

                    model.product_request_updated_at = Utils.get_current_datetime_utc()
                    model.product_request_updated_id = operator.operator_id
                    model.product_request_updated_by = operator.operator_name
                    model.product_request_updated_department = operator.operator_department
                    model.product_request_updated_role = operator.operator_role

                    model.product_request_requested_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
                    model.product_request_requested_id = ''
                    model.product_request_requested_by = ''
                    model.product_request_requested_department = ''
                    model.product_request_requested_role = ''

                    model.product_request_reviewed_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
                    model.product_request_reviewed_id = ''
                    model.product_request_reviewed_by = ''
                    model.product_request_reviewed_department = ''
                    model.product_request_reviewed_role = ''

                    model.product_request_approved_updated_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
                    model.product_request_approved_updated_id = ''
                    model.product_request_approved_updated_by = ''
                    model.product_request_approved_updated_department = ''
                    model.product_request_approved_updated_role = ''

                    model.product_request_closed_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
                    model.product_request_closed_id = ''
                    model.product_request_closed_by = ''
                    model.product_request_closed_department = ''
                    model.product_request_closed_role = ''

                    model.product_request_cancelled_at = settings.APP_CONSTANT_DEFAULT_DATETIME_VALUE
                    model.product_request_cancelled_id = ''
                    model.product_request_cancelled_by = ''
                    model.product_request_cancelled_department = ''
                    model.product_request_cancelled_role = ''

                    model.product_request_status = Product_Requests.STATUS_PENDING
                    # noinspection PyCallByClass,PyTypeChecker
                    model.save('Created')

                    messages.info(request,
                                  'Your stock request has been created successfully.')
                    return redirect(reverse("product_requests_view", args=[model.product_request_id]))
                else:
                    return render(
                        request, template_url,
                        {
                            'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,
                            'title': Product_Requests.TITLE,
                            'name': Product_Requests.NAME,
                            'operator': operator,
                            'auth_permissions': auth_permissions,
                            'form': form,
                            'index_url': reverse("product_requests_index"),
                        }
                    )
            else:
                form = ProductRequestCreateForm()

            return render(
                request, template_url,
                {
                    'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,
                    'title': Product_Requests.TITLE,
                    'name': Product_Requests.NAME,
                    'operator': operator,
                    'auth_permissions': auth_permissions,
                    'form': form,
                    'index_url': reverse("product_requests_index"),
                }
            )
        else:
            return HttpResponseForbidden('Forbidden', content_type='text/plain')
Exemple #27
0
def view(request, pk):
    template_url = 'product-requests/view.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_ORDER_VIEW in auth_permissions.values():
            try:
                model = Product_Requests.objects.get(product_request_id=pk)
                product_request_items = Product_Request_Items.objects.filter(
                    product_requests_product_request_id=pk).all()

                if model.product_request_created_id == str(
                        operator.operator_id) and model.product_request_status == Product_Requests.STATUS_PENDING:
                    template_url = 'product-requests/view-edit.html'

                display_level_approval = False

                timeline_notifications = []
                counter = -1
                if model.product_request_requested_id != '':
                    notification_timeline = NotificationsTimeline()
                    notification_timeline.message = 'Requested <small>by ' + model.product_request_requested_role + '</small>'
                    notification_timeline.datetime = Utils.get_convert_datetime(model.product_request_requested_at,
                                                                                settings.TIME_ZONE,
                                                                                settings.APP_CONSTANT_DISPLAY_TIME_ZONE) + ' ' + settings.APP_CONSTANT_DISPLAY_TIME_ZONE_INFO
                    timeline_notifications.append(notification_timeline)

                if model.product_request_reviewed_id != '':
                    notification_timeline = NotificationsTimeline()
                    notification_timeline.message = 'Reviewed <small>by ' + model.product_request_reviewed_role + '</small>'
                    notification_timeline.datetime = Utils.get_convert_datetime(model.product_request_reviewed_at,
                                                                                settings.TIME_ZONE,
                                                                                settings.APP_CONSTANT_DISPLAY_TIME_ZONE) + ' ' + settings.APP_CONSTANT_DISPLAY_TIME_ZONE_INFO
                    timeline_notifications.append(notification_timeline)

                if model.product_request_approved_updated_id != '':
                    notification_timeline = NotificationsTimeline()
                    notification_timeline.message = 'Approved <small>by ' + model.product_request_approved_updated_role + '</small>'
                    if model.product_request_status == Product_Requests.STATUS_REJECTED:
                        notification_timeline.message = 'Rejected <small>by ' + model.product_request_approved_updated_role + '</small>'
                    notification_timeline.datetime = Utils.get_convert_datetime(
                        model.product_request_approved_updated_at,
                        settings.TIME_ZONE,
                        settings.APP_CONSTANT_DISPLAY_TIME_ZONE) + ' ' + settings.APP_CONSTANT_DISPLAY_TIME_ZONE_INFO
                    timeline_notifications.append(notification_timeline)

                if model.product_request_status == Product_Requests.STATUS_REQUESTED:
                    notification_timeline = NotificationsTimeline()
                    model.product_request_readable_status = notification_timeline.message = "<b class='text-red'>Review pending from Stock Admin</b>"
                    notification_timeline.datetime = ''
                    timeline_notifications.append(notification_timeline)

                if model.product_request_status == Product_Requests.STATUS_REVIEWED:
                    notification_timeline = NotificationsTimeline()
                    model.product_request_readable_status = notification_timeline.message = "<b class='text-red'>Approval pending from Stock Admin</b>"
                    notification_timeline.datetime = ''
                    timeline_notifications.append(notification_timeline)

                if model.product_request_status == Product_Requests.STATUS_APPROVED:
                    notification_timeline = NotificationsTimeline()
                    model.product_request_readable_status = notification_timeline.message = "<b class='text-red'>Approved</b>"
                    notification_timeline.datetime = ''
                    timeline_notifications.append(notification_timeline)

                if model.product_request_status == Product_Requests.STATUS_REJECTED:
                    notification_timeline = NotificationsTimeline()
                    model.product_request_readable_status = notification_timeline.message = "<b class='text-red'>Rejected</b>"
                    notification_timeline.datetime = ''
                    timeline_notifications.append(notification_timeline)

                return render(
                    request, template_url,
                    {
                        'section': settings.BACKEND_SECTION_STOCK_ALL_REQUESTS,
                        'title': Product_Requests.TITLE,
                        'name': Product_Requests.NAME,
                        'operator': operator,
                        'auth_permissions': auth_permissions,
                        'model': model,
                        'index_url': reverse("product_requests_index"),
                        'select_single_url': reverse("product_requests_select_single"),
                        'product_request_items': product_request_items,
                        'product_request_items_size': product_request_items,
                        'item_index_url': reverse("product_requests_view", kwargs={'pk': pk}),
                        'item_select_single_url': reverse("product_request_items_select_single"),
                        'status_html_tag': Product_Requests.get_status_html_tag(model),
                        'display_level_approval': display_level_approval,
                        'timeline_notifications': timeline_notifications,
                    }
                )
            except(TypeError, ValueError, OverflowError, Product_Requests.DoesNotExist):
                return HttpResponseNotFound('Not Found', content_type='text/plain')
        else:
            return HttpResponseForbidden('Forbidden', content_type='text/plain')
def create(request, pk, action, ids):
    template_url = 'inventory-items/create.html'
    operator = Operators.login_required(request)
    if operator is None:
        Operators.set_redirect_field_name(request, request.path)
        return redirect(reverse("operators_signin"))
    else:
        auth_permissions = Operators.get_auth_permissions(operator)
        if settings.ACCESS_PERMISSION_ORDER_UPDATE in auth_permissions.values(
        ):
            # try:
            order = Orders.objects.get(order_id=pk)
            order_proposal = Order_Proposals.objects.get(
                order_proposal_id=order.order_proposal_id)
            try:
                ids = ids.split("-")
            except (TypeError, ValueError, OverflowError):
                ids = None
            if action != 'order-item-received' or ids is None:
                return HttpResponseNotFound('Not Found',
                                            content_type='text/plain')
            else:
                if request.method == 'POST':
                    form = InventoryItemCreateForm(request.POST)
                    # noinspection PyArgumentList
                    if form.is_valid():
                        inventory_item_voucher_reference = form.cleaned_data[
                            'inventory_item_voucher_reference']
                        inventory_item_location = form.cleaned_data[
                            'inventory_item_location']
                        inventory_item_equipment_holder_status = form.cleaned_data[
                            'inventory_item_equipment_holder_status']
                        inventory_item_staff_name = form.cleaned_data[
                            'inventory_item_staff_name']
                        inventory_item_room_number = form.cleaned_data[
                            'inventory_item_room_number']
                        inventory_item_disposal_date = form.cleaned_data[
                            'inventory_item_disposal_date']
                        inventory_item_verified_date = form.cleaned_data[
                            'inventory_item_verified_date']
                        inventory_item_present_condition = form.cleaned_data[
                            'inventory_item_present_condition']
                        inventory_item_remark = form.cleaned_data[
                            'inventory_item_remark']

                        try:
                            inventory = Inventory.objects.get(
                                inventory_order_purchase_no=order.
                                order_purchase_no)
                            inventory.inventory_order_proposal_id = order.order_proposal_id
                            inventory.inventory_order_proposal_supplier_title = order_proposal.order_proposal_supplier_title
                            inventory.inventory_updated_at = Utils.get_current_datetime_utc(
                            )
                            inventory.inventory_updated_id = operator.operator_id
                            inventory.inventory_updated_by = operator.operator_name
                            inventory.inventory_updated_department = operator.operator_department
                            inventory.inventory_updated_role = operator.operator_role
                            inventory.save()
                        except Inventory.DoesNotExist:
                            inventory = Inventory()
                            inventory.inventory_order_purchase_no = order.order_purchase_no
                            inventory.inventory_order_proposal_id = order.order_proposal_id
                            inventory.inventory_order_proposal_supplier_title = order_proposal.order_proposal_supplier_title
                            inventory.inventory_created_at = Utils.get_current_datetime_utc(
                            )
                            inventory.inventory_created_id = operator.operator_id
                            inventory.inventory_created_by = operator.operator_name
                            inventory.inventory_created_department = operator.operator_department
                            inventory.inventory_created_role = operator.operator_role
                            inventory.inventory_updated_at = Utils.get_current_datetime_utc(
                            )
                            inventory.inventory_updated_id = operator.operator_id
                            inventory.inventory_updated_by = operator.operator_name
                            inventory.inventory_updated_department = operator.operator_department
                            inventory.inventory_updated_role = operator.operator_role
                            inventory.save()

                        for id in ids:
                            try:
                                order_item = Order_Items.objects.get(
                                    order_item_id=id)
                                if order_item.order_item_status == Order_Items.STATUS_PENDING:
                                    if order_item.order_item_type != Order_Items.TYPE_SERVICE:
                                        order_item.order_item_received_at = Utils.get_current_datetime_utc(
                                        )
                                        order_item.order_item_received_id = operator.operator_id
                                        order_item.order_item_received_by = operator.operator_name
                                        order_item.order_item_received_department = operator.operator_department
                                        order_item.order_item_received_role = operator.operator_role
                                        order_item.order_item_status = Order_Items.STATUS_RECEIVED
                                        order_item.save()

                                        try:
                                            product = Products.objects.get(
                                                product_id=order_item.
                                                order_item_type_id)
                                            inventory_item = Inventory_Items()
                                            inventory_item.inventory_inventory_id = inventory.inventory_id
                                            inventory_item.products_product_id = order_item.order_item_type_id
                                            inventory_item.inventory_item_product_type = order_item.order_item_type
                                            inventory_item.inventory_item_product_code = product.product_code
                                            inventory_item.inventory_item_product_tag = product.product_tag
                                            inventory_item.inventory_item_product_category = product.product_category
                                            inventory_item.inventory_item_product_title = product.product_title
                                            inventory_item.inventory_item_product_sub_title = product.product_sub_title
                                            inventory_item.inventory_item_product_quantity_initial = product.product_quantity_available
                                            inventory_item.inventory_item_product_quantity_ordered = order_item.order_item_quantity_ordered
                                            inventory_item.inventory_item_product_quantity_balance = product.product_quantity_available + order_item.order_item_quantity_ordered
                                            inventory_item.inventory_item_product_quantity_unit = product.product_quantity_unit
                                            inventory_item.inventory_item_product_currency = order_item.order_item_currency
                                            inventory_item.inventory_item_product_unit_price = order_item.order_item_unit_price
                                            inventory_item.inventory_item_product_rate_price = 0
                                            inventory_item.inventory_item_product_usd_price = 0
                                            inventory_item.inventory_item_product_usaid_equipment_price = 0
                                            inventory_item.inventory_item_product_small_equipment_price = 0
                                            inventory_item.inventory_item_project = order.order_project_name
                                            inventory_item.inventory_item_voucher_reference = inventory_item_voucher_reference
                                            inventory_item.inventory_item_location = inventory_item_location
                                            inventory_item.inventory_item_equipment_holder_status = inventory_item_equipment_holder_status
                                            inventory_item.inventory_item_staff_name = inventory_item_staff_name
                                            inventory_item.inventory_item_room_number = inventory_item_room_number
                                            inventory_item.inventory_item_present_condition = inventory_item_present_condition
                                            inventory_item.inventory_item_disposal_date = inventory_item_disposal_date
                                            inventory_item.inventory_item_verified_date = inventory_item_verified_date
                                            inventory_item.inventory_item_remark = inventory_item_remark
                                            inventory_item.inventory_created_at = Utils.get_current_datetime_utc(
                                            )
                                            inventory_item.inventory_created_id = operator.operator_id
                                            inventory_item.inventory_created_by = operator.operator_name
                                            inventory_item.inventory_created_department = operator.operator_department
                                            inventory_item.inventory_created_role = operator.operator_role
                                            inventory_item.inventory_updated_at = Utils.get_current_datetime_utc(
                                            )
                                            inventory_item.inventory_updated_id = operator.operator_id
                                            inventory_item.inventory_updated_by = operator.operator_name
                                            inventory_item.inventory_updated_department = operator.operator_department
                                            inventory_item.inventory_updated_role = operator.operator_role
                                            inventory_item.save()

                                            product.product_quantity_available = product.product_quantity_available + order_item.order_item_quantity_ordered
                                            product.product_updated_at = Utils.get_current_datetime_utc(
                                            )
                                            product.product_updated_id = operator.operator_id
                                            product.product_updated_by = operator.operator_name
                                            product.product_updated_department = operator.operator_department
                                            product.product_updated_role = operator.operator_role
                                            product.save()

                                        except Products.DoesNotExist:
                                            continue

                            except Order_Items.DoesNotExist:
                                continue

                        messages.success(request, 'Updated successfully.')
                        return redirect(
                            reverse("order_items_index",
                                    args=[order.order_id]))
                    else:
                        error_string = ' '.join([
                            ' '.join(x for x in l)
                            for l in list(form.errors.values())
                        ])
                        messages.error(request, '' + error_string)
                        return redirect(
                            reverse("order_items_index",
                                    args=[order.order_id]))
                else:
                    form = InventoryItemCreateForm(
                        initial={
                            'inventory_order_purchase_no':
                            order.order_purchase_no,
                            'inventory_order_project_name':
                            order.order_project_name,
                        })

                return render(
                    request, template_url, {
                        'section':
                        settings.BACKEND_SECTION_PROCUREMENT_ALL_REQUESTS,
                        'title': Orders.TITLE,
                        'name': Orders.NAME,
                        'operator': operator,
                        'auth_permissions': auth_permissions,
                        'form': form,
                    })
        # except(TypeError, ValueError, OverflowError, Orders.DoesNotExist, Order_Proposals.DoesNotExist,
        #        Order_Proposals.DoesNotExist):
        #     return HttpResponseNotFound('Not Found', content_type='text/plain')
        else:
            return HttpResponseForbidden('Forbidden',
                                         content_type='text/plain')