Les tests fonctionnent

This commit is contained in:
Thomas Girod 2023-01-10 16:20:06 +01:00
parent b88cd9673c
commit e5abba89bd
5 changed files with 59 additions and 38 deletions

View File

@ -451,11 +451,11 @@ class Counter(models.Model):
Show if the counter authorize the refilling with physic money Show if the counter authorize the refilling with physic money
""" """
if ( if self.type != "BAR":
self.id in SITH_COUNTER_OFFICES return False
): # If the counter is the counters 'AE' or 'BdF', the refiling are authorized if self.id in SITH_COUNTER_OFFICES:
# If the counter is either 'AE' or 'BdF', refills are authorized
return True return True
is_ae_member = False is_ae_member = False
ae = Club.objects.get(unix_name=SITH_MAIN_CLUB["unix_name"]) ae = Club.objects.get(unix_name=SITH_MAIN_CLUB["unix_name"])
for barman in self.get_barmen_list(): for barman in self.get_barmen_list():

View File

@ -12,6 +12,15 @@ document.addEventListener('alpine:init', () => {
return total / 100; return total / 100;
}, },
async handle_code(event) {
const code = $(event.target).find("#code_field").val().toUpperCase();
if(["FIN", "ANN"].includes(code)) {
$(event.target).submit();
} else {
await this.handle_action(event);
}
},
async handle_action(event) { async handle_action(event) {
const payload = $(event.target).serialize(); const payload = $(event.target).serialize();
let request = new Request(click_api_url, { let request = new Request(click_api_url, {

View File

@ -56,14 +56,17 @@
<h5>{% trans %}Selling{% endtrans %}</h5> <h5>{% trans %}Selling{% endtrans %}</h5>
<div> <div>
{% set counter_click_url = url('counter:click', counter_id=counter.id, user_id=customer.user.id) %} {% set counter_click_url = url('counter:click', counter_id=counter.id, user_id=customer.user.id) %}
{# Formulaire pour rechercher un produit en tapant son code dans une barre de recherche #}
<form method="post" action="" <form method="post" action=""
class="code_form" @submit.prevent="handle_action"> class="code_form" @submit.prevent="handle_code">
{% csrf_token %} {% csrf_token %}
<input type="hidden" name="action" value="code"> <input type="hidden" name="action" value="code">
<label for="code_field"></label> <label for="code_field"></label>
<input type="text" name="code" value="" class="focus" id="code_field"/> <input type="text" name="code" value="" class="focus" id="code_field"/>
<input type="submit" value="{% trans %}Go{% endtrans %}"/> <input type="submit" value="{% trans %}Go{% endtrans %}"/>
</form> </form>
<template x-for="error in errors"> <template x-for="error in errors">
<div class="alert alert-red" x-text="error"> <div class="alert alert-red" x-text="error">
</div> </div>
@ -71,7 +74,7 @@
<p>{% trans %}Basket: {% endtrans %}</p> <p>{% trans %}Basket: {% endtrans %}</p>
<ul> <ul>
<template x-for="[id, item] in Object.entries(basket)"> <template x-for="[id, item] in Object.entries(basket)" :key="id">
<div> <div>
<form method="post" action="" class="inline del_product_form" <form method="post" action="" class="inline del_product_form"
@submit.prevent="handle_action"> @submit.prevent="handle_action">

View File

@ -62,12 +62,12 @@ class CounterTest(TestCase):
reverse("counter:details", kwargs={"counter_id": self.mde.id}), reverse("counter:details", kwargs={"counter_id": self.mde.id}),
{"code": "4000k", "counter_token": counter_token}, {"code": "4000k", "counter_token": counter_token},
) )
location = response.get("location") counter_url = response.get("location")
response = self.client.get(response.get("location")) response = self.client.get(response.get("location"))
self.assertTrue(">Richard Batsbak</" in str(response.content)) self.assertTrue(">Richard Batsbak</" in str(response.content))
self.client.post( self.client.post(
location, counter_url,
{ {
"action": "refill", "action": "refill",
"amount": "5", "amount": "5",
@ -75,14 +75,14 @@ class CounterTest(TestCase):
"bank": "OTHER", "bank": "OTHER",
}, },
) )
self.client.post(location, {"action": "code", "code": "BARB"}) self.client.post(counter_url, "action=code&code=BARB", content_type="text/xml")
self.client.post(location, {"action": "add_product", "product_id": "4"}) self.client.post(counter_url, "action=add_product&product_id=4", content_type="text/xml")
self.client.post(location, {"action": "del_product", "product_id": "4"}) self.client.post(counter_url, "action=del_product&product_id=4", content_type="text/xml")
self.client.post(location, {"action": "code", "code": "2xdeco"}) self.client.post(counter_url, "action=code&code=2xdeco", content_type="text/xml")
self.client.post(location, {"action": "code", "code": "1xbarb"}) self.client.post(counter_url, "action=code&code=1xbarb", content_type="text/xml")
response = self.client.post(location, {"action": "finish"}) response = self.client.post(counter_url, "action=code&code=fin", content_type="text/xml")
response_get = self.client.get(location) response_get = self.client.get(response.get("location"))
response_content = response_get.content.decode("utf-8") response_content = response_get.content.decode("utf-8")
self.assertTrue("2 x Barbar" in str(response_content)) self.assertTrue("2 x Barbar" in str(response_content))
self.assertTrue("2 x Déconsigne Eco-cup" in str(response_content)) self.assertTrue("2 x Déconsigne Eco-cup" in str(response_content))
@ -97,7 +97,7 @@ class CounterTest(TestCase):
) )
response = self.client.post( response = self.client.post(
location, counter_url,
{ {
"action": "refill", "action": "refill",
"amount": "5", "amount": "5",
@ -107,7 +107,7 @@ class CounterTest(TestCase):
) )
self.assertTrue(response.status_code == 200) self.assertTrue(response.status_code == 200)
response = self.client.post( self.client.post(
reverse("counter:login", kwargs={"counter_id": self.foyer.id}), reverse("counter:login", kwargs={"counter_id": self.foyer.id}),
{"username": self.krophil.username, "password": "plop"}, {"username": self.krophil.username, "password": "plop"},
) )
@ -124,10 +124,10 @@ class CounterTest(TestCase):
reverse("counter:details", kwargs={"counter_id": self.foyer.id}), reverse("counter:details", kwargs={"counter_id": self.foyer.id}),
{"code": "4000k", "counter_token": counter_token}, {"code": "4000k", "counter_token": counter_token},
) )
location = response.get("location") counter_url = response.get("location")
response = self.client.post( response = self.client.post(
location, counter_url,
{ {
"action": "refill", "action": "refill",
"amount": "5", "amount": "5",
@ -143,7 +143,7 @@ class CounterStatsTest(TestCase):
call_command("populate") call_command("populate")
self.counter = Counter.objects.filter(id=2).first() self.counter = Counter.objects.filter(id=2).first()
def test_unothorized_user_fail(self): def test_unauthorised_user_fail(self):
# Test with not login user # Test with not login user
response = self.client.get(reverse("counter:stats", args=[self.counter.id])) response = self.client.get(reverse("counter:stats", args=[self.counter.id]))
self.assertTrue(response.status_code == 403) self.assertTrue(response.status_code == 403)

View File

@ -302,10 +302,7 @@ class CounterClick(CounterTabsMixin, CanViewMixin, DetailView):
current_tab = "counter" current_tab = "counter"
def render_to_response(self, *args, **kwargs): def render_to_response(self, *args, **kwargs):
if len(self.request.POST) == 0 and len(self.request.body) != 0: if self.is_ajax(self.request):
# when using the fetch API, the django request.POST dict is empty
# this is but a wretched contrivance which must be replaced as soon as possible
# by a proper separation between the api endpoints of the counter
response = {"errors": []} response = {"errors": []}
status = HTTPStatus.OK status = HTTPStatus.OK
@ -404,8 +401,9 @@ class CounterClick(CounterTabsMixin, CanViewMixin, DetailView):
self.operator = self.customer.user self.operator = self.customer.user
else: else:
self.operator = self.object.get_random_barman() self.operator = self.object.get_random_barman()
action = self.request.POST.get("action", None)
if action is None:
action = parse_qs(request.body.decode()).get("action", [""])[0] action = parse_qs(request.body.decode()).get("action", [""])[0]
if action == "add_product": if action == "add_product":
self.add_product(request) self.add_product(request)
elif action == "add_student_card": elif action == "add_student_card":
@ -477,6 +475,16 @@ class CounterClick(CounterTabsMixin, CanViewMixin, DetailView):
self.compute_record_product(request, product) self.compute_record_product(request, product)
) )
@staticmethod
def is_ajax(request):
# when using the fetch API, the django request.POST dict is empty
# this is but a wretched contrivance which strive to replace
# the deprecated django is_ajax() method
# and which must be replaced as soon as possible
# by a proper separation between the api endpoints of the counter
return len(request.POST) == 0 and len(request.body) != 0
def add_product(self, request, q=1, p=None): def add_product(self, request, q=1, p=None):
""" """
Add a product to the basket Add a product to the basket
@ -578,8 +586,6 @@ class CounterClick(CounterTabsMixin, CanViewMixin, DetailView):
request.session["basket"][pid]["qty"] -= 1 request.session["basket"][pid]["qty"] -= 1
if request.session["basket"][pid]["qty"] <= 0: if request.session["basket"][pid]["qty"] <= 0:
del request.session["basket"][pid] del request.session["basket"][pid]
else:
request.session["basket"][pid] = None
request.session.modified = True request.session.modified = True
def parse_code(self, request): def parse_code(self, request):
@ -590,6 +596,10 @@ class CounterClick(CounterTabsMixin, CanViewMixin, DetailView):
- <int>X<str>, where the integer is the quantity and str the code - <int>X<str>, where the integer is the quantity and str the code
""" """
string = parse_qs(request.body.decode())["code"][0].upper() string = parse_qs(request.body.decode())["code"][0].upper()
if string == "FIN":
return self.finish(request)
elif string == "ANN":
return self.cancel(request)
regex = re.compile(r"^((?P<nb>[0-9]+)X)?(?P<code>[A-Z0-9]+)$") regex = re.compile(r"^((?P<nb>[0-9]+)X)?(?P<code>[A-Z0-9]+)$")
m = regex.match(string) m = regex.match(string)
if m is not None: if m is not None:
@ -664,7 +674,8 @@ class CounterClick(CounterTabsMixin, CanViewMixin, DetailView):
def refill(self, request): def refill(self, request):
"""Refill the customer's account""" """Refill the customer's account"""
if self.get_object().type == "BAR" and self.object.can_refill(): if not self.object.can_refill():
raise PermissionDenied
form = RefillForm(request.POST) form = RefillForm(request.POST)
if form.is_valid(): if form.is_valid():
form.instance.counter = self.object form.instance.counter = self.object
@ -673,8 +684,6 @@ class CounterClick(CounterTabsMixin, CanViewMixin, DetailView):
form.instance.save() form.instance.save()
else: else:
self.refill_form = form self.refill_form = form
else:
raise PermissionDenied
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
"""Add customer to the context""" """Add customer to the context"""