mirror of
https://github.com/ae-utbm/sith.git
synced 2024-12-22 07:41:14 +00:00
Merge pull request #953 from ae-utbm/taiste
Counter views split, unique student cards, student cards and reloads HTMXification, refactors and fixes
This commit is contained in:
commit
c1be55a719
18
.github/workflows/deploy.yml
vendored
18
.github/workflows/deploy.yml
vendored
@ -45,3 +45,21 @@ jobs:
|
||||
poetry run ./manage.py compilemessages
|
||||
|
||||
sudo systemctl restart uwsgi
|
||||
|
||||
sentry:
|
||||
runs-on: ubuntu-latest
|
||||
environment: production
|
||||
timeout-minutes: 30
|
||||
needs: deployment
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Sentry Release
|
||||
uses: getsentry/action-release@v1.7.0
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
|
||||
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
|
||||
SENTRY_URL: ${{ secrets.SENTRY_URL }}
|
||||
with:
|
||||
environment: production
|
@ -1,7 +1,7 @@
|
||||
repos:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
# Ruff version.
|
||||
rev: v0.6.9
|
||||
rev: v0.8.3
|
||||
hooks:
|
||||
- id: ruff # just check the code, and print the errors
|
||||
- id: ruff # actually fix the fixable errors, but print nothing
|
||||
@ -14,7 +14,7 @@ repos:
|
||||
- id: biome-check
|
||||
additional_dependencies: ["@biomejs/biome@1.9.3"]
|
||||
- repo: https://github.com/rtts/djhtml
|
||||
rev: 3.0.6
|
||||
rev: 3.0.7
|
||||
hooks:
|
||||
- id: djhtml
|
||||
name: format templates
|
||||
|
@ -69,7 +69,7 @@ class Command(BaseCommand):
|
||||
# sqlite doesn't support this operation
|
||||
return
|
||||
sqlcmd = StringIO()
|
||||
call_command("sqlsequencereset", *args, stdout=sqlcmd)
|
||||
call_command("sqlsequencereset", "--no-color", *args, stdout=sqlcmd)
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(sqlcmd.getvalue())
|
||||
|
||||
@ -137,11 +137,10 @@ class Command(BaseCommand):
|
||||
)
|
||||
|
||||
self.reset_index("club")
|
||||
for bar_id, bar_name in settings.SITH_COUNTER_BARS:
|
||||
Counter(id=bar_id, name=bar_name, club=bar_club, type="BAR").save()
|
||||
self.reset_index("counter")
|
||||
counters = [
|
||||
*[
|
||||
Counter(id=bar_id, name=bar_name, club=bar_club, type="BAR")
|
||||
for bar_id, bar_name in settings.SITH_COUNTER_BARS
|
||||
],
|
||||
Counter(name="Eboutic", club=main_club, type="EBOUTIC"),
|
||||
Counter(name="AE", club=main_club, type="OFFICE"),
|
||||
Counter(name="Vidage comptes AE", club=main_club, type="OFFICE"),
|
||||
|
@ -4,6 +4,7 @@ from typing import Annotated
|
||||
from annotated_types import MinLen
|
||||
from django.contrib.staticfiles.storage import staticfiles_storage
|
||||
from django.db.models import Q
|
||||
from django.urls import reverse
|
||||
from django.utils.text import slugify
|
||||
from haystack.query import SearchQuerySet
|
||||
from ninja import FilterSchema, ModelSchema, Schema
|
||||
@ -37,13 +38,13 @@ class UserProfileSchema(ModelSchema):
|
||||
|
||||
@staticmethod
|
||||
def resolve_profile_url(obj: User) -> str:
|
||||
return obj.get_absolute_url()
|
||||
return reverse("core:user_profile", kwargs={"user_id": obj.pk})
|
||||
|
||||
@staticmethod
|
||||
def resolve_profile_pict(obj: User) -> str:
|
||||
if obj.profile_pict_id is None:
|
||||
return staticfiles_storage.url("core/img/unknown.jpg")
|
||||
return obj.profile_pict.get_download_url()
|
||||
return reverse("core:download", kwargs={"file_id": obj.profile_pict_id})
|
||||
|
||||
|
||||
class SithFileSchema(ModelSchema):
|
||||
|
@ -103,6 +103,12 @@ export class AutoCompleteSelectBase extends inheritHtmlElement("select") {
|
||||
export abstract class AjaxSelect extends AutoCompleteSelectBase {
|
||||
protected filter?: (items: TomOption[]) => TomOption[] = null;
|
||||
protected minCharNumberForSearch = 2;
|
||||
/**
|
||||
* A cache of researches that have been made using this input.
|
||||
* For each record, the key is the user's query and the value
|
||||
* is the list of results sent back by the server.
|
||||
*/
|
||||
protected cache = {} as Record<string, TomOption[]>;
|
||||
|
||||
protected abstract valueField: string;
|
||||
protected abstract labelField: string;
|
||||
@ -135,7 +141,13 @@ export abstract class AjaxSelect extends AutoCompleteSelectBase {
|
||||
this.widget.clearOptions();
|
||||
}
|
||||
|
||||
const resp = await this.search(query);
|
||||
// Check in the cache if this query has already been typed
|
||||
// and do an actual HTTP request only if the result isn't cached
|
||||
let resp = this.cache[query];
|
||||
if (!resp) {
|
||||
resp = await this.search(query);
|
||||
this.cache[query] = resp;
|
||||
}
|
||||
|
||||
if (this.filter) {
|
||||
callback(this.filter(resp), []);
|
||||
|
@ -1,3 +1,11 @@
|
||||
import htmx from "htmx.org";
|
||||
|
||||
document.body.addEventListener("htmx:beforeRequest", (event) => {
|
||||
event.target.ariaBusy = true;
|
||||
});
|
||||
|
||||
document.body.addEventListener("htmx:afterRequest", (event) => {
|
||||
event.originalTarget.ariaBusy = null;
|
||||
});
|
||||
|
||||
Object.assign(window, { htmx });
|
||||
|
@ -6,7 +6,16 @@
|
||||
**/
|
||||
export function registerComponent(name: string, options?: ElementDefinitionOptions) {
|
||||
return (component: CustomElementConstructor) => {
|
||||
try {
|
||||
window.customElements.define(name, component, options);
|
||||
} catch (e) {
|
||||
if (e instanceof DOMException) {
|
||||
// biome-ignore lint/suspicious/noConsole: it's handy to troobleshot
|
||||
console.warn(e.message);
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -30,3 +30,8 @@ $shadow-color: rgb(223, 223, 223);
|
||||
$background-button-color: hsl(0, 0%, 95%);
|
||||
|
||||
$deepblue: #354a5f;
|
||||
|
||||
@mixin shadow {
|
||||
box-shadow: rgba(60, 64, 67, 0.3) 0 1px 3px 0,
|
||||
rgba(60, 64, 67, 0.15) 0 4px 8px 3px;
|
||||
}
|
@ -42,6 +42,32 @@ body {
|
||||
}
|
||||
}
|
||||
|
||||
[tooltip] {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
[tooltip]::before {
|
||||
@include shadow;
|
||||
opacity: 0;
|
||||
z-index: 1;
|
||||
content: attr(tooltip);
|
||||
background: hsl(219.6, 20.8%, 96%);
|
||||
color: $black-color;
|
||||
border: 0.5px solid hsl(0, 0%, 50%);
|
||||
;
|
||||
border-radius: 5px;
|
||||
padding: 5px;
|
||||
top: 1em;
|
||||
position: absolute;
|
||||
margin-top: 5px;
|
||||
white-space: nowrap;
|
||||
transition: opacity 500ms ease-out;
|
||||
}
|
||||
|
||||
[tooltip]:hover::before {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.ib {
|
||||
display: inline-block;
|
||||
padding: 1px;
|
||||
@ -79,8 +105,7 @@ body {
|
||||
}
|
||||
|
||||
.shadow {
|
||||
box-shadow: rgba(60, 64, 67, 0.3) 0 1px 3px 0,
|
||||
rgba(60, 64, 67, 0.15) 0 4px 8px 3px;
|
||||
@include shadow;
|
||||
}
|
||||
|
||||
.w_big {
|
||||
@ -308,6 +333,7 @@ body {
|
||||
font-size: 120%;
|
||||
background-color: unset;
|
||||
position: relative;
|
||||
|
||||
&:after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
@ -318,14 +344,17 @@ body {
|
||||
border-radius: 2px;
|
||||
transition: all 0.2s ease-in-out;
|
||||
}
|
||||
|
||||
&:hover:after {
|
||||
border-bottom-color: darken($primary-neutral-light-color, 20%);
|
||||
}
|
||||
|
||||
&.active:after {
|
||||
border-bottom-color: $primary-dark-color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
section {
|
||||
padding: 20px;
|
||||
}
|
||||
|
@ -28,42 +28,20 @@
|
||||
</form>
|
||||
|
||||
{% else %}
|
||||
<p>{% trans trombi=user.trombi_user.trombi %}You already choose to be in that Trombi: {{ trombi }}.{% endtrans %}
|
||||
<p>{% trans trombi=profile.trombi_user.trombi %}You already choose to be in that Trombi: {{ trombi }}.{% endtrans %}
|
||||
<br />
|
||||
<a href="{{ url('trombi:user_tools') }}">{% trans %}Go to my Trombi tools{% endtrans %}</a>
|
||||
</p>
|
||||
{% endif %}
|
||||
|
||||
|
||||
{% if profile.customer %}
|
||||
<h3>{% trans %}Student cards{% endtrans %}</h3>
|
||||
|
||||
{% if profile.customer.student_cards.exists() %}
|
||||
<ul class="student-cards">
|
||||
{% for card in profile.customer.student_cards.all() %}
|
||||
<li>
|
||||
{{ card.uid }}
|
||||
-
|
||||
<a href="{{ url('counter:delete_student_card', customer_id=profile.customer.pk, card_id=card.id) }}">
|
||||
{% trans %}Delete{% endtrans %}
|
||||
</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
<em class="no-cards">{% trans %}No student card registered.{% endtrans %}</em>
|
||||
{% if student_card_fragment %}
|
||||
<h3>{% trans %}Student card{% endtrans %}</h3>
|
||||
{{ student_card_fragment }}
|
||||
<p class="justify">
|
||||
{% trans %}You can add a card by asking at a counter or add it yourself here. If you want to manually
|
||||
add a student card yourself, you'll need a NFC reader. We store the UID of the card which is 14 characters long.{% endtrans %}
|
||||
</p>
|
||||
{% endif %}
|
||||
|
||||
<form class="form form-cards" action="{{ url('counter:add_student_card', customer_id=profile.customer.pk) }}"
|
||||
method="post">
|
||||
{% csrf_token %}
|
||||
{{ student_card_form.as_p() }}
|
||||
<input class="form-submit-btn" type="submit" value="{% trans %}Save{% endtrans %}" />
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
@ -13,22 +13,41 @@
|
||||
#
|
||||
#
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
# Image utils
|
||||
from io import BytesIO
|
||||
from typing import Optional
|
||||
from typing import Any
|
||||
|
||||
import PIL
|
||||
from django.conf import settings
|
||||
from django.core.files.base import ContentFile
|
||||
from django.forms import BaseForm
|
||||
from django.http import HttpRequest
|
||||
from django.template.loader import render_to_string
|
||||
from django.utils.html import SafeString
|
||||
from django.utils.timezone import localdate
|
||||
from PIL import ExifTags
|
||||
from PIL.Image import Image, Resampling
|
||||
|
||||
|
||||
def get_start_of_semester(today: Optional[date] = None) -> date:
|
||||
@dataclass
|
||||
class FormFragmentTemplateData[T: BaseForm]:
|
||||
"""Dataclass used to pre-render form fragments"""
|
||||
|
||||
form: T
|
||||
template: str
|
||||
context: dict[str, Any]
|
||||
|
||||
def render(self, request: HttpRequest) -> SafeString:
|
||||
# Request is needed for csrf_tokens
|
||||
return render_to_string(
|
||||
self.template, context={"form": self.form, **self.context}, request=request
|
||||
)
|
||||
|
||||
|
||||
def get_start_of_semester(today: date | None = None) -> date:
|
||||
"""Return the date of the start of the semester of the given date.
|
||||
If no date is given, return the start date of the current semester.
|
||||
|
||||
@ -58,7 +77,7 @@ def get_start_of_semester(today: Optional[date] = None) -> date:
|
||||
return autumn.replace(year=autumn.year - 1)
|
||||
|
||||
|
||||
def get_semester_code(d: Optional[date] = None) -> str:
|
||||
def get_semester_code(d: date | None = None) -> str:
|
||||
"""Return the semester code of the given date.
|
||||
If no date is given, return the semester code of the current semester.
|
||||
|
||||
|
@ -70,8 +70,8 @@ from core.views.forms import (
|
||||
UserGodfathersForm,
|
||||
UserProfileForm,
|
||||
)
|
||||
from counter.forms import StudentCardForm
|
||||
from counter.models import Refilling, Selling
|
||||
from counter.views.student_card import StudentCardFormView
|
||||
from eboutic.models import Invoice
|
||||
from subscription.models import Subscription
|
||||
from trombi.views import UserTrombiForm
|
||||
@ -559,10 +559,6 @@ class UserPreferencesView(UserTabsMixin, CanEditMixin, UpdateView):
|
||||
context_object_name = "profile"
|
||||
current_tab = "prefs"
|
||||
|
||||
def get_object(self, queryset=None):
|
||||
user = get_object_or_404(User, pk=self.kwargs["user_id"])
|
||||
return user
|
||||
|
||||
def get_form_kwargs(self):
|
||||
kwargs = super().get_form_kwargs()
|
||||
pref = self.object.preferences
|
||||
@ -572,13 +568,12 @@ class UserPreferencesView(UserTabsMixin, CanEditMixin, UpdateView):
|
||||
def get_context_data(self, **kwargs):
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
|
||||
if not (
|
||||
hasattr(self.object, "trombi_user") and self.request.user.trombi_user.trombi
|
||||
):
|
||||
if not hasattr(self.object, "trombi_user"):
|
||||
kwargs["trombi_form"] = UserTrombiForm()
|
||||
|
||||
if hasattr(self.object, "customer"):
|
||||
kwargs["student_card_form"] = StudentCardForm()
|
||||
kwargs["student_card_fragment"] = StudentCardFormView.get_template_data(
|
||||
self.object.customer
|
||||
).render(self.request)
|
||||
return kwargs
|
||||
|
||||
|
||||
|
@ -24,6 +24,12 @@
|
||||
from django.apps import AppConfig
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
PAYMENT_METHOD = [
|
||||
("CHECK", _("Check")),
|
||||
("CASH", _("Cash")),
|
||||
("CARD", _("Credit card")),
|
||||
]
|
||||
|
||||
|
||||
class CounterConfig(AppConfig):
|
||||
name = "counter"
|
||||
|
@ -45,16 +45,12 @@ class BillingInfoForm(forms.ModelForm):
|
||||
|
||||
|
||||
class StudentCardForm(forms.ModelForm):
|
||||
"""Form for adding student cards
|
||||
Only used for user profile since CounterClick is to complicated.
|
||||
"""
|
||||
"""Form for adding student cards"""
|
||||
|
||||
class Meta:
|
||||
model = StudentCard
|
||||
fields = ["uid"]
|
||||
widgets = {
|
||||
"uid": NFCTextInput,
|
||||
}
|
||||
widgets = {"uid": NFCTextInput}
|
||||
|
||||
def clean(self):
|
||||
cleaned_data = super().clean()
|
||||
@ -114,15 +110,9 @@ class GetUserForm(forms.Form):
|
||||
return cleaned_data
|
||||
|
||||
|
||||
class NFCCardForm(forms.Form):
|
||||
student_card_uid = forms.CharField(
|
||||
max_length=StudentCard.UID_SIZE,
|
||||
required=False,
|
||||
widget=NFCTextInput,
|
||||
)
|
||||
|
||||
|
||||
class RefillForm(forms.ModelForm):
|
||||
allowed_refilling_methods = ["CASH", "CARD"]
|
||||
|
||||
error_css_class = "error"
|
||||
required_css_class = "required"
|
||||
amount = forms.FloatField(
|
||||
@ -132,6 +122,21 @@ class RefillForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Refilling
|
||||
fields = ["amount", "payment_method", "bank"]
|
||||
widgets = {"payment_method": forms.RadioSelect}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
self.fields["payment_method"].choices = (
|
||||
method
|
||||
for method in self.fields["payment_method"].choices
|
||||
if method[0] in self.allowed_refilling_methods
|
||||
)
|
||||
if self.fields["payment_method"].initial not in self.allowed_refilling_methods:
|
||||
self.fields["payment_method"].initial = self.allowed_refilling_methods[0]
|
||||
|
||||
if "CHECK" not in self.allowed_refilling_methods:
|
||||
del self.fields["bank"]
|
||||
|
||||
|
||||
class CounterEditForm(forms.ModelForm):
|
||||
@ -153,7 +158,6 @@ class ProductEditForm(forms.ModelForm):
|
||||
"description",
|
||||
"product_type",
|
||||
"code",
|
||||
"parent_product",
|
||||
"buying_groups",
|
||||
"purchase_price",
|
||||
"selling_price",
|
||||
@ -165,7 +169,6 @@ class ProductEditForm(forms.ModelForm):
|
||||
"archived",
|
||||
]
|
||||
widgets = {
|
||||
"parent_product": AutoCompleteSelectMultipleProduct,
|
||||
"product_type": AutoCompleteSelect,
|
||||
"buying_groups": AutoCompleteSelectMultipleGroup,
|
||||
"club": AutoCompleteSelectClub,
|
||||
|
@ -55,7 +55,9 @@ class Command(BaseCommand):
|
||||
customer__user__in=reactivated_users
|
||||
).delete()
|
||||
self._dump_accounts({u.customer for u in users_to_dump})
|
||||
self._send_mails(users_to_dump)
|
||||
self.stdout.write("Accounts dumped")
|
||||
nb_successful_mails = self._send_mails(users_to_dump)
|
||||
self.stdout.write(f"{nb_successful_mails} were successfuly sent.")
|
||||
self.stdout.write("Finished !")
|
||||
|
||||
@staticmethod
|
||||
@ -103,13 +105,14 @@ class Command(BaseCommand):
|
||||
if len(pending_dumps) != len(customer_ids):
|
||||
raise ValueError("One or more accounts were not engaged in a dump process")
|
||||
counter = Counter.objects.get(pk=settings.SITH_COUNTER_ACCOUNT_DUMP_ID)
|
||||
seller = User.objects.get(pk=settings.SITH_ROOT_USER_ID)
|
||||
sales = Selling.objects.bulk_create(
|
||||
[
|
||||
Selling(
|
||||
label="Vidange compte inactif",
|
||||
club=counter.club,
|
||||
counter=counter,
|
||||
seller=None,
|
||||
seller=seller,
|
||||
product=None,
|
||||
customer=account,
|
||||
quantity=1,
|
||||
@ -134,8 +137,12 @@ class Command(BaseCommand):
|
||||
Customer.objects.filter(pk__in=customer_ids).update(amount=0)
|
||||
|
||||
@staticmethod
|
||||
def _send_mails(users: Iterable[User]):
|
||||
"""Send the mails informing users that their account has been dumped."""
|
||||
def _send_mails(users: Iterable[User]) -> int:
|
||||
"""Send the mails informing users that their account has been dumped.
|
||||
|
||||
Returns:
|
||||
The number of emails successfully sent.
|
||||
"""
|
||||
mails = [
|
||||
(
|
||||
_("Your AE account has been emptied"),
|
||||
@ -145,4 +152,4 @@ class Command(BaseCommand):
|
||||
)
|
||||
for user in users
|
||||
]
|
||||
send_mass_mail(mails)
|
||||
return send_mass_mail(mails, fail_silently=True)
|
||||
|
@ -0,0 +1,38 @@
|
||||
# Generated by Django 4.2.17 on 2024-12-09 11:07
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
import accounting.models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [("counter", "0024_accountdump_accountdump_unique_ongoing_dump")]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(model_name="product", name="parent_product"),
|
||||
migrations.AlterField(
|
||||
model_name="product",
|
||||
name="description",
|
||||
field=models.TextField(default="", verbose_name="description"),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="product",
|
||||
name="purchase_price",
|
||||
field=accounting.models.CurrencyField(
|
||||
decimal_places=2,
|
||||
help_text="Initial cost of purchasing the product",
|
||||
max_digits=12,
|
||||
verbose_name="purchase price",
|
||||
),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name="product",
|
||||
name="special_selling_price",
|
||||
field=accounting.models.CurrencyField(
|
||||
decimal_places=2,
|
||||
help_text="Price for barmen during their permanence",
|
||||
max_digits=12,
|
||||
verbose_name="special selling price",
|
||||
),
|
||||
),
|
||||
]
|
53
counter/migrations/0026_alter_studentcard_customer.py
Normal file
53
counter/migrations/0026_alter_studentcard_customer.py
Normal file
@ -0,0 +1,53 @@
|
||||
# Generated by Django 4.2.17 on 2024-12-08 13:30
|
||||
from operator import attrgetter
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
from django.db.migrations.state import StateApps
|
||||
from django.db.models import Count
|
||||
|
||||
|
||||
def delete_duplicates(apps: StateApps, schema_editor):
|
||||
"""Delete cards of users with more than one student cards.
|
||||
|
||||
For all users who have more than one registered student card, all
|
||||
the cards except the last one are deleted.
|
||||
"""
|
||||
Customer = apps.get_model("counter", "Customer")
|
||||
StudentCard = apps.get_model("counter", "StudentCard")
|
||||
customers = (
|
||||
Customer.objects.annotate(nb_cards=Count("student_cards"))
|
||||
.filter(nb_cards__gt=1)
|
||||
.prefetch_related("student_cards")
|
||||
)
|
||||
to_delete = [
|
||||
card.id
|
||||
for customer in customers
|
||||
for card in sorted(customer.student_cards.all(), key=attrgetter("id"))[:-1]
|
||||
]
|
||||
StudentCard.objects.filter(id__in=to_delete).delete()
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [("counter", "0025_remove_product_parent_product_and_more")]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(delete_duplicates, migrations.RunPython.noop),
|
||||
migrations.AlterField(
|
||||
model_name="studentcard",
|
||||
name="customer",
|
||||
field=models.OneToOneField(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
related_name="student_card",
|
||||
to="counter.customer",
|
||||
verbose_name="student card",
|
||||
),
|
||||
),
|
||||
migrations.AlterModelOptions(
|
||||
name="studentcard",
|
||||
options={
|
||||
"verbose_name": "student card",
|
||||
"verbose_name_plural": "student cards",
|
||||
},
|
||||
),
|
||||
]
|
22
counter/migrations/0027_alter_refilling_payment_method.py
Normal file
22
counter/migrations/0027_alter_refilling_payment_method.py
Normal file
@ -0,0 +1,22 @@
|
||||
# Generated by Django 4.2.17 on 2024-12-15 22:21
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("counter", "0026_alter_studentcard_customer"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name="refilling",
|
||||
name="payment_method",
|
||||
field=models.CharField(
|
||||
choices=[("CHECK", "Check"), ("CASH", "Cash"), ("CARD", "Credit card")],
|
||||
default="CARD",
|
||||
max_length=255,
|
||||
verbose_name="payment method",
|
||||
),
|
||||
),
|
||||
]
|
@ -42,7 +42,8 @@ from club.models import Club
|
||||
from core.fields import ResizedImageField
|
||||
from core.models import Group, Notification, User
|
||||
from core.utils import get_start_of_semester
|
||||
from sith.settings import SITH_COUNTER_OFFICES, SITH_MAIN_CLUB
|
||||
from counter.apps import PAYMENT_METHOD
|
||||
from sith.settings import SITH_MAIN_CLUB
|
||||
from subscription.models import Subscription
|
||||
|
||||
|
||||
@ -326,7 +327,7 @@ class Product(models.Model):
|
||||
"""A product, with all its related information."""
|
||||
|
||||
name = models.CharField(_("name"), max_length=64)
|
||||
description = models.TextField(_("description"), blank=True)
|
||||
description = models.TextField(_("description"), default="")
|
||||
product_type = models.ForeignKey(
|
||||
ProductType,
|
||||
related_name="products",
|
||||
@ -336,9 +337,15 @@ class Product(models.Model):
|
||||
on_delete=models.SET_NULL,
|
||||
)
|
||||
code = models.CharField(_("code"), max_length=16, blank=True)
|
||||
purchase_price = CurrencyField(_("purchase price"))
|
||||
purchase_price = CurrencyField(
|
||||
_("purchase price"),
|
||||
help_text=_("Initial cost of purchasing the product"),
|
||||
)
|
||||
selling_price = CurrencyField(_("selling price"))
|
||||
special_selling_price = CurrencyField(_("special selling price"))
|
||||
special_selling_price = CurrencyField(
|
||||
_("special selling price"),
|
||||
help_text=_("Price for barmen during their permanence"),
|
||||
)
|
||||
icon = ResizedImageField(
|
||||
height=70,
|
||||
force_format="WEBP",
|
||||
@ -352,14 +359,6 @@ class Product(models.Model):
|
||||
)
|
||||
limit_age = models.IntegerField(_("limit age"), default=0)
|
||||
tray = models.BooleanField(_("tray price"), default=False)
|
||||
parent_product = models.ForeignKey(
|
||||
"self",
|
||||
related_name="children_products",
|
||||
verbose_name=_("parent product"),
|
||||
null=True,
|
||||
blank=True,
|
||||
on_delete=models.SET_NULL,
|
||||
)
|
||||
buying_groups = models.ManyToManyField(
|
||||
Group, related_name="products", verbose_name=_("buying groups"), blank=True
|
||||
)
|
||||
@ -369,7 +368,7 @@ class Product(models.Model):
|
||||
verbose_name = _("product")
|
||||
|
||||
def __str__(self):
|
||||
return "%s (%s)" % (self.name, self.code)
|
||||
return f"{self.name} ({self.code})"
|
||||
|
||||
def get_absolute_url(self):
|
||||
return reverse("counter:product_list")
|
||||
@ -560,9 +559,6 @@ class Counter(models.Model):
|
||||
"""Show if the counter authorize the refilling with physic money."""
|
||||
if self.type != "BAR":
|
||||
return False
|
||||
if self.id in SITH_COUNTER_OFFICES:
|
||||
# If the counter is either 'AE' or 'BdF', refills are authorized
|
||||
return True
|
||||
# at least one of the barmen is in the AE board
|
||||
ae = Club.objects.get(unix_name=SITH_MAIN_CLUB["unix_name"])
|
||||
return any(ae.get_membership_for(barman) for barman in self.barmen_list)
|
||||
@ -652,6 +648,14 @@ class Counter(models.Model):
|
||||
)
|
||||
)["total"]
|
||||
|
||||
def customer_is_barman(self, customer: Customer | User) -> bool:
|
||||
"""Check if this counter is a `bar` and if the customer is currently logged in.
|
||||
This is useful to compute special prices."""
|
||||
|
||||
# Customer and User are two different tables,
|
||||
# but they share the same primary key
|
||||
return self.type == "BAR" and any(b.pk == customer.pk for b in self.barmen_list)
|
||||
|
||||
|
||||
class RefillingQuerySet(models.QuerySet):
|
||||
def annotate_total(self) -> Self:
|
||||
@ -690,8 +694,8 @@ class Refilling(models.Model):
|
||||
payment_method = models.CharField(
|
||||
_("payment method"),
|
||||
max_length=255,
|
||||
choices=settings.SITH_COUNTER_PAYMENT_METHOD,
|
||||
default="CASH",
|
||||
choices=PAYMENT_METHOD,
|
||||
default="CARD",
|
||||
)
|
||||
bank = models.CharField(
|
||||
_("bank"), max_length=255, choices=settings.SITH_COUNTER_BANK, default="OTHER"
|
||||
@ -1140,20 +1144,22 @@ class StudentCard(models.Model):
|
||||
uid = models.CharField(
|
||||
_("uid"), max_length=UID_SIZE, unique=True, validators=[MinLengthValidator(4)]
|
||||
)
|
||||
customer = models.ForeignKey(
|
||||
customer = models.OneToOneField(
|
||||
Customer,
|
||||
related_name="student_cards",
|
||||
verbose_name=_("student cards"),
|
||||
null=False,
|
||||
blank=False,
|
||||
related_name="student_card",
|
||||
verbose_name=_("student card"),
|
||||
on_delete=models.CASCADE,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
verbose_name = _("student card")
|
||||
verbose_name_plural = _("student cards")
|
||||
|
||||
def __str__(self):
|
||||
return self.uid
|
||||
|
||||
@staticmethod
|
||||
def is_valid(uid):
|
||||
def is_valid(uid: str) -> bool:
|
||||
return (
|
||||
(uid.isupper() or uid.isnumeric())
|
||||
and len(uid) == StudentCard.UID_SIZE
|
||||
|
129
counter/static/bundled/counter/counter-click-index.ts
Normal file
129
counter/static/bundled/counter/counter-click-index.ts
Normal file
@ -0,0 +1,129 @@
|
||||
import { exportToHtml } from "#core:utils/globals";
|
||||
|
||||
interface CounterConfig {
|
||||
csrfToken: string;
|
||||
clickApiUrl: string;
|
||||
sessionBasket: Record<number, BasketItem>;
|
||||
customerBalance: number;
|
||||
customerId: number;
|
||||
}
|
||||
interface BasketItem {
|
||||
// biome-ignore lint/style/useNamingConvention: talking with python
|
||||
bonus_qty: number;
|
||||
price: number;
|
||||
qty: number;
|
||||
}
|
||||
|
||||
exportToHtml("loadCounter", (config: CounterConfig) => {
|
||||
document.addEventListener("alpine:init", () => {
|
||||
Alpine.data("counter", () => ({
|
||||
basket: config.sessionBasket,
|
||||
errors: [],
|
||||
customerBalance: config.customerBalance,
|
||||
|
||||
sumBasket() {
|
||||
if (!this.basket || Object.keys(this.basket).length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const total = Object.values(this.basket).reduce(
|
||||
(acc: number, cur: BasketItem) => acc + cur.qty * cur.price,
|
||||
0,
|
||||
) as number;
|
||||
return total / 100;
|
||||
},
|
||||
|
||||
onRefillingSuccess(event: CustomEvent) {
|
||||
if (event.type !== "htmx:after-request" || event.detail.failed) {
|
||||
return;
|
||||
}
|
||||
this.customerBalance += Number.parseFloat(
|
||||
(event.detail.target.querySelector("#id_amount") as HTMLInputElement).value,
|
||||
);
|
||||
document.getElementById("selling-accordion").click();
|
||||
},
|
||||
|
||||
async handleCode(event: SubmitEvent) {
|
||||
const code = (
|
||||
$(event.target).find("#code_field").val() as string
|
||||
).toUpperCase();
|
||||
if (["FIN", "ANN"].includes(code)) {
|
||||
$(event.target).submit();
|
||||
} else {
|
||||
await this.handleAction(event);
|
||||
}
|
||||
},
|
||||
|
||||
async handleAction(event: SubmitEvent) {
|
||||
const payload = $(event.target).serialize();
|
||||
const request = new Request(config.clickApiUrl, {
|
||||
method: "POST",
|
||||
body: payload,
|
||||
headers: {
|
||||
// biome-ignore lint/style/useNamingConvention: this goes into http headers
|
||||
Accept: "application/json",
|
||||
"X-CSRFToken": config.csrfToken,
|
||||
},
|
||||
});
|
||||
const response = await fetch(request);
|
||||
const json = await response.json();
|
||||
this.basket = json.basket;
|
||||
this.errors = json.errors;
|
||||
$("form.code_form #code_field").val("").focus();
|
||||
},
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
interface Product {
|
||||
value: string;
|
||||
label: string;
|
||||
tags: string;
|
||||
}
|
||||
declare global {
|
||||
const productsAutocomplete: Product[];
|
||||
}
|
||||
|
||||
$(() => {
|
||||
/* Autocompletion in the code field */
|
||||
// biome-ignore lint/suspicious/noExplicitAny: dealing with legacy jquery
|
||||
const codeField: any = $("#code_field");
|
||||
|
||||
let quantity = "";
|
||||
codeField.autocomplete({
|
||||
// biome-ignore lint/suspicious/noExplicitAny: dealing with legacy jquery
|
||||
select: (event: any, ui: any) => {
|
||||
event.preventDefault();
|
||||
codeField.val(quantity + ui.item.value);
|
||||
},
|
||||
// biome-ignore lint/suspicious/noExplicitAny: dealing with legacy jquery
|
||||
focus: (event: any, ui: any) => {
|
||||
event.preventDefault();
|
||||
codeField.val(quantity + ui.item.value);
|
||||
},
|
||||
// biome-ignore lint/suspicious/noExplicitAny: dealing with legacy jquery
|
||||
source: (request: any, response: any) => {
|
||||
// biome-ignore lint/performance/useTopLevelRegex: performance impact is minimal
|
||||
const res = /^(\d+x)?(.*)/i.exec(request.term);
|
||||
quantity = res[1] || "";
|
||||
const search = res[2];
|
||||
// biome-ignore lint/suspicious/noExplicitAny: dealing with legacy jquery
|
||||
const matcher = new RegExp(($ as any).ui.autocomplete.escapeRegex(search), "i");
|
||||
response(
|
||||
$.grep(productsAutocomplete, (value: Product) => {
|
||||
return matcher.test(value.tags);
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
/* Accordion UI between basket and refills */
|
||||
// biome-ignore lint/suspicious/noExplicitAny: dealing with legacy jquery
|
||||
($("#click_form") as any).accordion({
|
||||
heightStyle: "content",
|
||||
activate: () => $(".focus").focus(),
|
||||
});
|
||||
// biome-ignore lint/suspicious/noExplicitAny: dealing with legacy jquery
|
||||
($("#products") as any).tabs();
|
||||
|
||||
codeField.focus();
|
||||
});
|
@ -1,86 +0,0 @@
|
||||
document.addEventListener("alpine:init", () => {
|
||||
Alpine.data("counter", () => ({
|
||||
// biome-ignore lint/correctness/noUndeclaredVariables: defined in counter_click.jinja
|
||||
basket: sessionBasket,
|
||||
errors: [],
|
||||
|
||||
sumBasket() {
|
||||
if (!this.basket || Object.keys(this.basket).length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const total = Object.values(this.basket).reduce(
|
||||
(acc, cur) => acc + cur.qty * cur.price,
|
||||
0,
|
||||
);
|
||||
return total / 100;
|
||||
},
|
||||
|
||||
async handleCode(event) {
|
||||
const code = $(event.target).find("#code_field").val().toUpperCase();
|
||||
if (["FIN", "ANN"].includes(code)) {
|
||||
$(event.target).submit();
|
||||
} else {
|
||||
await this.handleAction(event);
|
||||
}
|
||||
},
|
||||
|
||||
async handleAction(event) {
|
||||
const payload = $(event.target).serialize();
|
||||
// biome-ignore lint/correctness/noUndeclaredVariables: defined in counter_click.jinja
|
||||
const request = new Request(clickApiUrl, {
|
||||
method: "POST",
|
||||
body: payload,
|
||||
headers: {
|
||||
// biome-ignore lint/style/useNamingConvention: this goes into http headers
|
||||
Accept: "application/json",
|
||||
// biome-ignore lint/correctness/noUndeclaredVariables: defined in counter_click.jinja
|
||||
"X-CSRFToken": csrfToken,
|
||||
},
|
||||
});
|
||||
const response = await fetch(request);
|
||||
const json = await response.json();
|
||||
this.basket = json.basket;
|
||||
this.errors = json.errors;
|
||||
$("form.code_form #code_field").val("").focus();
|
||||
},
|
||||
}));
|
||||
});
|
||||
|
||||
$(() => {
|
||||
/* Autocompletion in the code field */
|
||||
const codeField = $("#code_field");
|
||||
|
||||
let quantity = "";
|
||||
codeField.autocomplete({
|
||||
select: (event, ui) => {
|
||||
event.preventDefault();
|
||||
codeField.val(quantity + ui.item.value);
|
||||
},
|
||||
focus: (event, ui) => {
|
||||
event.preventDefault();
|
||||
codeField.val(quantity + ui.item.value);
|
||||
},
|
||||
source: (request, response) => {
|
||||
// biome-ignore lint/performance/useTopLevelRegex: performance impact is minimal
|
||||
const res = /^(\d+x)?(.*)/i.exec(request.term);
|
||||
quantity = res[1] || "";
|
||||
const search = res[2];
|
||||
const matcher = new RegExp($.ui.autocomplete.escapeRegex(search), "i");
|
||||
response(
|
||||
// biome-ignore lint/correctness/noUndeclaredVariables: defined in counter_click.jinja
|
||||
$.grep(productsAutocomplete, (value) => {
|
||||
return matcher.test(value.tags);
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
/* Accordion UI between basket and refills */
|
||||
$("#click_form").accordion({
|
||||
heightStyle: "content",
|
||||
activate: () => $(".focus").focus(),
|
||||
});
|
||||
$("#products").tabs();
|
||||
|
||||
codeField.focus();
|
||||
});
|
@ -6,7 +6,7 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block additional_js %}
|
||||
<script src="{{ static('counter/js/counter_click.js') }}" defer></script>
|
||||
<script type="module" src="{{ static('bundled/counter/counter-click-index.ts') }}"></script>
|
||||
{% endblock %}
|
||||
|
||||
{% block info_boxes %}
|
||||
@ -28,32 +28,11 @@
|
||||
<h5>{% trans %}Customer{% endtrans %}</h5>
|
||||
{{ user_mini_profile(customer.user) }}
|
||||
{{ user_subscription(customer.user) }}
|
||||
<p>{% trans %}Amount: {% endtrans %}{{ customer.amount }} €</p>
|
||||
<form method="post" action="{{ url('counter:click', counter_id=counter.id, user_id=customer.user.id) }}">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="action" value="add_student_card">
|
||||
{% trans %}Add a student card{% endtrans %}
|
||||
{{ student_card_input.student_card_uid }}
|
||||
{% if request.session['not_valid_student_card_uid'] %}
|
||||
<p><strong>{% trans %}This is not a valid student card UID{% endtrans %}</strong></p>
|
||||
{% endif %}
|
||||
<input type="submit" value="{% trans %}Go{% endtrans %}"/>
|
||||
</form>
|
||||
<h6>{% trans %}Registered cards{% endtrans %}</h6>
|
||||
{% if student_cards %}
|
||||
|
||||
<ul>
|
||||
{% for card in student_cards %}
|
||||
<li>{{ card.uid }}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% else %}
|
||||
{% trans %}No card registered{% endtrans %}
|
||||
{% endif %}
|
||||
<p>{% trans %}Amount: {% endtrans %}<span x-text="customerBalance"></span> €</p>
|
||||
</div>
|
||||
|
||||
<div id="click_form">
|
||||
<h5>{% trans %}Selling{% endtrans %}</h5>
|
||||
<div id="click_form" style="width: 20%;">
|
||||
<h5 id="selling-accordion">{% trans %}Selling{% endtrans %}</h5>
|
||||
<div>
|
||||
{% set counter_click_url = url('counter:click', counter_id=counter.id, user_id=customer.user_id) %}
|
||||
|
||||
@ -121,17 +100,32 @@
|
||||
<input type="submit" value="{% trans %}Cancel{% endtrans %}"/>
|
||||
</form>
|
||||
</div>
|
||||
{% if (counter.type == 'BAR' and barmens_can_refill) %}
|
||||
{% if object.type == "BAR" %}
|
||||
<h5>{% trans %}Refilling{% endtrans %}</h5>
|
||||
<div>
|
||||
<form method="post"
|
||||
action="{{ url('counter:click', counter_id=counter.id, user_id=customer.user.id) }}">
|
||||
{% csrf_token %}
|
||||
{{ refill_form.as_p() }}
|
||||
<input type="hidden" name="action" value="refill">
|
||||
<input type="submit" value="{% trans %}Go{% endtrans %}"/>
|
||||
</form>
|
||||
{% if refilling_fragment %}
|
||||
<div
|
||||
@htmx:after-request="onRefillingSuccess"
|
||||
>
|
||||
{{ refilling_fragment }}
|
||||
</div>
|
||||
{% else %}
|
||||
<div>
|
||||
<p class="alert alert-yellow">
|
||||
{% trans trimmed %}
|
||||
As a barman, you are not able to refill any account on your own.
|
||||
An admin should be connected on this counter for that.
|
||||
The customer can refill by using the eboutic.
|
||||
{% endtrans %}
|
||||
</p>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if student_card_fragment %}
|
||||
<h5>{% trans %}Student card{% endtrans %}</h3>
|
||||
<div>
|
||||
{{ student_card_fragment }}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
@ -171,9 +165,6 @@
|
||||
{% block script %}
|
||||
{{ super() }}
|
||||
<script>
|
||||
const csrfToken = "{{ csrf_token }}";
|
||||
const clickApiUrl = "{{ url('counter:click', counter_id=counter.id, user_id=customer.user.id) }}";
|
||||
const sessionBasket = {{ request.session["basket"]|tojson }};
|
||||
const products = {
|
||||
{%- for p in products -%}
|
||||
{{ p.id }}: {
|
||||
@ -192,5 +183,14 @@
|
||||
},
|
||||
{%- endfor %}
|
||||
];
|
||||
window.addEventListener("DOMContentLoaded", () => {
|
||||
loadCounter({
|
||||
csrfToken: "{{ csrf_token }}",
|
||||
clickApiUrl: "{{ url('counter:click', counter_id=counter.id, user_id=customer.user.id) }}",
|
||||
sessionBasket: {{ request.session["basket"]|tojson }},
|
||||
customerBalance: {{ customer.amount }},
|
||||
customerId: {{ customer.pk }},
|
||||
});
|
||||
});
|
||||
</script>
|
||||
{% endblock script %}
|
9
counter/templates/counter/fragments/create_refill.jinja
Normal file
9
counter/templates/counter/fragments/create_refill.jinja
Normal file
@ -0,0 +1,9 @@
|
||||
<form
|
||||
hx-trigger="submit"
|
||||
hx-post="{{ action }}"
|
||||
hx-swap="outerHTML"
|
||||
>
|
||||
{% csrf_token %}
|
||||
{{ form.as_p() }}
|
||||
<input type="submit" value="{% trans %}Go{% endtrans %}"/>
|
||||
</form>
|
@ -0,0 +1,29 @@
|
||||
<div id="student_card_form">
|
||||
{% if not customer.student_card %}
|
||||
<form
|
||||
hx-post="{{ action }}"
|
||||
hx-swap="outerHTML"
|
||||
hx-target="#student_card_form"
|
||||
>
|
||||
{% csrf_token %}
|
||||
{{ form.as_p() }}
|
||||
<input type="submit" value="{% trans %}Go{% endtrans %}"/>
|
||||
</form>
|
||||
<em class="no-cards">{% trans %}No student card registered.{% endtrans %}</em>
|
||||
{% else %}
|
||||
<p>
|
||||
<span tooltip="{% trans uid=customer.student_card.uid %}uid: {{ uid }} {% endtrans %}">
|
||||
{% trans %}Card registered{% endtrans %}
|
||||
<i class="fa fa-check" style="color: green"></i>
|
||||
</span>
|
||||
-
|
||||
<button
|
||||
hx-get="{{ url('counter:delete_student_card', customer_id=customer.pk) }}"
|
||||
hx-swap="outerHTML"
|
||||
hx-target="#student_card_form"
|
||||
>
|
||||
{% trans %}Delete{% endtrans %}
|
||||
</button>
|
||||
</p>
|
||||
{% endif %}
|
||||
</div>
|
@ -0,0 +1,15 @@
|
||||
<div id="student_card_form">
|
||||
<form hx-post="{{ action }}" hx-swap="outerHTML" hx-target="#student_card_form">
|
||||
{% csrf_token %}
|
||||
<p>{% trans obj=object %}Are you sure you want to delete "{{ obj }}"?{% endtrans %}</p>
|
||||
<input type="submit" value="{% trans %}Confirm{% endtrans %}" />
|
||||
<input
|
||||
hx-get="{{ action_cancel }}"
|
||||
hx-swap="outerHTML"
|
||||
hx-target="#student_card_form"
|
||||
type="submit"
|
||||
name="cancel"
|
||||
value="{% trans %}Cancel{% endtrans %}"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
@ -67,17 +67,22 @@ class TestCounter(TestCase):
|
||||
{"code": self.richard.customer.account_id, "counter_token": counter_token},
|
||||
)
|
||||
counter_url = response.get("location")
|
||||
response = self.client.get(response.get("location"))
|
||||
refill_url = reverse(
|
||||
"counter:refilling_create",
|
||||
kwargs={"customer_id": self.richard.customer.pk},
|
||||
)
|
||||
|
||||
response = self.client.get(counter_url)
|
||||
assert ">Richard Batsbak</" in str(response.content)
|
||||
|
||||
self.client.post(
|
||||
counter_url,
|
||||
refill_url,
|
||||
{
|
||||
"action": "refill",
|
||||
"amount": "5",
|
||||
"payment_method": "CASH",
|
||||
"bank": "OTHER",
|
||||
},
|
||||
HTTP_REFERER=counter_url,
|
||||
)
|
||||
self.client.post(counter_url, "action=code&code=BARB", content_type="text/xml")
|
||||
self.client.post(
|
||||
@ -110,15 +115,15 @@ class TestCounter(TestCase):
|
||||
)
|
||||
|
||||
response = self.client.post(
|
||||
counter_url,
|
||||
refill_url,
|
||||
{
|
||||
"action": "refill",
|
||||
"amount": "5",
|
||||
"payment_method": "CASH",
|
||||
"bank": "OTHER",
|
||||
},
|
||||
HTTP_REFERER=counter_url,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.status_code == 302
|
||||
|
||||
self.client.post(
|
||||
reverse("counter:login", kwargs={"counter_id": self.foyer.id}),
|
||||
@ -138,17 +143,23 @@ class TestCounter(TestCase):
|
||||
{"code": self.richard.customer.account_id, "counter_token": counter_token},
|
||||
)
|
||||
counter_url = response.get("location")
|
||||
refill_url = reverse(
|
||||
"counter:refilling_create",
|
||||
kwargs={
|
||||
"customer_id": self.richard.customer.pk,
|
||||
},
|
||||
)
|
||||
|
||||
response = self.client.post(
|
||||
counter_url,
|
||||
refill_url,
|
||||
{
|
||||
"action": "refill",
|
||||
"amount": "5",
|
||||
"payment_method": "CASH",
|
||||
"bank": "OTHER",
|
||||
},
|
||||
HTTP_REFERER=counter_url,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.status_code == 403 # Krophil is not board admin
|
||||
|
||||
def test_annotate_has_barman_queryset(self):
|
||||
"""Test if the custom queryset method `annotate_has_barman` works as intended."""
|
||||
|
@ -1,15 +1,28 @@
|
||||
import itertools
|
||||
import json
|
||||
import string
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.base_user import make_password
|
||||
from django.test import Client, TestCase
|
||||
from django.urls import reverse
|
||||
from django.utils.timezone import now
|
||||
from model_bakery import baker
|
||||
|
||||
from core.baker_recipes import subscriber_user
|
||||
from club.models import Membership
|
||||
from core.baker_recipes import board_user, subscriber_user
|
||||
from core.models import User
|
||||
from counter.baker_recipes import refill_recipe, sale_recipe
|
||||
from counter.models import BillingInfo, Counter, Customer, Refilling, Selling
|
||||
from counter.models import (
|
||||
BillingInfo,
|
||||
Counter,
|
||||
Customer,
|
||||
Refilling,
|
||||
Selling,
|
||||
StudentCard,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@ -162,302 +175,221 @@ class TestStudentCard(TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
cls.krophil = User.objects.get(username="krophil")
|
||||
cls.sli = User.objects.get(username="sli")
|
||||
cls.skia = User.objects.get(username="skia")
|
||||
cls.root = User.objects.get(username="root")
|
||||
cls.customer = subscriber_user.make()
|
||||
cls.barmen = subscriber_user.make(password=make_password("plop"))
|
||||
cls.board_admin = board_user.make()
|
||||
cls.club_admin = baker.make(User)
|
||||
cls.root = baker.make(User, is_superuser=True)
|
||||
cls.subscriber = subscriber_user.make()
|
||||
|
||||
cls.counter = Counter.objects.get(id=2)
|
||||
cls.counter = baker.make(Counter, type="BAR")
|
||||
cls.counter.sellers.add(cls.barmen)
|
||||
|
||||
def setUp(self):
|
||||
# Auto login on counter
|
||||
self.client.post(
|
||||
reverse("counter:login", args=[self.counter.id]),
|
||||
{"username": "krophil", "password": "plop"},
|
||||
cls.club_counter = baker.make(Counter)
|
||||
baker.make(
|
||||
Membership,
|
||||
start_date=now() - timedelta(days=30),
|
||||
club=cls.club_counter.club,
|
||||
role=settings.SITH_CLUB_ROLES_ID["Board member"],
|
||||
user=cls.club_admin,
|
||||
)
|
||||
|
||||
cls.valid_card = baker.make(
|
||||
StudentCard, customer=cls.customer.customer, uid="8A89B82018B0A0"
|
||||
)
|
||||
|
||||
def login_in_counter(self):
|
||||
self.client.post(
|
||||
reverse("counter:login", args=[self.counter.id]),
|
||||
{"username": self.barmen.username, "password": "plop"},
|
||||
)
|
||||
|
||||
def invalid_uids(self) -> list[tuple[str, str]]:
|
||||
"""Return a list of invalid uids, with the associated error message"""
|
||||
return [
|
||||
("8B90734A802A8", ""), # too short
|
||||
(
|
||||
"8B90734A802A8FA",
|
||||
"Assurez-vous que cette valeur comporte au plus 14 caractères (actuellement 15).",
|
||||
), # too long
|
||||
("8b90734a802a9f", ""), # has lowercases
|
||||
(" " * 14, "Ce champ est obligatoire."), # empty
|
||||
(
|
||||
self.customer.customer.student_card.uid,
|
||||
"Un objet Carte étudiante avec ce champ Uid existe déjà.",
|
||||
),
|
||||
]
|
||||
|
||||
def test_search_user_with_student_card(self):
|
||||
self.login_in_counter()
|
||||
response = self.client.post(
|
||||
reverse("counter:details", args=[self.counter.id]),
|
||||
{"code": "9A89B82018B0A0"},
|
||||
{"code": self.valid_card.uid},
|
||||
)
|
||||
|
||||
assert response.url == reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.customer.pk},
|
||||
)
|
||||
|
||||
def test_add_student_card_from_counter(self):
|
||||
# Test card with mixed letters and numbers
|
||||
self.login_in_counter()
|
||||
for uid in ["8B90734A802A8F", "ABCAAAFAAFAAAB", "15248196326518"]:
|
||||
customer = subscriber_user.make().customer
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
|
||||
"counter:add_student_card", kwargs={"customer_id": customer.pk}
|
||||
),
|
||||
{"student_card_uid": "8B90734A802A8F", "action": "add_student_card"},
|
||||
)
|
||||
self.assertContains(response, text="8B90734A802A8F")
|
||||
|
||||
# Test card with only numbers
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
{"uid": uid},
|
||||
HTTP_REFERER=reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
|
||||
kwargs={"counter_id": self.counter.id, "user_id": customer.pk},
|
||||
),
|
||||
{"student_card_uid": "04786547890123", "action": "add_student_card"},
|
||||
)
|
||||
self.assertContains(response, text="04786547890123")
|
||||
|
||||
# Test card with only letters
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
|
||||
),
|
||||
{"student_card_uid": "ABCAAAFAAFAAAB", "action": "add_student_card"},
|
||||
)
|
||||
self.assertContains(response, text="ABCAAAFAAFAAAB")
|
||||
assert response.status_code == 302
|
||||
customer.refresh_from_db()
|
||||
assert hasattr(customer, "student_card")
|
||||
assert customer.student_card.uid == uid
|
||||
|
||||
def test_add_student_card_from_counter_fail(self):
|
||||
# UID too short
|
||||
self.login_in_counter()
|
||||
customer = subscriber_user.make().customer
|
||||
for uid, error_msg in self.invalid_uids():
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
|
||||
"counter:add_student_card", kwargs={"customer_id": customer.pk}
|
||||
),
|
||||
{"uid": uid},
|
||||
HTTP_REFERER=reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": customer.pk},
|
||||
),
|
||||
{"student_card_uid": "8B90734A802A8", "action": "add_student_card"},
|
||||
)
|
||||
self.assertContains(
|
||||
response, text="Ce n'est pas un UID de carte étudiante valide"
|
||||
self.assertContains(response, text="Cet UID est invalide")
|
||||
self.assertContains(response, text=error_msg)
|
||||
customer.refresh_from_db()
|
||||
assert not hasattr(customer, "student_card")
|
||||
|
||||
def test_add_student_card_from_counter_unauthorized(self):
|
||||
def send_valid_request(client, counter_id):
|
||||
return client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.customer.pk}
|
||||
),
|
||||
{"uid": "8B90734A802A8F"},
|
||||
HTTP_REFERER=reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": counter_id, "user_id": self.customer.pk},
|
||||
),
|
||||
)
|
||||
|
||||
# UID too long
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
|
||||
),
|
||||
{"student_card_uid": "8B90734A802A8FA", "action": "add_student_card"},
|
||||
)
|
||||
self.assertContains(
|
||||
response, text="Ce n'est pas un UID de carte étudiante valide"
|
||||
)
|
||||
# Send to a counter where you aren't logged in
|
||||
assert send_valid_request(self.client, self.counter.id).status_code == 403
|
||||
|
||||
# Test with already existing card
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
|
||||
),
|
||||
{"student_card_uid": "9A89B82018B0A0", "action": "add_student_card"},
|
||||
)
|
||||
self.assertContains(
|
||||
response, text="Ce n'est pas un UID de carte étudiante valide"
|
||||
)
|
||||
self.login_in_counter()
|
||||
barman = subscriber_user.make()
|
||||
self.counter.sellers.add(barman)
|
||||
# We want to test sending requests from another counter while
|
||||
# we are currently registered to another counter
|
||||
# so we connect to a counter and
|
||||
# we create a new client, in order to check
|
||||
# that using a client not logged to a counter
|
||||
# where another client is logged still isn't authorized.
|
||||
client = Client()
|
||||
# Send to a counter where you aren't logged in
|
||||
assert send_valid_request(client, self.counter.id).status_code == 403
|
||||
|
||||
# Test with lowercase
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
|
||||
),
|
||||
{"student_card_uid": "8b90734a802a9f", "action": "add_student_card"},
|
||||
)
|
||||
self.assertContains(
|
||||
response, text="Ce n'est pas un UID de carte étudiante valide"
|
||||
)
|
||||
|
||||
# Test with white spaces
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:click",
|
||||
kwargs={"counter_id": self.counter.id, "user_id": self.sli.id},
|
||||
),
|
||||
{"student_card_uid": " ", "action": "add_student_card"},
|
||||
)
|
||||
self.assertContains(
|
||||
response, text="Ce n'est pas un UID de carte étudiante valide"
|
||||
)
|
||||
# Send to a non bar counter
|
||||
client.force_login(self.club_admin)
|
||||
assert send_valid_request(client, self.club_counter.id).status_code == 403
|
||||
|
||||
def test_delete_student_card_with_owner(self):
|
||||
self.client.force_login(self.sli)
|
||||
self.client.force_login(self.customer)
|
||||
self.client.post(
|
||||
reverse(
|
||||
"counter:delete_student_card",
|
||||
kwargs={
|
||||
"customer_id": self.sli.customer.pk,
|
||||
"card_id": self.sli.customer.student_cards.first().id,
|
||||
},
|
||||
kwargs={"customer_id": self.customer.customer.pk},
|
||||
)
|
||||
)
|
||||
assert not self.sli.customer.student_cards.exists()
|
||||
self.customer.customer.refresh_from_db()
|
||||
assert not hasattr(self.customer.customer, "student_card")
|
||||
|
||||
def test_delete_student_card_with_board_member(self):
|
||||
self.client.force_login(self.skia)
|
||||
def test_delete_student_card_with_admin_user(self):
|
||||
"""Test that AE board members and root users can delete student cards"""
|
||||
for user in self.board_admin, self.root:
|
||||
self.client.force_login(user)
|
||||
self.client.post(
|
||||
reverse(
|
||||
"counter:delete_student_card",
|
||||
kwargs={
|
||||
"customer_id": self.sli.customer.pk,
|
||||
"card_id": self.sli.customer.student_cards.first().id,
|
||||
},
|
||||
kwargs={"customer_id": self.customer.customer.pk},
|
||||
)
|
||||
)
|
||||
assert not self.sli.customer.student_cards.exists()
|
||||
self.customer.customer.refresh_from_db()
|
||||
assert not hasattr(self.customer.customer, "student_card")
|
||||
|
||||
def test_delete_student_card_with_root(self):
|
||||
self.client.force_login(self.root)
|
||||
def test_delete_student_card_from_counter(self):
|
||||
self.login_in_counter()
|
||||
self.client.post(
|
||||
reverse(
|
||||
"counter:delete_student_card",
|
||||
kwargs={"customer_id": self.customer.customer.pk},
|
||||
),
|
||||
http_referer=reverse(
|
||||
"counter:click",
|
||||
kwargs={
|
||||
"customer_id": self.sli.customer.pk,
|
||||
"card_id": self.sli.customer.student_cards.first().id,
|
||||
"counter_id": self.counter.id,
|
||||
"user_id": self.customer.customer.pk,
|
||||
},
|
||||
),
|
||||
)
|
||||
)
|
||||
assert not self.sli.customer.student_cards.exists()
|
||||
self.customer.customer.refresh_from_db()
|
||||
assert not hasattr(self.customer.customer, "student_card")
|
||||
|
||||
def test_delete_student_card_fail(self):
|
||||
self.client.force_login(self.krophil)
|
||||
"""Test that non-admin users cannot delete student cards"""
|
||||
self.client.force_login(self.subscriber)
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:delete_student_card",
|
||||
kwargs={
|
||||
"customer_id": self.sli.customer.pk,
|
||||
"card_id": self.sli.customer.student_cards.first().id,
|
||||
},
|
||||
kwargs={"customer_id": self.customer.customer.pk},
|
||||
)
|
||||
)
|
||||
assert response.status_code == 403
|
||||
assert self.sli.customer.student_cards.exists()
|
||||
self.subscriber.customer.refresh_from_db()
|
||||
assert not hasattr(self.subscriber.customer, "student_card")
|
||||
|
||||
def test_add_student_card_from_user_preferences(self):
|
||||
# Test with owner of the card
|
||||
self.client.force_login(self.sli)
|
||||
self.client.post(
|
||||
users = [self.customer, self.board_admin, self.root]
|
||||
uids = ["8B90734A802A8F", "ABCAAAFAAFAAAB", "15248196326518"]
|
||||
for user, uid in itertools.product(users, uids):
|
||||
self.customer.customer.student_card.delete()
|
||||
self.client.force_login(user)
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
"counter:add_student_card",
|
||||
kwargs={"customer_id": self.customer.customer.pk},
|
||||
),
|
||||
{"uid": "8B90734A802A8F"},
|
||||
{"uid": uid},
|
||||
)
|
||||
assert response.status_code == 302
|
||||
response = self.client.get(response.url)
|
||||
|
||||
response = self.client.get(
|
||||
reverse("core:user_prefs", kwargs={"user_id": self.sli.id})
|
||||
)
|
||||
self.assertContains(response, text="8B90734A802A8F")
|
||||
|
||||
# Test with board member
|
||||
self.client.force_login(self.skia)
|
||||
self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
),
|
||||
{"uid": "8B90734A802A8A"},
|
||||
)
|
||||
|
||||
response = self.client.get(
|
||||
reverse("core:user_prefs", kwargs={"user_id": self.sli.id})
|
||||
)
|
||||
self.assertContains(response, text="8B90734A802A8A")
|
||||
|
||||
# Test card with only numbers
|
||||
self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
),
|
||||
{"uid": "04786547890123"},
|
||||
)
|
||||
response = self.client.get(
|
||||
reverse("core:user_prefs", kwargs={"user_id": self.sli.id})
|
||||
)
|
||||
self.assertContains(response, text="04786547890123")
|
||||
|
||||
# Test card with only letters
|
||||
self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
),
|
||||
{"uid": "ABCAAAFAAFAAAB"},
|
||||
)
|
||||
response = self.client.get(
|
||||
reverse("core:user_prefs", kwargs={"user_id": self.sli.id})
|
||||
)
|
||||
self.assertContains(response, text="ABCAAAFAAFAAAB")
|
||||
|
||||
# Test with root
|
||||
self.client.force_login(self.root)
|
||||
self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
),
|
||||
{"uid": "8B90734A802A8B"},
|
||||
)
|
||||
|
||||
response = self.client.get(
|
||||
reverse("core:user_prefs", kwargs={"user_id": self.sli.id})
|
||||
)
|
||||
self.assertContains(response, text="8B90734A802A8B")
|
||||
self.customer.customer.refresh_from_db()
|
||||
assert self.customer.customer.student_card.uid == uid
|
||||
self.assertContains(response, text="Carte enregistrée")
|
||||
|
||||
def test_add_student_card_from_user_preferences_fail(self):
|
||||
self.client.force_login(self.sli)
|
||||
# UID too short
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
),
|
||||
{"uid": "8B90734A802A8"},
|
||||
customer = subscriber_user.make()
|
||||
self.client.force_login(customer)
|
||||
for uid, error_msg in self.invalid_uids():
|
||||
url = reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": customer.customer.pk}
|
||||
)
|
||||
|
||||
response = self.client.post(url, {"uid": uid})
|
||||
self.assertContains(response, text="Cet UID est invalide")
|
||||
|
||||
# UID too long
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
),
|
||||
{"uid": "8B90734A802A8FA"},
|
||||
)
|
||||
self.assertContains(response, text="Cet UID est invalide")
|
||||
|
||||
# Test with already existing card
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
),
|
||||
{"uid": "9A89B82018B0A0"},
|
||||
)
|
||||
self.assertContains(
|
||||
response, text="Un objet Student card avec ce champ Uid existe déjà."
|
||||
)
|
||||
|
||||
# Test with lowercase
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
),
|
||||
{"uid": "8b90734a802a9f"},
|
||||
)
|
||||
self.assertContains(response, text="Cet UID est invalide")
|
||||
|
||||
# Test with white spaces
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
),
|
||||
{"uid": " " * 14},
|
||||
)
|
||||
self.assertContains(response, text="Cet UID est invalide")
|
||||
|
||||
# Test with unauthorized user
|
||||
self.client.force_login(self.krophil)
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.sli.customer.pk}
|
||||
),
|
||||
{"uid": "8B90734A802A8F"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
self.assertContains(response, text=error_msg)
|
||||
customer.refresh_from_db()
|
||||
assert not hasattr(customer.customer, "student_card")
|
||||
|
||||
|
||||
class TestCustomerAccountId(TestCase):
|
||||
|
@ -15,28 +15,16 @@
|
||||
|
||||
from django.urls import path
|
||||
|
||||
from counter.views import (
|
||||
from counter.views.admin import (
|
||||
ActiveProductListView,
|
||||
ArchivedProductListView,
|
||||
CashSummaryEditView,
|
||||
CashSummaryListView,
|
||||
CounterActivityView,
|
||||
CounterCashSummaryView,
|
||||
CounterClick,
|
||||
CounterCreateView,
|
||||
CounterDeleteView,
|
||||
CounterEditPropView,
|
||||
CounterEditView,
|
||||
CounterLastOperationsView,
|
||||
CounterListView,
|
||||
CounterMain,
|
||||
CounterRefillingListView,
|
||||
CounterStatView,
|
||||
EticketCreateView,
|
||||
EticketEditView,
|
||||
EticketListView,
|
||||
EticketPDFView,
|
||||
InvoiceCallView,
|
||||
ProductCreateView,
|
||||
ProductEditView,
|
||||
ProductTypeCreateView,
|
||||
@ -44,15 +32,39 @@ from counter.views import (
|
||||
ProductTypeListView,
|
||||
RefillingDeleteView,
|
||||
SellingDeleteView,
|
||||
)
|
||||
from counter.views.auth import counter_login, counter_logout
|
||||
from counter.views.cash import (
|
||||
CashSummaryEditView,
|
||||
CashSummaryListView,
|
||||
CounterCashSummaryView,
|
||||
)
|
||||
from counter.views.click import CounterClick, RefillingCreateView
|
||||
from counter.views.eticket import (
|
||||
EticketCreateView,
|
||||
EticketEditView,
|
||||
EticketListView,
|
||||
EticketPDFView,
|
||||
)
|
||||
from counter.views.home import (
|
||||
CounterActivityView,
|
||||
CounterLastOperationsView,
|
||||
CounterMain,
|
||||
)
|
||||
from counter.views.invoice import InvoiceCallView
|
||||
from counter.views.student_card import (
|
||||
StudentCardDeleteView,
|
||||
StudentCardFormView,
|
||||
counter_login,
|
||||
counter_logout,
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
path("<int:counter_id>/", CounterMain.as_view(), name="details"),
|
||||
path("<int:counter_id>/click/<int:user_id>/", CounterClick.as_view(), name="click"),
|
||||
path(
|
||||
"refill/<int:customer_id>/",
|
||||
RefillingCreateView.as_view(),
|
||||
name="refilling_create",
|
||||
),
|
||||
path(
|
||||
"<int:counter_id>/last_ops/",
|
||||
CounterLastOperationsView.as_view(),
|
||||
@ -74,7 +86,7 @@ urlpatterns = [
|
||||
name="add_student_card",
|
||||
),
|
||||
path(
|
||||
"customer/<int:customer_id>/card/delete/<int:card_id>/",
|
||||
"customer/<int:customer_id>/card/delete/",
|
||||
StudentCardDeleteView.as_view(),
|
||||
name="delete_student_card",
|
||||
),
|
||||
|
@ -22,14 +22,22 @@ def is_logged_in_counter(request: HttpRequest) -> bool:
|
||||
to the counter)
|
||||
- The current session has a counter token associated with it.
|
||||
- A counter with this token exists.
|
||||
- The counter is open
|
||||
"""
|
||||
referer_ok = (
|
||||
"HTTP_REFERER" in request.META
|
||||
and resolve(urlparse(request.META["HTTP_REFERER"]).path).app_name == "counter"
|
||||
)
|
||||
return (
|
||||
has_token = (
|
||||
(referer_ok or request.resolver_match.app_name == "counter")
|
||||
and "counter_token" in request.session
|
||||
and request.session["counter_token"]
|
||||
and Counter.objects.filter(token=request.session["counter_token"]).exists()
|
||||
)
|
||||
if not has_token:
|
||||
return False
|
||||
|
||||
return (
|
||||
Counter.objects.annotate_is_open()
|
||||
.filter(token=request.session["counter_token"], is_open=True)
|
||||
.exists()
|
||||
)
|
||||
|
1537
counter/views.py
1537
counter/views.py
File diff suppressed because it is too large
Load Diff
0
counter/views/__init__.py
Normal file
0
counter/views/__init__.py
Normal file
288
counter/views/admin.py
Normal file
288
counter/views/admin.py
Normal file
@ -0,0 +1,288 @@
|
||||
#
|
||||
# Copyright 2023 © AE UTBM
|
||||
# ae@utbm.fr / ae.info@utbm.fr
|
||||
#
|
||||
# This file is part of the website of the UTBM Student Association (AE UTBM),
|
||||
# https://ae.utbm.fr.
|
||||
#
|
||||
# You can find the source code of the website at https://github.com/ae-utbm/sith
|
||||
#
|
||||
# LICENSED UNDER THE GNU GENERAL PUBLIC LICENSE VERSION 3 (GPLv3)
|
||||
# SEE : https://raw.githubusercontent.com/ae-utbm/sith/master/LICENSE
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
import itertools
|
||||
from datetime import timedelta
|
||||
from operator import itemgetter
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.db.models import F
|
||||
from django.forms import CheckboxSelectMultiple
|
||||
from django.forms.models import modelform_factory
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.urls import reverse, reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.views.generic import DetailView, ListView
|
||||
from django.views.generic.edit import CreateView, DeleteView, UpdateView
|
||||
|
||||
from core.utils import get_semester_code, get_start_of_semester
|
||||
from core.views import CanEditMixin, CanViewMixin
|
||||
from counter.forms import CounterEditForm, ProductEditForm
|
||||
from counter.models import Counter, Product, ProductType, Refilling, Selling
|
||||
from counter.utils import is_logged_in_counter
|
||||
from counter.views.mixins import CounterAdminMixin, CounterAdminTabsMixin
|
||||
|
||||
|
||||
class CounterListView(CounterAdminTabsMixin, CanViewMixin, ListView):
|
||||
"""A list view for the admins."""
|
||||
|
||||
model = Counter
|
||||
template_name = "counter/counter_list.jinja"
|
||||
current_tab = "counters"
|
||||
|
||||
|
||||
class CounterEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
|
||||
"""Edit a counter's main informations (for the counter's manager)."""
|
||||
|
||||
model = Counter
|
||||
form_class = CounterEditForm
|
||||
pk_url_kwarg = "counter_id"
|
||||
template_name = "core/edit.jinja"
|
||||
current_tab = "counters"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
obj = self.get_object()
|
||||
self.edit_club.append(obj.club)
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse_lazy("counter:admin", kwargs={"counter_id": self.object.id})
|
||||
|
||||
|
||||
class CounterEditPropView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
|
||||
"""Edit a counter's main informations (for the counter's admin)."""
|
||||
|
||||
model = Counter
|
||||
form_class = modelform_factory(Counter, fields=["name", "club", "type"])
|
||||
pk_url_kwarg = "counter_id"
|
||||
template_name = "core/edit.jinja"
|
||||
current_tab = "counters"
|
||||
|
||||
|
||||
class CounterCreateView(CounterAdminTabsMixin, CounterAdminMixin, CreateView):
|
||||
"""Create a counter (for the admins)."""
|
||||
|
||||
model = Counter
|
||||
form_class = modelform_factory(
|
||||
Counter,
|
||||
fields=["name", "club", "type", "products"],
|
||||
widgets={"products": CheckboxSelectMultiple},
|
||||
)
|
||||
template_name = "core/create.jinja"
|
||||
current_tab = "counters"
|
||||
|
||||
|
||||
class CounterDeleteView(CounterAdminTabsMixin, CounterAdminMixin, DeleteView):
|
||||
"""Delete a counter (for the admins)."""
|
||||
|
||||
model = Counter
|
||||
pk_url_kwarg = "counter_id"
|
||||
template_name = "core/delete_confirm.jinja"
|
||||
success_url = reverse_lazy("counter:admin_list")
|
||||
current_tab = "counters"
|
||||
|
||||
|
||||
# Product management
|
||||
|
||||
|
||||
class ProductTypeListView(CounterAdminTabsMixin, CounterAdminMixin, ListView):
|
||||
"""A list view for the admins."""
|
||||
|
||||
model = ProductType
|
||||
template_name = "counter/producttype_list.jinja"
|
||||
current_tab = "product_types"
|
||||
|
||||
|
||||
class ProductTypeCreateView(CounterAdminTabsMixin, CounterAdminMixin, CreateView):
|
||||
"""A create view for the admins."""
|
||||
|
||||
model = ProductType
|
||||
fields = ["name", "description", "comment", "icon", "priority"]
|
||||
template_name = "core/create.jinja"
|
||||
current_tab = "products"
|
||||
|
||||
|
||||
class ProductTypeEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
|
||||
"""An edit view for the admins."""
|
||||
|
||||
model = ProductType
|
||||
template_name = "core/edit.jinja"
|
||||
fields = ["name", "description", "comment", "icon", "priority"]
|
||||
pk_url_kwarg = "type_id"
|
||||
current_tab = "products"
|
||||
|
||||
|
||||
class ProductListView(CounterAdminTabsMixin, CounterAdminMixin, ListView):
|
||||
model = Product
|
||||
queryset = Product.objects.values("id", "name", "code", "product_type__name")
|
||||
template_name = "counter/product_list.jinja"
|
||||
ordering = [
|
||||
F("product_type__priority").desc(nulls_last=True),
|
||||
"product_type",
|
||||
"name",
|
||||
]
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
res = super().get_context_data(**kwargs)
|
||||
res["object_list"] = itertools.groupby(
|
||||
res["object_list"], key=itemgetter("product_type__name")
|
||||
)
|
||||
return res
|
||||
|
||||
|
||||
class ArchivedProductListView(ProductListView):
|
||||
"""A list view for the admins."""
|
||||
|
||||
current_tab = "archive"
|
||||
|
||||
def get_queryset(self):
|
||||
return super().get_queryset().filter(archived=True)
|
||||
|
||||
|
||||
class ActiveProductListView(ProductListView):
|
||||
"""A list view for the admins."""
|
||||
|
||||
current_tab = "products"
|
||||
|
||||
def get_queryset(self):
|
||||
return super().get_queryset().filter(archived=False)
|
||||
|
||||
|
||||
class ProductCreateView(CounterAdminTabsMixin, CounterAdminMixin, CreateView):
|
||||
"""A create view for the admins."""
|
||||
|
||||
model = Product
|
||||
form_class = ProductEditForm
|
||||
template_name = "core/create.jinja"
|
||||
current_tab = "products"
|
||||
|
||||
|
||||
class ProductEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
|
||||
"""An edit view for the admins."""
|
||||
|
||||
model = Product
|
||||
form_class = ProductEditForm
|
||||
pk_url_kwarg = "product_id"
|
||||
template_name = "core/edit.jinja"
|
||||
current_tab = "products"
|
||||
|
||||
|
||||
class RefillingDeleteView(DeleteView):
|
||||
"""Delete a refilling (for the admins)."""
|
||||
|
||||
model = Refilling
|
||||
pk_url_kwarg = "refilling_id"
|
||||
template_name = "core/delete_confirm.jinja"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
"""We have here a very particular right handling, we can't inherit from CanEditPropMixin."""
|
||||
self.object = self.get_object()
|
||||
if timezone.now() - self.object.date <= timedelta(
|
||||
minutes=settings.SITH_LAST_OPERATIONS_LIMIT
|
||||
) and is_logged_in_counter(request):
|
||||
self.success_url = reverse(
|
||||
"counter:details", kwargs={"counter_id": self.object.counter.id}
|
||||
)
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
elif self.object.is_owned_by(request.user):
|
||||
self.success_url = reverse(
|
||||
"core:user_account", kwargs={"user_id": self.object.customer.user.id}
|
||||
)
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
raise PermissionDenied
|
||||
|
||||
|
||||
class SellingDeleteView(DeleteView):
|
||||
"""Delete a selling (for the admins)."""
|
||||
|
||||
model = Selling
|
||||
pk_url_kwarg = "selling_id"
|
||||
template_name = "core/delete_confirm.jinja"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
"""We have here a very particular right handling, we can't inherit from CanEditPropMixin."""
|
||||
self.object = self.get_object()
|
||||
if timezone.now() - self.object.date <= timedelta(
|
||||
minutes=settings.SITH_LAST_OPERATIONS_LIMIT
|
||||
) and is_logged_in_counter(request):
|
||||
self.success_url = reverse(
|
||||
"counter:details", kwargs={"counter_id": self.object.counter.id}
|
||||
)
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
elif self.object.is_owned_by(request.user):
|
||||
self.success_url = reverse(
|
||||
"core:user_account", kwargs={"user_id": self.object.customer.user.id}
|
||||
)
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
raise PermissionDenied
|
||||
|
||||
|
||||
class CounterStatView(DetailView, CounterAdminMixin):
|
||||
"""Show the bar stats."""
|
||||
|
||||
model = Counter
|
||||
pk_url_kwarg = "counter_id"
|
||||
template_name = "counter/stats.jinja"
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
"""Add stats to the context."""
|
||||
counter: Counter = self.object
|
||||
semester_start = get_start_of_semester()
|
||||
office_hours = counter.get_top_barmen()
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
kwargs.update(
|
||||
{
|
||||
"counter": counter,
|
||||
"current_semester": get_semester_code(),
|
||||
"total_sellings": counter.get_total_sales(since=semester_start),
|
||||
"top_customers": counter.get_top_customers(since=semester_start)[:100],
|
||||
"top_barman": office_hours[:100],
|
||||
"top_barman_semester": (
|
||||
office_hours.filter(start__gt=semester_start)[:100]
|
||||
),
|
||||
}
|
||||
)
|
||||
return kwargs
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
try:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
except PermissionDenied:
|
||||
if (
|
||||
request.user.is_root
|
||||
or request.user.is_board_member
|
||||
or self.get_object().is_owned_by(request.user)
|
||||
):
|
||||
return super(CanEditMixin, self).dispatch(request, *args, **kwargs)
|
||||
raise PermissionDenied
|
||||
|
||||
|
||||
class CounterRefillingListView(CounterAdminTabsMixin, CounterAdminMixin, ListView):
|
||||
"""List of refillings on a counter."""
|
||||
|
||||
model = Refilling
|
||||
template_name = "counter/refilling_list.jinja"
|
||||
current_tab = "counters"
|
||||
paginate_by = 30
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.counter = get_object_or_404(Counter, pk=kwargs["counter_id"])
|
||||
self.queryset = Refilling.objects.filter(counter__id=self.counter.id)
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
kwargs["counter"] = self.counter
|
||||
return kwargs
|
53
counter/views/auth.py
Normal file
53
counter/views/auth.py
Normal file
@ -0,0 +1,53 @@
|
||||
#
|
||||
# Copyright 2023 © AE UTBM
|
||||
# ae@utbm.fr / ae.info@utbm.fr
|
||||
#
|
||||
# This file is part of the website of the UTBM Student Association (AE UTBM),
|
||||
# https://ae.utbm.fr.
|
||||
#
|
||||
# You can find the source code of the website at https://github.com/ae-utbm/sith
|
||||
#
|
||||
# LICENSED UNDER THE GNU GENERAL PUBLIC LICENSE VERSION 3 (GPLv3)
|
||||
# SEE : https://raw.githubusercontent.com/ae-utbm/sith/master/LICENSE
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
|
||||
from django.db.models import F
|
||||
from django.http import HttpRequest, HttpResponseRedirect
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.utils import timezone
|
||||
from django.views.decorators.http import require_POST
|
||||
|
||||
from core.views.forms import LoginForm
|
||||
from counter.models import Counter, Permanency
|
||||
|
||||
|
||||
@require_POST
|
||||
def counter_login(request: HttpRequest, counter_id: int) -> HttpResponseRedirect:
|
||||
"""Log a user in a counter.
|
||||
|
||||
A successful login will result in the beginning of a counter duty
|
||||
for the user.
|
||||
"""
|
||||
counter = get_object_or_404(Counter, pk=counter_id)
|
||||
form = LoginForm(request, data=request.POST)
|
||||
if not form.is_valid():
|
||||
return redirect(counter.get_absolute_url() + "?credentials")
|
||||
user = form.get_user()
|
||||
if not counter.sellers.contains(user) or user in counter.barmen_list:
|
||||
return redirect(counter.get_absolute_url() + "?sellers")
|
||||
if len(counter.barmen_list) == 0:
|
||||
counter.gen_token()
|
||||
request.session["counter_token"] = counter.token
|
||||
counter.permanencies.create(user=user, start=timezone.now())
|
||||
return redirect(counter)
|
||||
|
||||
|
||||
@require_POST
|
||||
def counter_logout(request: HttpRequest, counter_id: int) -> HttpResponseRedirect:
|
||||
"""End the permanency of a user in this counter."""
|
||||
Permanency.objects.filter(counter=counter_id, user=request.POST["user_id"]).update(
|
||||
end=F("activity")
|
||||
)
|
||||
return redirect("counter:details", counter_id=counter_id)
|
359
counter/views/cash.py
Normal file
359
counter/views/cash.py
Normal file
@ -0,0 +1,359 @@
|
||||
#
|
||||
# Copyright 2023 © AE UTBM
|
||||
# ae@utbm.fr / ae.info@utbm.fr
|
||||
#
|
||||
# This file is part of the website of the UTBM Student Association (AE UTBM),
|
||||
# https://ae.utbm.fr.
|
||||
#
|
||||
# You can find the source code of the website at https://github.com/ae-utbm/sith
|
||||
#
|
||||
# LICENSED UNDER THE GNU GENERAL PUBLIC LICENSE VERSION 3 (GPLv3)
|
||||
# SEE : https://raw.githubusercontent.com/ae-utbm/sith/master/LICENSE
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
from datetime import datetime
|
||||
from datetime import timezone as tz
|
||||
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.http import HttpResponseRedirect
|
||||
from django.urls import reverse, reverse_lazy
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import DetailView, ListView
|
||||
from django.views.generic.edit import UpdateView
|
||||
|
||||
from core.views import CanViewMixin
|
||||
from counter.forms import CashSummaryFormBase
|
||||
from counter.models import (
|
||||
CashRegisterSummary,
|
||||
CashRegisterSummaryItem,
|
||||
Counter,
|
||||
Refilling,
|
||||
)
|
||||
from counter.utils import is_logged_in_counter
|
||||
from counter.views.mixins import (
|
||||
CounterAdminMixin,
|
||||
CounterAdminTabsMixin,
|
||||
CounterTabsMixin,
|
||||
)
|
||||
|
||||
|
||||
class CashRegisterSummaryForm(forms.Form):
|
||||
"""Provide the cash summary form."""
|
||||
|
||||
ten_cents = forms.IntegerField(label=_("10 cents"), required=False, min_value=0)
|
||||
twenty_cents = forms.IntegerField(label=_("20 cents"), required=False, min_value=0)
|
||||
fifty_cents = forms.IntegerField(label=_("50 cents"), required=False, min_value=0)
|
||||
one_euro = forms.IntegerField(label=_("1 euro"), required=False, min_value=0)
|
||||
two_euros = forms.IntegerField(label=_("2 euros"), required=False, min_value=0)
|
||||
five_euros = forms.IntegerField(label=_("5 euros"), required=False, min_value=0)
|
||||
ten_euros = forms.IntegerField(label=_("10 euros"), required=False, min_value=0)
|
||||
twenty_euros = forms.IntegerField(label=_("20 euros"), required=False, min_value=0)
|
||||
fifty_euros = forms.IntegerField(label=_("50 euros"), required=False, min_value=0)
|
||||
hundred_euros = forms.IntegerField(
|
||||
label=_("100 euros"), required=False, min_value=0
|
||||
)
|
||||
check_1_value = forms.DecimalField(
|
||||
label=_("Check amount"), required=False, min_value=0
|
||||
)
|
||||
check_1_quantity = forms.IntegerField(
|
||||
label=_("Check quantity"), required=False, min_value=0
|
||||
)
|
||||
check_2_value = forms.DecimalField(
|
||||
label=_("Check amount"), required=False, min_value=0
|
||||
)
|
||||
check_2_quantity = forms.IntegerField(
|
||||
label=_("Check quantity"), required=False, min_value=0
|
||||
)
|
||||
check_3_value = forms.DecimalField(
|
||||
label=_("Check amount"), required=False, min_value=0
|
||||
)
|
||||
check_3_quantity = forms.IntegerField(
|
||||
label=_("Check quantity"), required=False, min_value=0
|
||||
)
|
||||
check_4_value = forms.DecimalField(
|
||||
label=_("Check amount"), required=False, min_value=0
|
||||
)
|
||||
check_4_quantity = forms.IntegerField(
|
||||
label=_("Check quantity"), required=False, min_value=0
|
||||
)
|
||||
check_5_value = forms.DecimalField(
|
||||
label=_("Check amount"), required=False, min_value=0
|
||||
)
|
||||
check_5_quantity = forms.IntegerField(
|
||||
label=_("Check quantity"), required=False, min_value=0
|
||||
)
|
||||
comment = forms.CharField(label=_("Comment"), required=False)
|
||||
emptied = forms.BooleanField(label=_("Emptied"), required=False)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
instance = kwargs.pop("instance", None)
|
||||
super().__init__(*args, **kwargs)
|
||||
if instance:
|
||||
self.fields["ten_cents"].initial = (
|
||||
instance.ten_cents.quantity if instance.ten_cents else 0
|
||||
)
|
||||
self.fields["twenty_cents"].initial = (
|
||||
instance.twenty_cents.quantity if instance.twenty_cents else 0
|
||||
)
|
||||
self.fields["fifty_cents"].initial = (
|
||||
instance.fifty_cents.quantity if instance.fifty_cents else 0
|
||||
)
|
||||
self.fields["one_euro"].initial = (
|
||||
instance.one_euro.quantity if instance.one_euro else 0
|
||||
)
|
||||
self.fields["two_euros"].initial = (
|
||||
instance.two_euros.quantity if instance.two_euros else 0
|
||||
)
|
||||
self.fields["five_euros"].initial = (
|
||||
instance.five_euros.quantity if instance.five_euros else 0
|
||||
)
|
||||
self.fields["ten_euros"].initial = (
|
||||
instance.ten_euros.quantity if instance.ten_euros else 0
|
||||
)
|
||||
self.fields["twenty_euros"].initial = (
|
||||
instance.twenty_euros.quantity if instance.twenty_euros else 0
|
||||
)
|
||||
self.fields["fifty_euros"].initial = (
|
||||
instance.fifty_euros.quantity if instance.fifty_euros else 0
|
||||
)
|
||||
self.fields["hundred_euros"].initial = (
|
||||
instance.hundred_euros.quantity if instance.hundred_euros else 0
|
||||
)
|
||||
self.fields["check_1_quantity"].initial = (
|
||||
instance.check_1.quantity if instance.check_1 else 0
|
||||
)
|
||||
self.fields["check_2_quantity"].initial = (
|
||||
instance.check_2.quantity if instance.check_2 else 0
|
||||
)
|
||||
self.fields["check_3_quantity"].initial = (
|
||||
instance.check_3.quantity if instance.check_3 else 0
|
||||
)
|
||||
self.fields["check_4_quantity"].initial = (
|
||||
instance.check_4.quantity if instance.check_4 else 0
|
||||
)
|
||||
self.fields["check_5_quantity"].initial = (
|
||||
instance.check_5.quantity if instance.check_5 else 0
|
||||
)
|
||||
self.fields["check_1_value"].initial = (
|
||||
instance.check_1.value if instance.check_1 else 0
|
||||
)
|
||||
self.fields["check_2_value"].initial = (
|
||||
instance.check_2.value if instance.check_2 else 0
|
||||
)
|
||||
self.fields["check_3_value"].initial = (
|
||||
instance.check_3.value if instance.check_3 else 0
|
||||
)
|
||||
self.fields["check_4_value"].initial = (
|
||||
instance.check_4.value if instance.check_4 else 0
|
||||
)
|
||||
self.fields["check_5_value"].initial = (
|
||||
instance.check_5.value if instance.check_5 else 0
|
||||
)
|
||||
self.fields["comment"].initial = instance.comment
|
||||
self.fields["emptied"].initial = instance.emptied
|
||||
self.instance = instance
|
||||
else:
|
||||
self.instance = None
|
||||
|
||||
def save(self, counter=None):
|
||||
cd = self.cleaned_data
|
||||
summary = self.instance or CashRegisterSummary(
|
||||
counter=counter, user=counter.get_random_barman()
|
||||
)
|
||||
summary.comment = cd["comment"]
|
||||
summary.emptied = cd["emptied"]
|
||||
summary.save()
|
||||
summary.items.all().delete()
|
||||
# Cash
|
||||
if cd["ten_cents"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary, value=0.1, quantity=cd["ten_cents"]
|
||||
).save()
|
||||
if cd["twenty_cents"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary, value=0.2, quantity=cd["twenty_cents"]
|
||||
).save()
|
||||
if cd["fifty_cents"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary, value=0.5, quantity=cd["fifty_cents"]
|
||||
).save()
|
||||
if cd["one_euro"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary, value=1, quantity=cd["one_euro"]
|
||||
).save()
|
||||
if cd["two_euros"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary, value=2, quantity=cd["two_euros"]
|
||||
).save()
|
||||
if cd["five_euros"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary, value=5, quantity=cd["five_euros"]
|
||||
).save()
|
||||
if cd["ten_euros"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary, value=10, quantity=cd["ten_euros"]
|
||||
).save()
|
||||
if cd["twenty_euros"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary, value=20, quantity=cd["twenty_euros"]
|
||||
).save()
|
||||
if cd["fifty_euros"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary, value=50, quantity=cd["fifty_euros"]
|
||||
).save()
|
||||
if cd["hundred_euros"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary, value=100, quantity=cd["hundred_euros"]
|
||||
).save()
|
||||
# Checks
|
||||
if cd["check_1_quantity"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary,
|
||||
value=cd["check_1_value"],
|
||||
quantity=cd["check_1_quantity"],
|
||||
is_check=True,
|
||||
).save()
|
||||
if cd["check_2_quantity"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary,
|
||||
value=cd["check_2_value"],
|
||||
quantity=cd["check_2_quantity"],
|
||||
is_check=True,
|
||||
).save()
|
||||
if cd["check_3_quantity"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary,
|
||||
value=cd["check_3_value"],
|
||||
quantity=cd["check_3_quantity"],
|
||||
is_check=True,
|
||||
).save()
|
||||
if cd["check_4_quantity"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary,
|
||||
value=cd["check_4_value"],
|
||||
quantity=cd["check_4_quantity"],
|
||||
is_check=True,
|
||||
).save()
|
||||
if cd["check_5_quantity"]:
|
||||
CashRegisterSummaryItem(
|
||||
cash_summary=summary,
|
||||
value=cd["check_5_value"],
|
||||
quantity=cd["check_5_quantity"],
|
||||
is_check=True,
|
||||
).save()
|
||||
if summary.items.count() < 1:
|
||||
summary.delete()
|
||||
|
||||
|
||||
class CounterCashSummaryView(CounterTabsMixin, CanViewMixin, DetailView):
|
||||
"""Provide the cash summary form."""
|
||||
|
||||
model = Counter
|
||||
pk_url_kwarg = "counter_id"
|
||||
template_name = "counter/cash_register_summary.jinja"
|
||||
current_tab = "cash_summary"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
"""We have here again a very particular right handling."""
|
||||
self.object = self.get_object()
|
||||
if is_logged_in_counter(request) and self.object.barmen_list:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
return HttpResponseRedirect(
|
||||
reverse("counter:details", kwargs={"counter_id": self.object.id})
|
||||
+ "?bad_location"
|
||||
)
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
self.object = self.get_object()
|
||||
self.form = CashRegisterSummaryForm()
|
||||
return super().get(request, *args, **kwargs)
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
self.object = self.get_object()
|
||||
self.form = CashRegisterSummaryForm(request.POST)
|
||||
if self.form.is_valid():
|
||||
self.form.save(self.object)
|
||||
return HttpResponseRedirect(self.get_success_url())
|
||||
return super().get(request, *args, **kwargs)
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse_lazy("counter:details", kwargs={"counter_id": self.object.id})
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
"""Add form to the context."""
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
kwargs["form"] = self.form
|
||||
return kwargs
|
||||
|
||||
|
||||
class CashSummaryEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
|
||||
"""Edit cash summaries."""
|
||||
|
||||
model = CashRegisterSummary
|
||||
template_name = "counter/cash_register_summary.jinja"
|
||||
context_object_name = "cashsummary"
|
||||
pk_url_kwarg = "cashsummary_id"
|
||||
form_class = CashRegisterSummaryForm
|
||||
current_tab = "cash_summary"
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse("counter:cash_summary_list")
|
||||
|
||||
|
||||
class CashSummaryListView(CounterAdminTabsMixin, CounterAdminMixin, ListView):
|
||||
"""Display a list of cash summaries."""
|
||||
|
||||
model = CashRegisterSummary
|
||||
template_name = "counter/cash_summary_list.jinja"
|
||||
context_object_name = "cashsummary_list"
|
||||
current_tab = "cash_summary"
|
||||
queryset = CashRegisterSummary.objects.all().order_by("-date")
|
||||
paginate_by = settings.SITH_COUNTER_CASH_SUMMARY_LENGTH
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
"""Add sums to the context."""
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
form = CashSummaryFormBase(self.request.GET)
|
||||
kwargs["form"] = form
|
||||
kwargs["summaries_sums"] = {}
|
||||
kwargs["refilling_sums"] = {}
|
||||
for c in Counter.objects.filter(type="BAR").all():
|
||||
refillings = Refilling.objects.filter(counter=c)
|
||||
cashredistersummaries = CashRegisterSummary.objects.filter(counter=c)
|
||||
if form.is_valid() and form.cleaned_data["begin_date"]:
|
||||
refillings = refillings.filter(
|
||||
date__gte=form.cleaned_data["begin_date"]
|
||||
)
|
||||
cashredistersummaries = cashredistersummaries.filter(
|
||||
date__gte=form.cleaned_data["begin_date"]
|
||||
)
|
||||
else:
|
||||
last_summary = (
|
||||
CashRegisterSummary.objects.filter(counter=c, emptied=True)
|
||||
.order_by("-date")
|
||||
.first()
|
||||
)
|
||||
if last_summary:
|
||||
refillings = refillings.filter(date__gt=last_summary.date)
|
||||
cashredistersummaries = cashredistersummaries.filter(
|
||||
date__gt=last_summary.date
|
||||
)
|
||||
else:
|
||||
refillings = refillings.filter(
|
||||
date__gte=datetime(year=1994, month=5, day=17, tzinfo=tz.utc)
|
||||
) # My birth date should be old enough
|
||||
cashredistersummaries = cashredistersummaries.filter(
|
||||
date__gte=datetime(year=1994, month=5, day=17, tzinfo=tz.utc)
|
||||
)
|
||||
if form.is_valid() and form.cleaned_data["end_date"]:
|
||||
refillings = refillings.filter(date__lte=form.cleaned_data["end_date"])
|
||||
cashredistersummaries = cashredistersummaries.filter(
|
||||
date__lte=form.cleaned_data["end_date"]
|
||||
)
|
||||
kwargs["summaries_sums"][c.name] = sum(
|
||||
[s.get_total() for s in cashredistersummaries.all()]
|
||||
)
|
||||
kwargs["refilling_sums"][c.name] = sum([s.amount for s in refillings.all()])
|
||||
return kwargs
|
468
counter/views/click.py
Normal file
468
counter/views/click.py
Normal file
@ -0,0 +1,468 @@
|
||||
#
|
||||
# Copyright 2023 © AE UTBM
|
||||
# ae@utbm.fr / ae.info@utbm.fr
|
||||
#
|
||||
# This file is part of the website of the UTBM Student Association (AE UTBM),
|
||||
# https://ae.utbm.fr.
|
||||
#
|
||||
# You can find the source code of the website at https://github.com/ae-utbm/sith
|
||||
#
|
||||
# LICENSED UNDER THE GNU GENERAL PUBLIC LICENSE VERSION 3 (GPLv3)
|
||||
# SEE : https://raw.githubusercontent.com/ae-utbm/sith/master/LICENSE
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
import re
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.db import DataError, transaction
|
||||
from django.db.models import F
|
||||
from django.http import Http404, HttpResponseRedirect, JsonResponse
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import DetailView, FormView
|
||||
|
||||
from core.utils import FormFragmentTemplateData
|
||||
from core.views import CanViewMixin
|
||||
from counter.forms import RefillForm
|
||||
from counter.models import Counter, Customer, Product, Selling
|
||||
from counter.utils import is_logged_in_counter
|
||||
from counter.views.mixins import CounterTabsMixin
|
||||
from counter.views.student_card import StudentCardFormView
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from core.models import User
|
||||
|
||||
|
||||
class CounterClick(CounterTabsMixin, CanViewMixin, DetailView):
|
||||
"""The click view
|
||||
This is a detail view not to have to worry about loading the counter
|
||||
Everything is made by hand in the post method.
|
||||
"""
|
||||
|
||||
model = Counter
|
||||
queryset = Counter.objects.annotate_is_open()
|
||||
template_name = "counter/counter_click.jinja"
|
||||
pk_url_kwarg = "counter_id"
|
||||
current_tab = "counter"
|
||||
|
||||
def render_to_response(self, *args, **kwargs):
|
||||
if self.is_ajax(self.request):
|
||||
response = {"errors": []}
|
||||
status = HTTPStatus.OK
|
||||
|
||||
if self.request.session["too_young"]:
|
||||
response["errors"].append(_("Too young for that product"))
|
||||
status = HTTPStatus.UNAVAILABLE_FOR_LEGAL_REASONS
|
||||
if self.request.session["not_allowed"]:
|
||||
response["errors"].append(_("Not allowed for that product"))
|
||||
status = HTTPStatus.FORBIDDEN
|
||||
if self.request.session["no_age"]:
|
||||
response["errors"].append(_("No date of birth provided"))
|
||||
status = HTTPStatus.UNAVAILABLE_FOR_LEGAL_REASONS
|
||||
if self.request.session["not_enough"]:
|
||||
response["errors"].append(_("Not enough money"))
|
||||
status = HTTPStatus.PAYMENT_REQUIRED
|
||||
|
||||
if len(response["errors"]) > 1:
|
||||
status = HTTPStatus.BAD_REQUEST
|
||||
|
||||
response["basket"] = self.request.session["basket"]
|
||||
|
||||
return JsonResponse(response, status=status)
|
||||
|
||||
else: # Standard HTML page
|
||||
return super().render_to_response(*args, **kwargs)
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.customer = get_object_or_404(Customer, user__id=self.kwargs["user_id"])
|
||||
obj: Counter = self.get_object()
|
||||
if not self.customer.can_buy:
|
||||
raise Http404
|
||||
if obj.type != "BAR" and not request.user.is_authenticated:
|
||||
raise PermissionDenied
|
||||
if obj.type == "BAR" and (
|
||||
"counter_token" not in request.session
|
||||
or request.session["counter_token"] != obj.token
|
||||
or len(obj.barmen_list) == 0
|
||||
):
|
||||
return redirect(obj)
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
"""Simple get view."""
|
||||
if "basket" not in request.session: # Init the basket session entry
|
||||
request.session["basket"] = {}
|
||||
request.session["basket_total"] = 0
|
||||
request.session["not_enough"] = False # Reset every variable
|
||||
request.session["too_young"] = False
|
||||
request.session["not_allowed"] = False
|
||||
request.session["no_age"] = False
|
||||
ret = super().get(request, *args, **kwargs)
|
||||
if (self.object.type != "BAR" and not request.user.is_authenticated) or (
|
||||
self.object.type == "BAR" and len(self.object.barmen_list) == 0
|
||||
): # Check that at least one barman is logged in
|
||||
ret = self.cancel(request) # Otherwise, go to main view
|
||||
return ret
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
"""Handle the many possibilities of the post request."""
|
||||
self.object = self.get_object()
|
||||
if (self.object.type != "BAR" and not request.user.is_authenticated) or (
|
||||
self.object.type == "BAR" and len(self.object.barmen_list) < 1
|
||||
): # Check that at least one barman is logged in
|
||||
return self.cancel(request)
|
||||
if self.object.type == "BAR" and not (
|
||||
"counter_token" in self.request.session
|
||||
and self.request.session["counter_token"] == self.object.token
|
||||
): # Also check the token to avoid the bar to be stolen
|
||||
return HttpResponseRedirect(
|
||||
reverse_lazy(
|
||||
"counter:details",
|
||||
args=self.args,
|
||||
kwargs={"counter_id": self.object.id},
|
||||
)
|
||||
+ "?bad_location"
|
||||
)
|
||||
if "basket" not in request.session:
|
||||
request.session["basket"] = {}
|
||||
request.session["basket_total"] = 0
|
||||
request.session["not_enough"] = False # Reset every variable
|
||||
request.session["too_young"] = False
|
||||
request.session["not_allowed"] = False
|
||||
request.session["no_age"] = False
|
||||
if self.object.type != "BAR":
|
||||
self.operator = request.user
|
||||
elif self.object.customer_is_barman(self.customer):
|
||||
self.operator = self.customer.user
|
||||
else:
|
||||
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]
|
||||
if action == "add_product":
|
||||
self.add_product(request)
|
||||
elif action == "del_product":
|
||||
self.del_product(request)
|
||||
elif action == "code":
|
||||
return self.parse_code(request)
|
||||
elif action == "cancel":
|
||||
return self.cancel(request)
|
||||
elif action == "finish":
|
||||
return self.finish(request)
|
||||
context = self.get_context_data(object=self.object)
|
||||
return self.render_to_response(context)
|
||||
|
||||
def get_product(self, pid):
|
||||
return Product.objects.filter(pk=int(pid)).first()
|
||||
|
||||
def get_price(self, pid):
|
||||
p = self.get_product(pid)
|
||||
if self.object.customer_is_barman(self.customer):
|
||||
price = p.special_selling_price
|
||||
else:
|
||||
price = p.selling_price
|
||||
return price
|
||||
|
||||
def sum_basket(self, request):
|
||||
total = 0
|
||||
for infos in request.session["basket"].values():
|
||||
total += infos["price"] * infos["qty"]
|
||||
return total / 100
|
||||
|
||||
def get_total_quantity_for_pid(self, request, pid):
|
||||
pid = str(pid)
|
||||
if pid not in request.session["basket"]:
|
||||
return 0
|
||||
return (
|
||||
request.session["basket"][pid]["qty"]
|
||||
+ request.session["basket"][pid]["bonus_qty"]
|
||||
)
|
||||
|
||||
def compute_record_product(self, request, product=None):
|
||||
recorded = 0
|
||||
basket = request.session["basket"]
|
||||
|
||||
if product:
|
||||
if product.is_record_product:
|
||||
recorded -= 1
|
||||
elif product.is_unrecord_product:
|
||||
recorded += 1
|
||||
|
||||
for p in basket:
|
||||
bproduct = self.get_product(str(p))
|
||||
if bproduct.is_record_product:
|
||||
recorded -= basket[p]["qty"]
|
||||
elif bproduct.is_unrecord_product:
|
||||
recorded += basket[p]["qty"]
|
||||
return recorded
|
||||
|
||||
def is_record_product_ok(self, request, product):
|
||||
return self.customer.can_record_more(
|
||||
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):
|
||||
"""Add a product to the basket
|
||||
q is the quantity passed as integer
|
||||
p is the product id, passed as an integer.
|
||||
"""
|
||||
pid = p or parse_qs(request.body.decode())["product_id"][0]
|
||||
pid = str(pid)
|
||||
price = self.get_price(pid)
|
||||
total = self.sum_basket(request)
|
||||
product: Product = self.get_product(pid)
|
||||
user: User = self.customer.user
|
||||
buying_groups = list(product.buying_groups.values_list("pk", flat=True))
|
||||
can_buy = len(buying_groups) == 0 or any(
|
||||
user.is_in_group(pk=group_id) for group_id in buying_groups
|
||||
)
|
||||
if not can_buy:
|
||||
request.session["not_allowed"] = True
|
||||
return False
|
||||
bq = 0 # Bonus quantity, for trays
|
||||
if (
|
||||
product.tray
|
||||
): # Handle the tray to adjust the quantity q to add and the bonus quantity bq
|
||||
total_qty_mod_6 = self.get_total_quantity_for_pid(request, pid) % 6
|
||||
bq = int((total_qty_mod_6 + q) / 6) # Integer division
|
||||
q -= bq
|
||||
if self.customer.amount < (
|
||||
total + round(q * float(price), 2)
|
||||
): # Check for enough money
|
||||
request.session["not_enough"] = True
|
||||
return False
|
||||
if product.is_unrecord_product and not self.is_record_product_ok(
|
||||
request, product
|
||||
):
|
||||
request.session["not_allowed"] = True
|
||||
return False
|
||||
if product.limit_age >= 18 and not user.date_of_birth:
|
||||
request.session["no_age"] = True
|
||||
return False
|
||||
if product.limit_age >= 18 and user.is_banned_alcohol:
|
||||
request.session["not_allowed"] = True
|
||||
return False
|
||||
if user.is_banned_counter:
|
||||
request.session["not_allowed"] = True
|
||||
return False
|
||||
if (
|
||||
user.date_of_birth and self.customer.user.get_age() < product.limit_age
|
||||
): # Check if affordable
|
||||
request.session["too_young"] = True
|
||||
return False
|
||||
if pid in request.session["basket"]: # Add if already in basket
|
||||
request.session["basket"][pid]["qty"] += q
|
||||
request.session["basket"][pid]["bonus_qty"] += bq
|
||||
else: # or create if not
|
||||
request.session["basket"][pid] = {
|
||||
"qty": q,
|
||||
"price": int(price * 100),
|
||||
"bonus_qty": bq,
|
||||
}
|
||||
request.session.modified = True
|
||||
return True
|
||||
|
||||
def del_product(self, request):
|
||||
"""Delete a product from the basket."""
|
||||
pid = parse_qs(request.body.decode())["product_id"][0]
|
||||
product = self.get_product(pid)
|
||||
if pid in request.session["basket"]:
|
||||
if (
|
||||
product.tray
|
||||
and (self.get_total_quantity_for_pid(request, pid) % 6 == 0)
|
||||
and request.session["basket"][pid]["bonus_qty"]
|
||||
):
|
||||
request.session["basket"][pid]["bonus_qty"] -= 1
|
||||
else:
|
||||
request.session["basket"][pid]["qty"] -= 1
|
||||
if request.session["basket"][pid]["qty"] <= 0:
|
||||
del request.session["basket"][pid]
|
||||
request.session.modified = True
|
||||
|
||||
def parse_code(self, request):
|
||||
"""Parse the string entered by the barman.
|
||||
|
||||
This can be of two forms :
|
||||
- `<str>`, where the string is the code of the product
|
||||
- `<int>X<str>`, where the integer is the quantity and str the code.
|
||||
"""
|
||||
string = parse_qs(request.body.decode()).get("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]+)$")
|
||||
m = regex.match(string)
|
||||
if m is not None:
|
||||
nb = m.group("nb")
|
||||
code = m.group("code")
|
||||
nb = int(nb) if nb is not None else 1
|
||||
p = self.object.products.filter(code=code).first()
|
||||
if p is not None:
|
||||
self.add_product(request, nb, p.id)
|
||||
context = self.get_context_data(object=self.object)
|
||||
return self.render_to_response(context)
|
||||
|
||||
def finish(self, request):
|
||||
"""Finish the click session, and validate the basket."""
|
||||
with transaction.atomic():
|
||||
request.session["last_basket"] = []
|
||||
if self.sum_basket(request) > self.customer.amount:
|
||||
raise DataError(_("You have not enough money to buy all the basket"))
|
||||
|
||||
for pid, infos in request.session["basket"].items():
|
||||
# This duplicates code for DB optimization (prevent to load many times the same object)
|
||||
p = Product.objects.filter(pk=pid).first()
|
||||
if self.object.customer_is_barman(self.customer):
|
||||
uprice = p.special_selling_price
|
||||
else:
|
||||
uprice = p.selling_price
|
||||
request.session["last_basket"].append(
|
||||
"%d x %s" % (infos["qty"] + infos["bonus_qty"], p.name)
|
||||
)
|
||||
s = Selling(
|
||||
label=p.name,
|
||||
product=p,
|
||||
club=p.club,
|
||||
counter=self.object,
|
||||
unit_price=uprice,
|
||||
quantity=infos["qty"],
|
||||
seller=self.operator,
|
||||
customer=self.customer,
|
||||
)
|
||||
s.save()
|
||||
if infos["bonus_qty"]:
|
||||
s = Selling(
|
||||
label=p.name + " (Plateau)",
|
||||
product=p,
|
||||
club=p.club,
|
||||
counter=self.object,
|
||||
unit_price=0,
|
||||
quantity=infos["bonus_qty"],
|
||||
seller=self.operator,
|
||||
customer=self.customer,
|
||||
)
|
||||
s.save()
|
||||
self.customer.recorded_products -= self.compute_record_product(request)
|
||||
self.customer.save()
|
||||
request.session["last_customer"] = self.customer.user.get_display_name()
|
||||
request.session["last_total"] = "%0.2f" % self.sum_basket(request)
|
||||
request.session["new_customer_amount"] = str(self.customer.amount)
|
||||
del request.session["basket"]
|
||||
request.session.modified = True
|
||||
kwargs = {"counter_id": self.object.id}
|
||||
return HttpResponseRedirect(
|
||||
reverse_lazy("counter:details", args=self.args, kwargs=kwargs)
|
||||
)
|
||||
|
||||
def cancel(self, request):
|
||||
"""Cancel the click session."""
|
||||
kwargs = {"counter_id": self.object.id}
|
||||
request.session.pop("basket", None)
|
||||
return HttpResponseRedirect(
|
||||
reverse_lazy("counter:details", args=self.args, kwargs=kwargs)
|
||||
)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
"""Add customer to the context."""
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
products = self.object.products.select_related("product_type")
|
||||
if self.object.customer_is_barman(self.customer):
|
||||
products = products.annotate(price=F("special_selling_price"))
|
||||
else:
|
||||
products = products.annotate(price=F("selling_price"))
|
||||
kwargs["products"] = products
|
||||
kwargs["categories"] = {}
|
||||
for product in kwargs["products"]:
|
||||
if product.product_type:
|
||||
kwargs["categories"].setdefault(product.product_type, []).append(
|
||||
product
|
||||
)
|
||||
kwargs["customer"] = self.customer
|
||||
kwargs["basket_total"] = self.sum_basket(self.request)
|
||||
|
||||
if self.object.type == "BAR":
|
||||
kwargs["student_card_fragment"] = StudentCardFormView.get_template_data(
|
||||
self.customer
|
||||
).render(self.request)
|
||||
|
||||
if self.object.can_refill():
|
||||
kwargs["refilling_fragment"] = RefillingCreateView.get_template_data(
|
||||
self.customer
|
||||
).render(self.request)
|
||||
return kwargs
|
||||
|
||||
|
||||
class RefillingCreateView(FormView):
|
||||
"""This is a fragment only view which integrates with counter_click.jinja"""
|
||||
|
||||
form_class = RefillForm
|
||||
template_name = "counter/fragments/create_refill.jinja"
|
||||
|
||||
@classmethod
|
||||
def get_template_data(
|
||||
cls, customer: Customer, *, form_instance: form_class | None = None
|
||||
) -> FormFragmentTemplateData[form_class]:
|
||||
return FormFragmentTemplateData(
|
||||
form=form_instance if form_instance else cls.form_class(),
|
||||
template=cls.template_name,
|
||||
context={
|
||||
"action": reverse_lazy(
|
||||
"counter:refilling_create", kwargs={"customer_id": customer.pk}
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.customer: Customer = get_object_or_404(Customer, pk=kwargs["customer_id"])
|
||||
if not self.customer.can_buy:
|
||||
raise Http404
|
||||
|
||||
if not is_logged_in_counter(request):
|
||||
raise PermissionDenied
|
||||
|
||||
self.counter: Counter = get_object_or_404(
|
||||
Counter, token=request.session["counter_token"]
|
||||
)
|
||||
|
||||
if not self.counter.can_refill():
|
||||
raise PermissionDenied
|
||||
|
||||
if self.counter.customer_is_barman(self.customer):
|
||||
self.operator = self.customer.user
|
||||
else:
|
||||
self.operator = self.counter.get_random_barman()
|
||||
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def form_valid(self, form):
|
||||
res = super().form_valid(form)
|
||||
form.clean()
|
||||
form.instance.counter = self.counter
|
||||
form.instance.operator = self.operator
|
||||
form.instance.customer = self.customer
|
||||
form.instance.save()
|
||||
return res
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
data = self.get_template_data(self.customer, form_instance=context["form"])
|
||||
context.update(data.context)
|
||||
return context
|
||||
|
||||
def get_success_url(self, **kwargs):
|
||||
return self.request.path
|
141
counter/views/eticket.py
Normal file
141
counter/views/eticket.py
Normal file
@ -0,0 +1,141 @@
|
||||
#
|
||||
# Copyright 2023 © AE UTBM
|
||||
# ae@utbm.fr / ae.info@utbm.fr
|
||||
#
|
||||
# This file is part of the website of the UTBM Student Association (AE UTBM),
|
||||
# https://ae.utbm.fr.
|
||||
#
|
||||
# You can find the source code of the website at https://github.com/ae-utbm/sith
|
||||
#
|
||||
# LICENSED UNDER THE GNU GENERAL PUBLIC LICENSE VERSION 3 (GPLv3)
|
||||
# SEE : https://raw.githubusercontent.com/ae-utbm/sith/master/LICENSE
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
|
||||
from django.http import Http404, HttpResponse
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import DetailView, ListView
|
||||
from django.views.generic.edit import CreateView, UpdateView
|
||||
|
||||
from core.views import CanViewMixin
|
||||
from counter.forms import EticketForm
|
||||
from counter.models import Eticket, Selling
|
||||
from counter.views.mixins import CounterAdminMixin, CounterAdminTabsMixin
|
||||
|
||||
|
||||
class EticketListView(CounterAdminTabsMixin, CounterAdminMixin, ListView):
|
||||
"""A list view for the admins."""
|
||||
|
||||
model = Eticket
|
||||
template_name = "counter/eticket_list.jinja"
|
||||
ordering = ["id"]
|
||||
current_tab = "etickets"
|
||||
|
||||
|
||||
class EticketCreateView(CounterAdminTabsMixin, CounterAdminMixin, CreateView):
|
||||
"""Create an eticket."""
|
||||
|
||||
model = Eticket
|
||||
template_name = "core/create.jinja"
|
||||
form_class = EticketForm
|
||||
current_tab = "etickets"
|
||||
|
||||
|
||||
class EticketEditView(CounterAdminTabsMixin, CounterAdminMixin, UpdateView):
|
||||
"""Edit an eticket."""
|
||||
|
||||
model = Eticket
|
||||
template_name = "core/edit.jinja"
|
||||
form_class = EticketForm
|
||||
pk_url_kwarg = "eticket_id"
|
||||
current_tab = "etickets"
|
||||
|
||||
|
||||
class EticketPDFView(CanViewMixin, DetailView):
|
||||
"""Display the PDF of an eticket."""
|
||||
|
||||
model = Selling
|
||||
pk_url_kwarg = "selling_id"
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
from reportlab.graphics import renderPDF
|
||||
from reportlab.graphics.barcode.qr import QrCodeWidget
|
||||
from reportlab.graphics.shapes import Drawing
|
||||
from reportlab.lib.units import cm
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
if not (
|
||||
hasattr(self.object, "product") and hasattr(self.object.product, "eticket")
|
||||
):
|
||||
raise Http404
|
||||
|
||||
eticket = self.object.product.eticket
|
||||
user = self.object.customer.user
|
||||
code = "%s %s %s %s" % (
|
||||
self.object.customer.user.id,
|
||||
self.object.product.id,
|
||||
self.object.id,
|
||||
self.object.quantity,
|
||||
)
|
||||
code += " " + eticket.get_hash(code)[:8].upper()
|
||||
response = HttpResponse(content_type="application/pdf")
|
||||
response["Content-Disposition"] = 'filename="eticket.pdf"'
|
||||
p = canvas.Canvas(response)
|
||||
p.setTitle("Eticket")
|
||||
im = ImageReader("core/static/core/img/eticket.jpg")
|
||||
width, height = im.getSize()
|
||||
size = max(width, height)
|
||||
width = 8 * cm * width / size
|
||||
height = 8 * cm * height / size
|
||||
p.drawImage(im, 10 * cm, 25 * cm, width, height)
|
||||
if eticket.banner:
|
||||
im = ImageReader(eticket.banner)
|
||||
width, height = im.getSize()
|
||||
size = max(width, height)
|
||||
width = 6 * cm * width / size
|
||||
height = 6 * cm * height / size
|
||||
p.drawImage(im, 1 * cm, 25 * cm, width, height)
|
||||
if user.profile_pict:
|
||||
im = ImageReader(user.profile_pict.file)
|
||||
width, height = im.getSize()
|
||||
size = max(width, height)
|
||||
width = 150 * width / size
|
||||
height = 150 * height / size
|
||||
p.drawImage(im, 10.5 * cm - width / 2, 16 * cm, width, height)
|
||||
if eticket.event_title:
|
||||
p.setFont("Helvetica-Bold", 20)
|
||||
p.drawCentredString(10.5 * cm, 23.6 * cm, eticket.event_title)
|
||||
if eticket.event_date:
|
||||
p.setFont("Helvetica-Bold", 16)
|
||||
p.drawCentredString(
|
||||
10.5 * cm, 22.6 * cm, eticket.event_date.strftime("%d %b %Y")
|
||||
) # FIXME with a locale
|
||||
p.setFont("Helvetica-Bold", 14)
|
||||
p.drawCentredString(
|
||||
10.5 * cm,
|
||||
15 * cm,
|
||||
"%s : %d %s"
|
||||
% (user.get_display_name(), self.object.quantity, str(_("people(s)"))),
|
||||
)
|
||||
p.setFont("Courier-Bold", 14)
|
||||
qrcode = QrCodeWidget(code)
|
||||
bounds = qrcode.getBounds()
|
||||
width = bounds[2] - bounds[0]
|
||||
height = bounds[3] - bounds[1]
|
||||
d = Drawing(260, 260, transform=[260.0 / width, 0, 0, 260.0 / height, 0, 0])
|
||||
d.add(qrcode)
|
||||
renderPDF.draw(d, p, 10.5 * cm - 130, 6.1 * cm)
|
||||
p.drawCentredString(10.5 * cm, 6 * cm, code)
|
||||
|
||||
partners = ImageReader("core/static/core/img/partners.png")
|
||||
width, height = partners.getSize()
|
||||
size = max(width, height)
|
||||
width = width * 2 / 3
|
||||
height = height * 2 / 3
|
||||
p.drawImage(partners, 0 * cm, 0 * cm, width, height)
|
||||
|
||||
p.showPage()
|
||||
p.save()
|
||||
return response
|
147
counter/views/home.py
Normal file
147
counter/views/home.py
Normal file
@ -0,0 +1,147 @@
|
||||
#
|
||||
# Copyright 2023 © AE UTBM
|
||||
# ae@utbm.fr / ae.info@utbm.fr
|
||||
#
|
||||
# This file is part of the website of the UTBM Student Association (AE UTBM),
|
||||
# https://ae.utbm.fr.
|
||||
#
|
||||
# You can find the source code of the website at https://github.com/ae-utbm/sith
|
||||
#
|
||||
# LICENSED UNDER THE GNU GENERAL PUBLIC LICENSE VERSION 3 (GPLv3)
|
||||
# SEE : https://raw.githubusercontent.com/ae-utbm/sith/master/LICENSE
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
from datetime import timedelta
|
||||
|
||||
from django.conf import settings
|
||||
from django.http import HttpResponseRedirect
|
||||
from django.urls import reverse, reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic import DetailView
|
||||
from django.views.generic.edit import FormMixin, ProcessFormView
|
||||
|
||||
from core.views import CanViewMixin
|
||||
from core.views.forms import LoginForm
|
||||
from counter.forms import GetUserForm
|
||||
from counter.models import Counter
|
||||
from counter.utils import is_logged_in_counter
|
||||
from counter.views.mixins import CounterTabsMixin
|
||||
|
||||
|
||||
class CounterMain(
|
||||
CounterTabsMixin, CanViewMixin, DetailView, ProcessFormView, FormMixin
|
||||
):
|
||||
"""The public (barman) view."""
|
||||
|
||||
model = Counter
|
||||
template_name = "counter/counter_main.jinja"
|
||||
pk_url_kwarg = "counter_id"
|
||||
form_class = (
|
||||
GetUserForm # Form to enter a client code and get the corresponding user id
|
||||
)
|
||||
current_tab = "counter"
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
self.object = self.get_object()
|
||||
if self.object.type == "BAR" and not (
|
||||
"counter_token" in self.request.session
|
||||
and self.request.session["counter_token"] == self.object.token
|
||||
): # Check the token to avoid the bar to be stolen
|
||||
return HttpResponseRedirect(
|
||||
reverse_lazy(
|
||||
"counter:details",
|
||||
args=self.args,
|
||||
kwargs={"counter_id": self.object.id},
|
||||
)
|
||||
+ "?bad_location"
|
||||
)
|
||||
return super().post(request, *args, **kwargs)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
"""We handle here the login form for the barman."""
|
||||
if self.request.method == "POST":
|
||||
self.object = self.get_object()
|
||||
self.object.update_activity()
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
kwargs["login_form"] = LoginForm()
|
||||
kwargs["login_form"].fields["username"].widget.attrs["autofocus"] = True
|
||||
kwargs[
|
||||
"login_form"
|
||||
].cleaned_data = {} # add_error fails if there are no cleaned_data
|
||||
if "credentials" in self.request.GET:
|
||||
kwargs["login_form"].add_error(None, _("Bad credentials"))
|
||||
if "sellers" in self.request.GET:
|
||||
kwargs["login_form"].add_error(None, _("User is not barman"))
|
||||
kwargs["form"] = self.get_form()
|
||||
kwargs["form"].cleaned_data = {} # same as above
|
||||
if "bad_location" in self.request.GET:
|
||||
kwargs["form"].add_error(
|
||||
None, _("Bad location, someone is already logged in somewhere else")
|
||||
)
|
||||
if self.object.type == "BAR":
|
||||
kwargs["barmen"] = self.object.barmen_list
|
||||
elif self.request.user.is_authenticated:
|
||||
kwargs["barmen"] = [self.request.user]
|
||||
if "last_basket" in self.request.session:
|
||||
kwargs["last_basket"] = self.request.session.pop("last_basket")
|
||||
kwargs["last_customer"] = self.request.session.pop("last_customer")
|
||||
kwargs["last_total"] = self.request.session.pop("last_total")
|
||||
kwargs["new_customer_amount"] = self.request.session.pop(
|
||||
"new_customer_amount"
|
||||
)
|
||||
return kwargs
|
||||
|
||||
def form_valid(self, form):
|
||||
"""We handle here the redirection, passing the user id of the asked customer."""
|
||||
self.kwargs["user_id"] = form.cleaned_data["user_id"]
|
||||
return super().form_valid(form)
|
||||
|
||||
def get_success_url(self):
|
||||
return reverse_lazy("counter:click", args=self.args, kwargs=self.kwargs)
|
||||
|
||||
|
||||
class CounterLastOperationsView(CounterTabsMixin, CanViewMixin, DetailView):
|
||||
"""Provide the last operations to allow barmen to delete them."""
|
||||
|
||||
model = Counter
|
||||
pk_url_kwarg = "counter_id"
|
||||
template_name = "counter/last_ops.jinja"
|
||||
current_tab = "last_ops"
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
"""We have here again a very particular right handling."""
|
||||
self.object = self.get_object()
|
||||
if is_logged_in_counter(request) and self.object.barmen_list:
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
return HttpResponseRedirect(
|
||||
reverse("counter:details", kwargs={"counter_id": self.object.id})
|
||||
+ "?bad_location"
|
||||
)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
"""Add form to the context."""
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
threshold = timezone.now() - timedelta(
|
||||
minutes=settings.SITH_LAST_OPERATIONS_LIMIT
|
||||
)
|
||||
kwargs["last_refillings"] = (
|
||||
self.object.refillings.filter(date__gte=threshold)
|
||||
.select_related("operator", "customer__user")
|
||||
.order_by("-id")[:20]
|
||||
)
|
||||
kwargs["last_sellings"] = (
|
||||
self.object.sellings.filter(date__gte=threshold)
|
||||
.select_related("seller", "customer__user")
|
||||
.order_by("-id")[:20]
|
||||
)
|
||||
return kwargs
|
||||
|
||||
|
||||
class CounterActivityView(DetailView):
|
||||
"""Show the bar activity."""
|
||||
|
||||
model = Counter
|
||||
pk_url_kwarg = "counter_id"
|
||||
template_name = "counter/activity.jinja"
|
89
counter/views/invoice.py
Normal file
89
counter/views/invoice.py
Normal file
@ -0,0 +1,89 @@
|
||||
#
|
||||
# Copyright 2023 © AE UTBM
|
||||
# ae@utbm.fr / ae.info@utbm.fr
|
||||
#
|
||||
# This file is part of the website of the UTBM Student Association (AE UTBM),
|
||||
# https://ae.utbm.fr.
|
||||
#
|
||||
# You can find the source code of the website at https://github.com/ae-utbm/sith
|
||||
#
|
||||
# LICENSED UNDER THE GNU GENERAL PUBLIC LICENSE VERSION 3 (GPLv3)
|
||||
# SEE : https://raw.githubusercontent.com/ae-utbm/sith/master/LICENSE
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import timezone as tz
|
||||
|
||||
from django.db.models import F
|
||||
from django.utils import timezone
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
from accounting.models import CurrencyField
|
||||
from counter.models import Refilling, Selling
|
||||
from counter.views.mixins import CounterAdminMixin, CounterAdminTabsMixin
|
||||
|
||||
|
||||
class InvoiceCallView(CounterAdminTabsMixin, CounterAdminMixin, TemplateView):
|
||||
template_name = "counter/invoices_call.jinja"
|
||||
current_tab = "invoices_call"
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
"""Add sums to the context."""
|
||||
kwargs = super().get_context_data(**kwargs)
|
||||
kwargs["months"] = Selling.objects.datetimes("date", "month", order="DESC")
|
||||
if "month" in self.request.GET:
|
||||
start_date = datetime.strptime(self.request.GET["month"], "%Y-%m")
|
||||
else:
|
||||
start_date = datetime(
|
||||
year=timezone.now().year,
|
||||
month=(timezone.now().month + 10) % 12 + 1,
|
||||
day=1,
|
||||
)
|
||||
start_date = start_date.replace(tzinfo=tz.utc)
|
||||
end_date = (start_date + timedelta(days=32)).replace(
|
||||
day=1, hour=0, minute=0, microsecond=0
|
||||
)
|
||||
from django.db.models import Case, Sum, When
|
||||
|
||||
kwargs["sum_cb"] = sum(
|
||||
[
|
||||
r.amount
|
||||
for r in Refilling.objects.filter(
|
||||
payment_method="CARD",
|
||||
is_validated=True,
|
||||
date__gte=start_date,
|
||||
date__lte=end_date,
|
||||
)
|
||||
]
|
||||
)
|
||||
kwargs["sum_cb"] += sum(
|
||||
[
|
||||
s.quantity * s.unit_price
|
||||
for s in Selling.objects.filter(
|
||||
payment_method="CARD",
|
||||
is_validated=True,
|
||||
date__gte=start_date,
|
||||
date__lte=end_date,
|
||||
)
|
||||
]
|
||||
)
|
||||
kwargs["start_date"] = start_date
|
||||
kwargs["sums"] = (
|
||||
Selling.objects.values("club__name")
|
||||
.annotate(
|
||||
selling_sum=Sum(
|
||||
Case(
|
||||
When(
|
||||
date__gte=start_date,
|
||||
date__lt=end_date,
|
||||
then=F("unit_price") * F("quantity"),
|
||||
),
|
||||
output_field=CurrencyField(),
|
||||
)
|
||||
)
|
||||
)
|
||||
.exclude(selling_sum=None)
|
||||
.order_by("-selling_sum")
|
||||
)
|
||||
return kwargs
|
121
counter/views/mixins.py
Normal file
121
counter/views/mixins.py
Normal file
@ -0,0 +1,121 @@
|
||||
#
|
||||
# Copyright 2023 © AE UTBM
|
||||
# ae@utbm.fr / ae.info@utbm.fr
|
||||
#
|
||||
# This file is part of the website of the UTBM Student Association (AE UTBM),
|
||||
# https://ae.utbm.fr.
|
||||
#
|
||||
# You can find the source code of the website at https://github.com/ae-utbm/sith
|
||||
#
|
||||
# LICENSED UNDER THE GNU GENERAL PUBLIC LICENSE VERSION 3 (GPLv3)
|
||||
# SEE : https://raw.githubusercontent.com/ae-utbm/sith/master/LICENSE
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.views.generic.base import View
|
||||
|
||||
from core.views import TabedViewMixin
|
||||
|
||||
|
||||
class CounterAdminMixin(View):
|
||||
"""Protect counter admin section."""
|
||||
|
||||
edit_group = [settings.SITH_GROUP_COUNTER_ADMIN_ID]
|
||||
edit_club = []
|
||||
|
||||
def _test_group(self, user):
|
||||
return any(user.is_in_group(pk=grp_id) for grp_id in self.edit_group)
|
||||
|
||||
def _test_club(self, user):
|
||||
return any(c.can_be_edited_by(user) for c in self.edit_club)
|
||||
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
if not (
|
||||
request.user.is_root
|
||||
or self._test_group(request.user)
|
||||
or self._test_club(request.user)
|
||||
):
|
||||
raise PermissionDenied
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
|
||||
class CounterTabsMixin(TabedViewMixin):
|
||||
def get_tabs_title(self):
|
||||
return self.object
|
||||
|
||||
def get_list_of_tabs(self):
|
||||
tab_list = [
|
||||
{
|
||||
"url": reverse_lazy(
|
||||
"counter:details", kwargs={"counter_id": self.object.id}
|
||||
),
|
||||
"slug": "counter",
|
||||
"name": _("Counter"),
|
||||
}
|
||||
]
|
||||
if self.object.type == "BAR":
|
||||
tab_list.append(
|
||||
{
|
||||
"url": reverse_lazy(
|
||||
"counter:cash_summary", kwargs={"counter_id": self.object.id}
|
||||
),
|
||||
"slug": "cash_summary",
|
||||
"name": _("Cash summary"),
|
||||
}
|
||||
)
|
||||
tab_list.append(
|
||||
{
|
||||
"url": reverse_lazy(
|
||||
"counter:last_ops", kwargs={"counter_id": self.object.id}
|
||||
),
|
||||
"slug": "last_ops",
|
||||
"name": _("Last operations"),
|
||||
}
|
||||
)
|
||||
return tab_list
|
||||
|
||||
|
||||
class CounterAdminTabsMixin(TabedViewMixin):
|
||||
tabs_title = _("Counter administration")
|
||||
list_of_tabs = [
|
||||
{
|
||||
"url": reverse_lazy("counter:admin_list"),
|
||||
"slug": "counters",
|
||||
"name": _("Counters"),
|
||||
},
|
||||
{
|
||||
"url": reverse_lazy("counter:product_list"),
|
||||
"slug": "products",
|
||||
"name": _("Products"),
|
||||
},
|
||||
{
|
||||
"url": reverse_lazy("counter:product_list_archived"),
|
||||
"slug": "archive",
|
||||
"name": _("Archived products"),
|
||||
},
|
||||
{
|
||||
"url": reverse_lazy("counter:producttype_list"),
|
||||
"slug": "product_types",
|
||||
"name": _("Product types"),
|
||||
},
|
||||
{
|
||||
"url": reverse_lazy("counter:cash_summary_list"),
|
||||
"slug": "cash_summary",
|
||||
"name": _("Cash register summaries"),
|
||||
},
|
||||
{
|
||||
"url": reverse_lazy("counter:invoices_call"),
|
||||
"slug": "invoices_call",
|
||||
"name": _("Invoices call"),
|
||||
},
|
||||
{
|
||||
"url": reverse_lazy("counter:eticket_list"),
|
||||
"slug": "etickets",
|
||||
"name": _("Etickets"),
|
||||
},
|
||||
]
|
113
counter/views/student_card.py
Normal file
113
counter/views/student_card.py
Normal file
@ -0,0 +1,113 @@
|
||||
#
|
||||
# Copyright 2023 © AE UTBM
|
||||
# ae@utbm.fr / ae.info@utbm.fr
|
||||
#
|
||||
# This file is part of the website of the UTBM Student Association (AE UTBM),
|
||||
# https://ae.utbm.fr.
|
||||
#
|
||||
# You can find the source code of the website at https://github.com/ae-utbm/sith
|
||||
#
|
||||
# LICENSED UNDER THE GNU GENERAL PUBLIC LICENSE VERSION 3 (GPLv3)
|
||||
# SEE : https://raw.githubusercontent.com/ae-utbm/sith/master/LICENSE
|
||||
# OR WITHIN THE LOCAL FILE "LICENSE"
|
||||
#
|
||||
#
|
||||
|
||||
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.http import Http404, HttpRequest, HttpResponse
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.urls import reverse
|
||||
from django.utils.translation import gettext as _
|
||||
from django.views.generic.edit import DeleteView, FormView
|
||||
|
||||
from core.utils import FormFragmentTemplateData
|
||||
from core.views import can_edit
|
||||
from counter.forms import StudentCardForm
|
||||
from counter.models import Customer, StudentCard
|
||||
from counter.utils import is_logged_in_counter
|
||||
|
||||
|
||||
class StudentCardDeleteView(DeleteView):
|
||||
"""View used to delete a card from a user. This is a fragment view !"""
|
||||
|
||||
model = StudentCard
|
||||
template_name = "counter/fragments/delete_student_card.jinja"
|
||||
|
||||
def dispatch(self, request: HttpRequest, *args, **kwargs):
|
||||
self.customer = get_object_or_404(Customer, pk=kwargs["customer_id"])
|
||||
if not is_logged_in_counter(request) and not can_edit(
|
||||
self.get_object(), request.user
|
||||
):
|
||||
raise PermissionDenied()
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
context["action"] = self.request.path
|
||||
context["action_cancel"] = self.get_success_url()
|
||||
return context
|
||||
|
||||
def get_object(self, queryset=None):
|
||||
if not hasattr(self.customer, "student_card"):
|
||||
raise Http404(
|
||||
_("%(name)s has no registered student card")
|
||||
% {"name": self.customer.user.get_full_name()}
|
||||
)
|
||||
return self.customer.student_card
|
||||
|
||||
def get_success_url(self, **kwargs):
|
||||
return reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": self.customer.pk}
|
||||
)
|
||||
|
||||
|
||||
class StudentCardFormView(FormView):
|
||||
"""Add a new student card. This is a fragment view !"""
|
||||
|
||||
form_class = StudentCardForm
|
||||
template_name = "counter/fragments/create_student_card.jinja"
|
||||
|
||||
@classmethod
|
||||
def get_template_data(
|
||||
cls, customer: Customer, *, form_instance: form_class | None = None
|
||||
) -> FormFragmentTemplateData[form_class]:
|
||||
"""Get necessary data to pre-render the fragment"""
|
||||
return FormFragmentTemplateData(
|
||||
form=form_instance if form_instance else cls.form_class(),
|
||||
template=cls.template_name,
|
||||
context={
|
||||
"action": reverse(
|
||||
"counter:add_student_card", kwargs={"customer_id": customer.pk}
|
||||
),
|
||||
"customer": customer,
|
||||
},
|
||||
)
|
||||
|
||||
def dispatch(self, request: HttpRequest, *args, **kwargs):
|
||||
self.customer = get_object_or_404(
|
||||
Customer.objects.select_related("student_card"), pk=kwargs["customer_id"]
|
||||
)
|
||||
|
||||
if not is_logged_in_counter(request) and not StudentCard.can_create(
|
||||
self.customer, request.user
|
||||
):
|
||||
raise PermissionDenied
|
||||
|
||||
return super().dispatch(request, *args, **kwargs)
|
||||
|
||||
def form_valid(self, form: StudentCardForm) -> HttpResponse:
|
||||
data = form.clean()
|
||||
StudentCard.objects.update_or_create(
|
||||
customer=self.customer, defaults={"uid": data["uid"]}
|
||||
)
|
||||
return super().form_valid(form)
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
data = self.get_template_data(self.customer, form_instance=context["form"])
|
||||
context.update(data.context)
|
||||
return context
|
||||
|
||||
def get_success_url(self, **kwargs):
|
||||
return self.request.path
|
@ -145,10 +145,8 @@ class LaunderetteBookView(CanViewMixin, DetailView):
|
||||
and self.check_slot("WASHING", h)
|
||||
and self.check_slot("DRYING", h + timedelta(hours=1))
|
||||
)
|
||||
or self.slot_type == "WASHING"
|
||||
and self.check_slot("WASHING", h)
|
||||
or self.slot_type == "DRYING"
|
||||
and self.check_slot("DRYING", h)
|
||||
or (self.slot_type == "WASHING" and self.check_slot("WASHING", h))
|
||||
or (self.slot_type == "DRYING" and self.check_slot("DRYING", h))
|
||||
):
|
||||
free = True
|
||||
if free and datetime.now().replace(tzinfo=tz.utc) < h:
|
||||
|
File diff suppressed because it is too large
Load Diff
1415
poetry.lock
generated
1415
poetry.lock
generated
File diff suppressed because it is too large
Load Diff
@ -21,41 +21,38 @@ license = "GPL-3.0-only"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.12"
|
||||
Django = "^4.2.14"
|
||||
Django = "^4.2.17"
|
||||
django-ninja = "^1.3.0"
|
||||
django-ninja-extra = "^0.21.4"
|
||||
Pillow = "^10.4.0"
|
||||
django-ninja-extra = "^0.21.8"
|
||||
Pillow = "^11.0.0"
|
||||
mistune = "^3.0.2"
|
||||
django-jinja = "^2.11"
|
||||
cryptography = "^43.0.0"
|
||||
django-jinja = "^2.11.0"
|
||||
cryptography = "^44.0.0"
|
||||
django-phonenumber-field = "^8.0.0"
|
||||
phonenumbers = "^8.13"
|
||||
reportlab = "^4.2"
|
||||
django-haystack = "^3.2.1"
|
||||
xapian-haystack = "^3.0.1"
|
||||
libsass = "^0.23"
|
||||
django-ordered-model = "^3.7"
|
||||
phonenumbers = "^8.13.52"
|
||||
reportlab = "^4.2.5"
|
||||
django-haystack = "^3.3.0"
|
||||
xapian-haystack = "^3.1.0"
|
||||
libsass = "^0.23.0"
|
||||
django-ordered-model = "^3.7.4"
|
||||
django-simple-captcha = "^0.6.0"
|
||||
python-dateutil = "^2.8.2"
|
||||
sentry-sdk = "^2.16.0"
|
||||
Jinja2 = "^3.1"
|
||||
python-dateutil = "^2.9.0.post0"
|
||||
sentry-sdk = "^2.19.2"
|
||||
Jinja2 = "^3.1.4"
|
||||
django-countries = "^7.6.1"
|
||||
dict2xml = "^1.7.3"
|
||||
dict2xml = "^1.7.6"
|
||||
Sphinx = "^5" # Needed for building xapian
|
||||
tomli = "^2.0.1"
|
||||
tomli = "^2.2.1"
|
||||
django-honeypot = "^1.2.1"
|
||||
# When I introduced pydantic-extra-types, I needed *right now*
|
||||
# the PhoneNumberValidator class which was on the master branch but not released yet.
|
||||
# Once it's released, switch this to a regular version.
|
||||
pydantic-extra-types = { git = "https://github.com/pydantic/pydantic-extra-types.git", rev = "58db4b0" }
|
||||
pydantic-extra-types = "^2.10.1"
|
||||
|
||||
[tool.poetry.group.prod.dependencies]
|
||||
# deps used in prod, but unnecessary for development
|
||||
|
||||
# The C extra triggers compilation against sytem libs during install.
|
||||
# The C extra triggers compilation against system libs during install.
|
||||
# Removing it would switch psycopg to a slower full-python implementation
|
||||
psycopg = {extras = ["c"], version = "^3.2.1"}
|
||||
redis = {extras = ["hiredis"], version = "^5.0.8"}
|
||||
psycopg = {extras = ["c"], version = "^3.2.3"}
|
||||
redis = {extras = ["hiredis"], version = "^5.2.0"}
|
||||
|
||||
[tool.poetry.group.prod]
|
||||
optional = true
|
||||
@ -63,28 +60,28 @@ optional = true
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
# deps used for development purposes, but unneeded in prod
|
||||
django-debug-toolbar = "^4.4.6"
|
||||
ipython = "^8.26.0"
|
||||
ipython = "^8.30.0"
|
||||
pre-commit = "^4.0.1"
|
||||
ruff = "^0.6.9" # Version used in pipeline is controlled by pre-commit hooks in .pre-commit.config.yaml
|
||||
djhtml = "^3.0.6"
|
||||
faker = "^30.3.0"
|
||||
rjsmin = "^1.2.2"
|
||||
ruff = "^0.8.3" # Version used in pipeline is controlled by pre-commit hooks in .pre-commit.config.yaml
|
||||
djhtml = "^3.0.7"
|
||||
faker = "^33.1.0"
|
||||
rjsmin = "^1.2.3"
|
||||
|
||||
[tool.poetry.group.tests.dependencies]
|
||||
# deps used for testing purposes
|
||||
freezegun = "^1.5.1" # used to test time-dependent code
|
||||
pytest = "^8.3.2"
|
||||
pytest-cov = "^5.0.0"
|
||||
pytest = "^8.3.4"
|
||||
pytest-cov = "^6.0.0"
|
||||
pytest-django = "^4.9.0"
|
||||
model-bakery = "^1.20.0"
|
||||
|
||||
[tool.poetry.group.docs.dependencies]
|
||||
# deps used to work on the documentation
|
||||
mkdocs = "^1.6.1"
|
||||
mkdocs-material = "^9.5.40"
|
||||
mkdocstrings = "^0.26.2"
|
||||
mkdocstrings-python = "^1.12.0"
|
||||
mkdocs-include-markdown-plugin = "^6.2.2"
|
||||
mkdocs-material = "^9.5.47"
|
||||
mkdocstrings = "^0.27.0"
|
||||
mkdocstrings-python = "^1.12.2"
|
||||
mkdocs-include-markdown-plugin = "^7.1.2"
|
||||
|
||||
[tool.poetry.group.docs]
|
||||
optional = true
|
||||
|
@ -1,10 +1,10 @@
|
||||
from django.conf import settings
|
||||
from django.core.cache import cache
|
||||
from django.db import transaction
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
from model_bakery import baker
|
||||
from model_bakery.recipe import Recipe
|
||||
from pytest_django.asserts import assertNumQueries
|
||||
|
||||
from core.baker_recipes import old_subscriber_user, subscriber_user
|
||||
from core.models import RealGroup, SithFile, User
|
||||
@ -128,9 +128,11 @@ class TestPictureSearch(TestSas):
|
||||
def test_num_queries(self):
|
||||
"""Test that the number of queries is stable."""
|
||||
self.client.force_login(subscriber_user.make())
|
||||
with assertNumQueries(5):
|
||||
cache.clear()
|
||||
with self.assertNumQueries(7):
|
||||
# 2 requests to create the session
|
||||
# 1 request to fetch the user from the db
|
||||
# 2 requests to check the user permissions
|
||||
# 2 requests to check the user permissions, depends on the db engine
|
||||
# 1 request to fetch the pictures
|
||||
# 1 request to count the total number of items in the pagination
|
||||
self.client.get(self.url)
|
||||
|
@ -351,6 +351,9 @@ SITH_SEMESTER_START_SPRING = (2, 15) # 15 February
|
||||
# Used to determine the valid promos
|
||||
SITH_SCHOOL_START_YEAR = 1999
|
||||
|
||||
# id of the Root account
|
||||
SITH_ROOT_USER_ID = 0
|
||||
|
||||
SITH_GROUP_ROOT_ID = 1
|
||||
SITH_GROUP_PUBLIC_ID = 2
|
||||
SITH_GROUP_SUBSCRIBERS_ID = 3
|
||||
@ -429,14 +432,6 @@ SITH_SUBSCRIPTION_LOCATIONS = [
|
||||
|
||||
SITH_COUNTER_BARS = [(1, "MDE"), (2, "Foyer"), (35, "La Gommette")]
|
||||
|
||||
SITH_COUNTER_OFFICES = {2: "PdF", 1: "AE"}
|
||||
|
||||
SITH_COUNTER_PAYMENT_METHOD = [
|
||||
("CHECK", _("Check")),
|
||||
("CASH", _("Cash")),
|
||||
("CARD", _("Credit card")),
|
||||
]
|
||||
|
||||
SITH_COUNTER_BANK = [
|
||||
("OTHER", "Autre"),
|
||||
("SOCIETE-GENERALE", "Société générale"),
|
||||
|
@ -26,7 +26,8 @@ def test_sentry_debug_endpoint(
|
||||
expected_error: RaisesContext[ZeroDivisionError] | does_not_raise[None],
|
||||
expected_return_code: int | None,
|
||||
):
|
||||
with expected_error, override_settings(
|
||||
SENTRY_DSN=sentry_dsn, SENTRY_ENV=sentry_env
|
||||
with (
|
||||
expected_error,
|
||||
override_settings(SENTRY_DSN=sentry_dsn, SENTRY_ENV=sentry_env),
|
||||
):
|
||||
assert client.get(reverse("sentry-debug")).status_code == expected_return_code
|
||||
|
@ -4,11 +4,7 @@
|
||||
{% trans user=subscription.member %}Subscription created for {{ user }}{% endtrans %}
|
||||
</h3>
|
||||
<p>
|
||||
{% trans trimmed
|
||||
user=subscription.member.get_short_name(),
|
||||
type=subscription.subscription_type,
|
||||
end=subscription.subscription_end
|
||||
%}
|
||||
{% trans trimmed user=subscription.member.get_short_name(), type=subscription.subscription_type, end=subscription.subscription_end %}
|
||||
{{ user }} received its new {{ type }} subscription.
|
||||
It will be active until {{ end }} included.
|
||||
{% endtrans %}
|
||||
|
@ -21,6 +21,7 @@ from django.utils.timezone import localdate
|
||||
from django.views.generic import CreateView, DetailView, TemplateView
|
||||
from django.views.generic.edit import FormView
|
||||
|
||||
from counter.apps import PAYMENT_METHOD
|
||||
from subscription.forms import (
|
||||
SelectionDateForm,
|
||||
SubscriptionExistingUserForm,
|
||||
@ -108,6 +109,6 @@ class SubscriptionsStatsView(FormView):
|
||||
subscription_end__gte=self.end_date, subscription_start__lte=self.start_date
|
||||
)
|
||||
kwargs["subscriptions_types"] = settings.SITH_SUBSCRIPTIONS
|
||||
kwargs["payment_types"] = settings.SITH_COUNTER_PAYMENT_METHOD
|
||||
kwargs["payment_types"] = PAYMENT_METHOD
|
||||
kwargs["locations"] = settings.SITH_SUBSCRIPTION_LOCATIONS
|
||||
return kwargs
|
||||
|
Loading…
Reference in New Issue
Block a user