Merge branch 'cart'

This commit is contained in:
Andreas Zweili 2018-02-28 22:24:26 +01:00
commit 144a18d2e9
17 changed files with 819 additions and 798 deletions

View File

@ -31,7 +31,7 @@ def parse_rss(urlsocket):
def pass_local_file(): def pass_local_file():
rss_tree = ET.ElementTree(file='rss') rss_tree = ET.ElementTree(file='rss')
return(rss_tree) return(rss_tree)
def get_exchange_rate(rss_tree, ns): def get_exchange_rate(rss_tree, ns):
# Pathvariables to XML Namespaces with # Pathvariables to XML Namespaces with
@ -111,5 +111,4 @@ def get_exchange_rate(rss_tree, ns):
'exchangerate': foreign_value_round}] 'exchangerate': foreign_value_round}]
exchange_rates.append(data) exchange_rates.append(data)
# Print the Dictionary: # Print the Dictionary:
print(exchange_rates)
return(exchange_rates) return(exchange_rates)

View File

@ -1,8 +1,17 @@
from django import forms from django import forms
from currencies.models import ExchangeRate_name from currencies.models import ExchangeRate, ExchangeRate_name
class CurrenciesForm(forms.Form): class CurrenciesForm(forms.Form):
currencies = forms.ModelChoiceField( currencies = forms.ModelChoiceField(
queryset=ExchangeRate_name.objects.all(), queryset=ExchangeRate_name.objects.all(),
required=False, empty_label='CHF') required=False,
empty_label='CHF',
label='CURENCIES',
# widget=forms.Select(
# attrs={
# 'onchange': 'currency.submit();',
# 'class': 'btn-primary dropdown-toggle'
# }
#)
)

View File

@ -1,88 +1,28 @@
{% extends "webshop/base.html" %} {% extends "webshop/base.html" %}
{% block section_title %}Currencies in CHF{% endblock %} {% block section_title %}Currencies in CHF{% endblock %}
{% block content %} {% block content %}
<h2> {{ message }} </h2> <h4> Currency List: </h4>
<h3> Frühere Daten: </h3> {% if ordered_currency_list %}
<h4> US Dollars: </h4>
{% if currency_USD_list %}
<table> <table>
<tr> <tr>
<th scope="col">DATE</th> <th scope="col">DATE</th>
<th scope="col">NAME</th>
<th scope="col">RATE</th> <th scope="col">RATE</th>
</tr> </tr>
{% for currency in currency_USD_list %} {% for currency in ordered_currency_list %}
<tr> <tr>
<td scope="col">{{ currency.date.date }}</td> <td scope="col">{{ currency.date }}</td>
<td scope="col">{{ currency.name }}</td>
<td scope="col">{{ currency.exchange_rate_to_chf }}</td> <td scope="col">{{ currency.exchange_rate_to_chf }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
<p> {{ message }} </p>
{% else %} {% else %}
<br>
<p class="alert"> <p class="alert">
currency_USD_list missing. currency_list missing.
</p> </p>
{% endif %} {% endif %}
<br>
<h4> EURO: </h4>
{% if currency_EUR_list %}
<table>
<tr>
<th scope="col">DATE</th>
<th scope="col">RATE</th>
</tr>
{% for currency in currency_EUR_list %}
<tr>
<td scope="col">{{ currency.date.date }}</td>
<td scope="col">{{ currency.exchange_rate_to_chf }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p class="alert">
currency_EUR_list missing.
</p>
{% endif %}
<br>
<h4> Japanese Yenn: </h4>
{% if currency_JPY_list %}
<table>
<tr>
<th scope="col">DATE</th>
<th scope="col">RATE</th>
</tr>
{% for currency in currency_JPY_list %}
<tr>
<td scope="col">{{ currency.date.date }}</td>
<td scope="col">{{ currency.exchange_rate_to_chf }}</td>
</tr>
{% endfor %}
<tr>
</table>
{% else %}
<p class="alert">
currency_JPY_list missing.
</p>
{% endif %}
<br>
<h4> Great Britain Pounds: </h4>
{% if currency_GBP_list %}
<table>
<tr>
<th scope="col">DATE</th>
<th scope="col">RATE</th>
</tr>
{% for currency in currency_GBP_list %}
<tr>
<td scope="col">{{ currency.date.date }}</td>
<td scope="col">{{ currency.exchange_rate_to_chf }}</td>
</tr>
{% endfor %}
<tr>
</table>
{% else %}
<p class="alert">
currency_GBP_list missing.
</p>
{% endif %}
</div> </div>
{% endblock %} {% endblock %}

View File

@ -1,12 +0,0 @@
from django import template
register = template.Library()
@register.filter()
def boldcoffee(value):
# currency_of_customer = request.session['currency']
return '%s !!gefiltert!!' % value
# excample filter: {{ article.price_in_chf|boldcoffee }}

View File

@ -1,9 +1,6 @@
from django.conf.urls import url from django.conf.urls import url
from currencies.views import currencies, currency_update from currencies.views import currencies
urlpatterns = [ urlpatterns = [
url(r'^currencies/$', currencies), url(r'^currencies/$', currencies),
url(r'^ajax/currency_update/$',
currency_update,
name='currency_update'),
] ]

View File

@ -1,6 +1,5 @@
from django.shortcuts import render from django.shortcuts import render
from datetime import datetime from datetime import datetime
from django.views.generic.edit import UpdateView
from currencies.models import (ExchangeRate, from currencies.models import (ExchangeRate,
ExchangeRate_date, ExchangeRate_date,
ExchangeRate_name) ExchangeRate_name)
@ -8,20 +7,6 @@ from currencies import exchange_rates
from django.http import JsonResponse from django.http import JsonResponse
def currency_update(request):
# https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html
if request.GET.get('currency_update', None) == 'CHF':
data = {}
else:
currency = request.GET.get('currency_update', None)
data = ExchangeRate.objects.filter(
name__name=currency).values(
'exchange_rate_to_chf').latest(
'date__date')
print('currency:', currency, 'data: ', data)
return JsonResponse(data)
def currencies(request): def currencies(request):
"""this function fetches the data from swiss national bank """this function fetches the data from swiss national bank
@ -57,7 +42,7 @@ def currencies(request):
message_offline = """ message_offline = """
Are you offline? - useing stored currencies. Are you offline? - useing stored currencies.
This does not efect you, but your purchase prices will be This does not efect you, but your purchase prices will be
recalculated as soon as you submit your Order. recalculated as soon as you submit your Order. <br>
""" """
try: try:
raw_data = exchange_rates.get_exchange_rate(rss_tree, ns) raw_data = exchange_rates.get_exchange_rate(rss_tree, ns)
@ -163,32 +148,21 @@ def currencies(request):
elif datetime.datetime.today().isoweekday() == 6: elif datetime.datetime.today().isoweekday() == 6:
message = """Die Abfrage wurde ohne ergebniss beendet. message = """Die Abfrage wurde ohne ergebniss beendet.
Es ist Samstag, die SNB publiziert nur an Arbeitstagen Es ist Samstag, die SNB publiziert nur an Arbeitstagen
neue Kurse... neue Kurse... <br>
""" """
elif datetime.datetime.today().isoweekday() == 7: elif datetime.datetime.today().isoweekday() == 7:
message = """Die Abfrage wurde ohne ergebniss beendet. message = """Die Abfrage wurde ohne ergebniss beendet.
Es ist Sonntag, die SNB publiziert nur an Arbeitstagen Es ist Sonntag, die SNB publiziert nur an Arbeitstagen
neue Kurse... neue Kurse... <br>
""" """
else: else:
message = """Die Abfrage wurde ohne ergebniss beendet. message = """Die Abfrage wurde ohne ergebniss beendet. <br>
""" """
# know we can query our data for presentaton: # know we can query our data for presentaton:
currency_list = ExchangeRate.objects.all() ordered_currency_list = ExchangeRate.objects.order_by('name', 'date')
currency_USD_list = ExchangeRate.objects.filter(
name__name='USD').order_by('date__date')
currency_EUR_list = ExchangeRate.objects.filter(
name__name='EUR').order_by('date__date')
currency_JPY_list = ExchangeRate.objects.filter(
name__name='JPY').order_by('date__date')
currency_GBP_list = ExchangeRate.objects.filter(
name__name='GBP').order_by('date__date')
# and publish it on template: # and publish it on template:
return render(request, return render(request,
'currencies/index.html', 'currencies/index.html',
{'currency_list': currency_list, {'ordered_currency_list': ordered_currency_list,
'currency_USD_list': currency_USD_list,
'currency_EUR_list': currency_EUR_list,
'currency_JPY_list': currency_JPY_list,
'currency_GBP_list': currency_GBP_list,
'message': message}) 'message': message})

File diff suppressed because it is too large Load Diff

View File

@ -1,30 +0,0 @@
$("#id_currency_update").change(function () {
var currency_update = $(this).val();
$("#id_currency_update").val(currency_update);
$.ajax({
url: '/ajax/currency_update/',
data: {
'currency_update': currency_update
},
dataType: 'json',
success: function (data) {
var foo = jQuery.parseJSON(data);
alert("es pop auf! --dies kommt von: static/js/app.js--." + foo.currency_update);
}
});
});
//document.getElementById('id_currency_update').getElementsByTagName('currency_update')
//$("#id_currency_update").val('USD').selected = 'selected';
//https://stackoverflow.com/a/30489067/4061870
// var obj = document.getElementById("id_currency_update");
// for(i=0; i<obj.options.length; i++){
// if(obj.options[i].value == "USD"){
// obj.selectedIndex = i;
// }
// }
// var e document.getElementById("id_currency_update");
//e.value = currency_update;

View File

@ -100,6 +100,10 @@ class OrderPosition(models.Model):
validators=[MinValueValidator( validators=[MinValueValidator(
Decimal('0.00'))]) Decimal('0.00'))])
def calculate_position_price(self):
decimal_amount = Decimal.from_float(self.amount)
self.position_price = decimal_amount * self.article.price_in_chf
class ShoppingCart(models.Model): class ShoppingCart(models.Model):
""" Cart to User Relationships """ """ Cart to User Relationships """

View File

@ -3,15 +3,41 @@
{% block section_title %}User Profile{% endblock %} {% block section_title %}User Profile{% endblock %}
{% block content %} {% block content %}
</br>
<p><b>Username: </b>{{ request.user.username }}</p> <p><b>Username: </b>{{ request.user.username }}</p>
<p><b>Salutation: </b>{{ person.salutation }}</p> <p><b>Name: </b>
<p><b>Firstname: </b>{{ request.user.first_name }}</p> {{ person.salutation }}
<p><b>Lastname: </b>{{ request.user.last_name }}</p> {{ request.user.first_name }}
{{ request.user.last_name }}</p>
<p><b>Street: </b>{{ person.street_name }} {{ person.street_number }}</p>
<p><b>City: </b>{{ person.city }}</p> <p><b>City: </b>{{ person.city }}</p>
<p><b>Street: </b>{{ person.street_name }}</p>
<p><b>Streetnumber: </b>{{ person.street_number }}</p>
<form method="post"> <form method="post">
{% csrf_token %} {% csrf_token %}
{{ form.as_p }} {{ form.as_p }}
</form> </form>
{% if order_list_zip %}
</br>
<h4> Orders:</h4>
<table class="table price-table">
<tr class="table_header">
<th scope="col">ID</th>
<th scope="col">DATE</th>
<th scope="col">STATUS</th>
</tr>
{% for order, order_positions_count in order_list_zip %}
<tr class="table_content">
<td scope="col">{{ order.id }}</td>
<td scope="col">{{ order.date }}</td>
<td scope="col">
<a href="{% url 'order' order.id %}">{{ order.status }}</a>
</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>
you don't have Ordered anything yet.
As soon as you Purchase anything from us you can see your Orders here.
</p>
{% endif %}
{% endblock %} {% endblock %}

View File

@ -15,7 +15,9 @@
</form> </form>
</p> </p>
{% else %} {% else %}
<p> please login to fill your basket...</p> <p class="alert">
please login to fill your basket...
</p>
{% endif %} {% endif %}
{% for picture in picture_list %} {% for picture in picture_list %}
<p><img src="{{ MEDIA_URL }}{{ picture.image }}" width="200" /></p> <p><img src="{{ MEDIA_URL }}{{ picture.image }}" width="200" /></p>

View File

@ -81,7 +81,7 @@
<a href="/currencies">Currencies</a> <a href="/currencies">Currencies</a>
</li> </li>
<li> <li>
<a href="#">How to use</a> <a href="https://git.2li.ch/ibz/web_AI-5/src/branch/master/README.md">How to use</a>
</li> </li>
</ul> </ul>
</div> </div>
@ -93,7 +93,6 @@
</div> </div>
</footer> </footer>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="{% static 'js/app.js' %}"></script>
<script>{% block javascript %}{% endblock %}</script> <script>{% block javascript %}{% endblock %}</script>
</body> </body>
</html> </html>

View File

@ -1,5 +1,4 @@
{% extends "webshop/base.html" %} {% extends "webshop/base.html" %}
{% load customfilters %}
{% block section_title %}Articles{% endblock %} {% block section_title %}Articles{% endblock %}
{% block content %} {% block content %}

View File

@ -13,12 +13,12 @@
{% else %} {% else %}
<li><a href="{% url 'login' %}">LOGIN</a></li> <li><a href="{% url 'login' %}">LOGIN</a></li>
{% endif %} {% endif %}
<li class="dropdown"> <li>
{% if article_view %} {% if article_view %}
<form id="currency" action="" method="POST" novalidate> <form id="currency" action="" method="POST" novalidate>
{{ currencies_form.as_ul }} {{ currencies_form.as_ul }}
{% csrf_token %}
<li><input type="submit" value="Select"></li> <li><input type="submit" value="Select"></li>
{% csrf_token %}
</form> </form>
{% endif %} {% endif %}
</li> </li>

View File

@ -1,7 +1,70 @@
{% extends "webshop/base.html" %} {% extends "webshop/base.html" %}
{% load customfilters %}
{% block section_title %}Order{% endblock %} {% block section_title %}Order{% endblock %}
{% block content %} {% block content %}
<h1> Your order was submitted. </h1> {% if order %}
<h3> Thank you for Purchase. </h3> <h4>Your order was submitted on:
{{ order.date }}, current Status is:
{{ order.status }}.
</h4>
{% else %}
<p class="alert alert-danger">
<strong>
Orderdetails are not avalable.
<strong>
</p>
{% endif %}
<h3>List of Items in your Order:</h3>
{% if order_position_list_zip %}
<table class="table price-table">
<tr class="table_header">
<th scope="col">POS.</th>
<th scope="col">ART#</th>
<th scope="col">NAME</th>
<th scope="col">STOCK</th>
<th scope="col">AMOUNT</th>
<th scope="col" class="price-label">PRICE p.pce.</th>
<th scope="col" class="price-label">POSITION PRICE</th>
</tr>
{% for order_position, price, pos_price in order_position_list_zip %}
<tr class="table_content">
<td scope="col">{{ order_position.id }}</td>
<td scope="col">{{ order_position.article.id }}</td>
<td scope="col">
<a href="{% url 'details' order_position.article.id %}">
{{ order_position.article.name }}
</a>
</td>
<td scope="col">{{ order_position.article.stock }}</td>
<td scope="col">{{ order_position.amount }}</td>
<td scope="col" class="price-value">
{{ price }}
{{ currency_name }}
</td>
<td scope="col" class="price-value">
{{ pos_price }} {{ currency_name }}
</td>
</tr>
{% endfor %}
<tr>
<td scope="col" colspan="5"class="text-right">
<td scope="col" class="price-value">
<dl><dt>Total:</dl></dt></td>
<td scope="col" class="price-value">
<dl><dt>{{ total }} {{ currency_name }}</dl></dt>
</td>
</tr>
</table>
<h3> Thank you for Purchase. </h3>
{% else %}
<p class="alert alert-danger">
<strong>
This order is empty. Howcome?
<strong>
</p>
{% endif %}
<p class="alert text-danger">
<strong>
{{ message }}
<strong>
</p>
{% endblock %} {% endblock %}

View File

@ -23,7 +23,7 @@ urlpatterns = [
url(r'^cart/checkout/$', url(r'^cart/checkout/$',
views.checkout, views.checkout,
name='checkout'), name='checkout'),
url(r'^order/$', url(r'^order/(?P<order_id>[0-9]+)/$',
views.order, views.order,
name='order'), name='order'),
] ]

View File

@ -4,6 +4,7 @@ from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import UserCreationForm
from django.db import transaction from django.db import transaction
from decimal import Decimal
from webshop.models import (Article, from webshop.models import (Article,
Category, Category,
Person, Person,
@ -159,9 +160,32 @@ def article_details(request, article_id):
@login_required @login_required
def profile(request): def profile(request):
category_list = get_categories() category_list = get_categories()
totalprice_list = []
total_list = []
currency_list = []
order_list_zip = []
order_positions_count_list = []
order_positions_count = ""
total = ""
currency_name = ""
person = Person.objects.get(user=request.user) person = Person.objects.get(user=request.user)
orders = Order.objects.filter(user=request.user)
if orders:
orders_list = list(orders)
for idx1, order in enumerate(orders_list):
# get all items in the Order:
order_positions = OrderPosition.objects.filter(order=order)
if (order_positions.count()) > 0:
order_positions_count = order_positions.count()
order_positions_count_list.append(order_positions_count)
orders_list[idx1] = order
order_list_zip = zip(orders_list,
order_positions_count_list
)
# assert False
return render(request, 'registration/profile.html', return render(request, 'registration/profile.html',
{'person': person, {'person': person,
'order_list_zip': order_list_zip,
'category_list': category_list}) 'category_list': category_list})
@ -222,17 +246,14 @@ def cart(request):
if request.method == 'POST': if request.method == 'POST':
# here we react to a currency dropdown change: # here we react to a currency dropdown change:
if 'currencies' in request.POST: if 'currencies' in request.POST:
print('currencies')
currencies_form = CurrenciesForm(request.POST) currencies_form = CurrenciesForm(request.POST)
if currencies_form.is_valid(): if currencies_form.is_valid():
cf = currencies_form.cleaned_data cf = currencies_form.cleaned_data
if cf['currencies']: if cf['currencies']:
print('currencies cf:', cf)
selection = cf['currencies'] selection = cf['currencies']
request.session['currency'] = selection.id request.session['currency'] = selection.id
currency_name = ExchangeRate_name.objects.get( currency_name = ExchangeRate_name.objects.get(
id=selection.id) id=selection.id)
print('currencies currency_name:', currency_name)
else: else:
request.session['currency'] = None request.session['currency'] = None
@ -375,8 +396,6 @@ def checkout(request):
else: else:
order = Order.objects.create(user=request.user, order = Order.objects.create(user=request.user,
status=orderstatus) status=orderstatus)
print('order', order, 'created:', order)
for position in cart_positions: for position in cart_positions:
OrderPosition.objects.create( OrderPosition.objects.create(
article=position.article, article=position.article,
@ -384,7 +403,7 @@ def checkout(request):
amount=position.amount, amount=position.amount,
price_in_chf=position.article.price_in_chf price_in_chf=position.article.price_in_chf
) )
return HttpResponseRedirect('/order/') return HttpResponseRedirect('/order/%s/' % order.id)
return render(request, 'webshop/checkout.html', return render(request, 'webshop/checkout.html',
{'cart_position_list': cart_position_list, {'cart_position_list': cart_position_list,
@ -394,11 +413,14 @@ def checkout(request):
'article_view': article_view, 'article_view': article_view,
'category_list': category_list, 'category_list': category_list,
'message': message, 'message': message,
'person': person 'person': person,
}) })
def order(request): def order(request, order_id):
price_list = []
totalprice_list = []
order_position_list_zip = []
cart = ShoppingCart.objects.get(user=request.user) cart = ShoppingCart.objects.get(user=request.user)
if cart: if cart:
# get all items in the cart of this customer: # get all items in the cart of this customer:
@ -413,5 +435,34 @@ def order(request):
) )
else: else:
message = """something whent wrong. message = """something whent wrong.
We cold not delete your cartitems. """ We cold not empty your cart. """
return render(request, 'webshop/order.html', {}) order = Order.objects.get(id=order_id)
order_positions = OrderPosition.objects.filter(order=order_id)
if (order_positions.count()) > 0:
order_position_list = list(order_positions)
for idx, order_position in enumerate(order_positions):
# get currencyname to display:
if order.exchange_rate is not None:
# get price of position in order and append to a list:
rate = ExchangeRate.objects.get(id=order.exchange_rate.id)
price = round(
rate.exchange_rate_to_chf * order_position.price_in_chf,
2)
currency_name = order.exchange_rate
else:
currency_name = 'CHF'
price = order_position.price_in_chf
position_price = price * Decimal.from_float(order_position.amount)
order_position_list[idx] = order_position
price_list.append(price)
totalprice_list.append(position_price)
total = sum(totalprice_list)
order_position_list_zip = zip(order_position_list,
price_list,
totalprice_list)
return render(request, 'webshop/order.html', {
'order': order,
'order_position_list_zip': order_position_list_zip,
'total': total,
'currency_name': currency_name,
})