summaryrefslogtreecommitdiff
path: root/inventory/views.py
blob: 1896f4cfc72bba0098bf2ee77bcc133a452d8d69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


# This file is part of the Taler Codeless Merchant.
# (C) 2018 GNUnet e.V.
#
# The Taler Codeless Merchant is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# The Taler Codeless Merchant is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License
# for more details.
#
# You should have received a copy of the GNU Affero General Public License along
# with the Taler Codeless Merchant.  If not, see <https://www.gnu.org/licenses/>.
#
# @author Shivam Kohli


from inventory.forms import SignUpForm, MerchantDetailForm, LoginForm, DocumentForm
from inventory.models import Merchant, Product, Order
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.core.urlresolvers import resolve
import requests
from urllib.parse import urljoin
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
from django.http import JsonResponse


BACKEND_URL = "https://backend.demo.taler.net/"


def fulfillment(request):
    """ This function is responsible for redirecting to a
    page after successfully payment is done.
    For digital Inventory is displays the required document
    on payment completion.
    """
    order_id = request.GET.get('order_id')
    if order_id is None:
        return HttpResponse("Error while loading the page")
    order_instance = Order.objects.get(order_id=order_id)
    product = order_instance.product_id.all()
    for item in range(len(product)):
        if product[item].document:
            filename = product[item].document.file.name.split('/')[-1]
            file = product[item].document.file
            response = HttpResponse(file, content_type='application/pdf')
            response['Content-Disposition'] = 'inline; filename=%s' % filename
            return response
        else:
            return render(request, 'inventory/fulfillment.html')


def shipment(request):
    """ Function to redirect to the shipment detail form
    """
    context_dict = {}
    name = request.GET.get('name')
    price = request.GET.get('price')
    merchant = request.GET.get('merchant')
    context_dict['name'] = name
    context_dict['price'] = price
    context_dict['merchant'] = merchant
    return render(request, 'inventory/shipment_details.html', context_dict)


@login_required
def order(request):
    """ To display all the purchases made by the merchant this function
    is invoked.
    """
    user_instance = User.objects.get(username=request.user.username)
    order = Order.objects.filter(merchant=user_instance)
    context_dict = {}
    array = []
    for i in order:
        data = {}
        data['order_id'] = i.order_id
        product = i.product_id.all()
        array_product = []
        for item in range(len(product)):
            data_product = {}
            data_product["name"] = product[item].name
            array_product.append(data_product)
        data['array_product'] = array_product
        data['summary'] = i.summary
        data['order_date'] = i.order_date
        data['address'] = i.address
        array.append(data)
    context_dict['data'] = array
    return render(request, 'inventory/order.html', context_dict)


@csrf_exempt
def pay(request):
    """ The function is invoked by the wallet. In this function
    the csrf token in exemted.
    For proper inventory tracking this function is responsible
    to update the inventory only after the successfull payment
    completion.
    """
    if request.method == 'POST':
        body_unicode = request.body.decode('utf-8')
        json_data = json.loads(body_unicode)
        if json_data is None:
            return HttpResponse("no json in body")
        r = requests.post("https://backend.demo.taler.net/public/pay",
            json=json_data,
            headers={"Authorization": "ApiKey sandbox"})
        if r.status_code != 200:
            return HttpResponse(r.status_code)
        contract_terms = r.json()["contract_terms"]
        merchant = contract_terms["merchant"]["name"]
        order_instance = Order.objects.create(
            order_id=contract_terms["order_id"],
            summary=contract_terms["summary"],
            merchant=User.objects.get(username=merchant)
            )
        order_instance.save()
        for i in contract_terms['products']:
            product_instance = Product.objects.get(name=i["description"])
            order_instance.product_id.add(product_instance)
            order_instance.save()
            update_inventory(i["description"], i["quantity"])
        return JsonResponse(r.json())


def payment(request):
    """ This function is called when the user has submitted
    the shipment details. The order for the required product
    is made and a post request is send for creation of the
    order. On the basis of this a required order_id is returned
    which is used to send a get request and check the status of
    the order. On the basis of this the user is redirected to the
    payment page.
    """
    session_id = request.session.session_key
    name = request.GET.get('name')
    price = request.GET.get('price')
    merchant = request.GET.get('merchant')
    # name_user = request.GET.get('name_user')
    # address_user = request.GET.get('address_user')
    summary = name+' purchased from '+merchant
    user = User.objects.get(username=merchant)
    primary_key = user.pk
    merchant_instance = Merchant.objects.get(pk=primary_key)
    base_url = request.build_absolute_uri().rsplit('/', 1)[0]
    # Creating an Order for a Payment
    order = dict(order=dict(amount="KUDOS:"+price,
        summary=summary,
        products=[
            dict(
                description=name,
                quantity=1,
                product_id=1,
                price="KUDOS:"+price,
                ),
            ],
        fulfillment_url=base_url+"/fulfillment/",
        pay_url=base_url+"/pay/",
        merchant=dict(
            address=merchant_instance.address,
            name=merchant,
            jurisdiction="none",
            instance="default",
        ),
        )
    )
    order_resp = backend_post("order", order)
    try:
        order_id = order_resp["order_id"]
    except Exception as e:
        return HttpResponse("Please refresh and try again")
    # Checking Payment Status and Prompting for Payment
    pay_params = dict(
        instance="default",
        order_id=order_id,
        session_id=session_id,
    )
    pay_status = backend_get("check-payment", pay_params)
    if pay_status["paid"]:
        base_url = request.build_absolute_uri().rsplit('/', 1)[0]
        url = base_url+"/fulfillment?order_id="+order_resp["order_id"]
        return redirect(url)
    else:
        if pay_status["payment_redirect_url"]:
            payment_redirect_url = pay_status["payment_redirect_url"]
            return redirect(payment_redirect_url)


def backend_get(endpoint, params):
    headers = {"Authorization": "ApiKey sandbox"}
    try:
        resp = requests.get(urljoin(BACKEND_URL, endpoint),
            params=params,
            headers=headers)
    except requests.ConnectionError:
        return HttpResponse("Could not establish connection to backend")
    try:
        response_json = resp.json()
    except ValueError:
        return HttpResponse("Could not parse response from backend")
    return response_json


def backend_post(endpoint, json):
    headers = {"Authorization": "ApiKey sandbox"}
    try:
        resp_url = urljoin(BACKEND_URL, endpoint)
        resp = requests.post(resp_url,
            json=json,
            headers=headers)
    except requests.ConnectionError:
        return HttpResponse("Could not establish connection to backend")
    try:
        response_json = resp.json()
    except ValueError:
        return HttpResponse("Could not parse response from backend")
    return response_json


def update_inventory(name, quantity):
    product_instance = Product.objects.get(name=name)
    inventory_on_hand = product_instance.inventory_on_hand - quantity
    product_instance.inventory_on_hand = inventory_on_hand
    product_instance.save()


@login_required
def home(request):
    """ Home page for the merchant where he can add
    and view all his inventory.
    """
    user_instance = User.objects.get(username=request.user.username)
    product = Product.objects.filter(user=user_instance)
    context_dict = {}
    array = []
    for i in product:
        data = {}
        data['name'] = i.name
        data['description'] = i.description
        data['price'] = i.price
        data['inventory_on_hand'] = i.inventory_on_hand
        data['url'] = '/home/product/' + str(i.product_id)
        array.append(data)
    context_dict['data'] = array
    return render(request, 'inventory/home.html', context_dict)


@login_required
def update_stock(request, uid):
    product_instance = Product.objects.get(name=uid)
    product_instance.inventory_on_hand = request.POST.get('stock_updated')
    product_instance.save()
    product_instance = Product.objects.get(name=uid)
    context_dict = {}
    context_dict['name'] = product_instance.name
    context_dict['description'] = product_instance.description
    context_dict['price'] = product_instance.price
    context_dict['inventory_on_hand'] = product_instance.inventory_on_hand
    url_update_inventory = str('/update_stock/') + product_instance.name
    context_dict['url_update_inventory'] = url_update_inventory
    return render(request, 'inventory/product.html', context_dict)


@login_required
def add_product(request):
    """ When a merchant is required to add a new product in his
    inventory this function is invoked.
    """
    name = request.POST.get('name')
    product_instance = Product.objects.get_or_create(name=name)[0]
    description = request.POST.get('description')
    product_instance.description = description
    price = request.POST.get('price')
    product_instance.price = price
    starting_inventory = request.POST.get('starting_inventory')
    product_instance.starting_inventory = starting_inventory
    product_instance.inventory_on_hand = starting_inventory
    minimum_required = request.POST.get('minimum_required')
    product_instance.minimum_required = minimum_required
    current_merchant = request.user.username
    user_instance = User.objects.get(username=current_merchant)
    product_instance.user = user_instance
    product_instance.save()
    product = Product.objects.filter(user=user_instance)
    context_dict = {}
    array = []
    for i in product:
        data = {}
        data['name'] = i.name
        data['description'] = i.description
        data['price'] = i.price
        data['inventory_on_hand'] = i.inventory_on_hand
        data['url'] = '/home/product/' + str(i.product_id)
        array.append(data)
    context_dict['data'] = array
    return render(request, 'inventory/home.html', context_dict)


@login_required
def product(request, uid):
    """ The product display page for the Mercheant.
    The required product details are included in this page.
    """
    item = Product.objects.get_or_create(product_id=uid)[0]
    context_dict = {}
    context_dict['name'] = item.name
    context_dict['description'] = item.description
    context_dict['price'] = item.price
    context_dict['inventory_on_hand'] = item.inventory_on_hand
    url_update_inventory = str('/update_stock/') + item.name
    context_dict['url_update_inventory'] = url_update_inventory
    base_url = request.build_absolute_uri().rsplit('/', 3)[0]
    merchant = request.user.username
    parameters = "name="+item.name+'&price='+item.price+'&merchant='+merchant
    context_dict['href'] = base_url+"/shipment?"+parameters
    return render(request, 'inventory/product.html', context_dict)


@login_required
def new_product(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            user_instance = User.objects.get(username=request.user.username)
            Product.objects.create(
                name=form.cleaned_data['name'],
                description=form.cleaned_data['description'],
                price=form.cleaned_data['price'],
                starting_inventory=0,
                minimum_required=0,
                inventory_on_hand=0,
                inventory_recieved=0,
                inventory_shipped=0,
                user=user_instance,
                document=form.cleaned_data['document']
                )
            return redirect('home')
    else:
        form = DocumentForm()
    return render(request, 'inventory/new_product.html', {
        'form': form
    })


def signup(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        details_form = MerchantDetailForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            auth_login(request, user)
            instance = get_object_or_404(Merchant, user=user)
            if details_form.is_valid():
                instance.address = details_form.cleaned_data.get('address')
                instance.save()
            else:
                print("somethings wrong with the form")
            # Redirect to a success page.
            return redirect('home')
    else:
        form = SignUpForm()
        details_form = MerchantDetailForm()
    dictionary = {'form': form, 'details_form': details_form}
    return render(request, 'inventory/signup.html', dictionary)


def login(request):
    form = LoginForm()
    context_dict = {}
    context_dict['form'] = form
    error_message = ""
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            auth_login(request, user)
            current_url = resolve(request.path_info).url_name
            print(current_url)
            # Redirect to a success page.
            return redirect('home')
        else:
            error_message = "You are not a registered user please sign up"
            form = LoginForm()
            context_dict['form'] = form
            context_dict['error_message'] = error_message
    return render(request, 'inventory/login.html', context_dict)


def logout(request):
    auth_logout(request)
    return render(request, 'inventory/index.html')