Add manual order costs and person totals
This commit is contained in:
1 parent
45219614bb
commit
705c57fec2
12 files changed
+499
-16
No files matched your search
@@ -74,6 +74,11 @@ urlpatterns = [
|
||||
path("bestand/<int:pk>/anbieten/", views.marketplace_offer, name="marketplace_offer"),
|
||||
path("bestellung/", views.orders, name="orders"),
|
||||
path("bestellung/einkaufsliste/", views.order_shopping_list, name="order_shopping_list"),
|
||||
path(
|
||||
"bestellung/einkaufsliste/gesamtbetrag/",
|
||||
views.shopping_list_total,
|
||||
name="shopping_list_total",
|
||||
),
|
||||
path(
|
||||
"bestellung/einkaufsliste/<str:source>/<int:product_id>/<int:color_id>/<str:spool_type>/status/",
|
||||
views.shopping_order_status,
|
||||
@@ -93,6 +98,7 @@ urlpatterns = [
|
||||
path("bestellung/hinzufuegen/", views.order_add, name="order_add"),
|
||||
path("bestellung/<int:pk>/bearbeiten/", views.order_edit, name="order_edit"),
|
||||
path("bestellung/<int:pk>/status/", views.order_status, name="order_status"),
|
||||
path("bestellung/<int:pk>/betrag/", views.order_amount, name="order_amount"),
|
||||
path("bestellung/<int:pk>/teillieferung/", views.order_arrival, name="order_arrival"),
|
||||
path("bestellung/<int:pk>/verlauf/", views.order_adjustment, name="order_adjustment"),
|
||||
path("bestellung/<int:pk>/loeschen/", views.order_delete, name="order_delete"),
|
||||
|
||||
@@ -24,6 +24,9 @@ Keine SPA, keine externen Schriften/Skripte, kein externer Datenbankserver.
|
||||
→ Übergeben ändern. Teilmengen lassen sich bei Lieferung und Übergabe erfassen.
|
||||
- Die konsolidierte Bestellliste fasst dieselben laufenden Positionen nach Variante und Status
|
||||
zusammen. Vor einer Statusänderung lassen sich die betroffenen Positionen je Person auswählen.
|
||||
- Die Gesamtkosten pro Person ergeben sich aus den manuell eingetragenen Positionspreisen.
|
||||
Nicht verfügbare Positionen zählen dabei nicht mit. Der Gesamtbetrag in der konsolidierten
|
||||
Liste wird separat eingetragen. Bei einer geänderten Liste erscheint ein Hinweis zur Prüfung.
|
||||
- Bei Übergabe wird die Menge in den Bestand der Person gebucht. Spule und Refill bleiben getrennt.
|
||||
Bestellte und eingetroffene Positionen sind vor dem Entfernen geschützt. Korrekturen und
|
||||
Stornierungen werden mit Begründung im Bestellverlauf protokolliert.
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from django import forms
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db.models import Q
|
||||
from django.forms.models import ModelChoiceIterator
|
||||
|
||||
from .models import (
|
||||
MAX_ORDER_AMOUNT,
|
||||
Color,
|
||||
EmptySpool,
|
||||
Feedback,
|
||||
@@ -262,6 +265,22 @@ class OrderStatusForm(forms.Form):
|
||||
confirmation = forms.CharField(required=False, max_length=100)
|
||||
|
||||
|
||||
class OrderAmountForm(forms.Form):
|
||||
amount = forms.DecimalField(
|
||||
required=False,
|
||||
min_value=Decimal("0"),
|
||||
max_value=MAX_ORDER_AMOUNT,
|
||||
max_digits=10,
|
||||
decimal_places=2,
|
||||
localize=True,
|
||||
)
|
||||
expected_revision = forms.UUIDField(required=False)
|
||||
|
||||
|
||||
class ShoppingListAmountForm(OrderAmountForm):
|
||||
expected_scope = forms.CharField(min_length=64, max_length=64)
|
||||
|
||||
|
||||
class OrderGroupStatusForm(forms.Form):
|
||||
status = forms.ChoiceField()
|
||||
snapshot = forms.CharField(max_length=64)
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# Generated by Django 5.2.19 on 2026-11-27 11:32
|
||||
|
||||
import uuid
|
||||
|
||||
import django.core.validators
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("filament", "0026_order_spool_preference"),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="ShoppingListTotal",
|
||||
fields=[
|
||||
(
|
||||
"id",
|
||||
models.BigAutoField(
|
||||
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
|
||||
),
|
||||
),
|
||||
(
|
||||
"amount",
|
||||
models.DecimalField(
|
||||
decimal_places=2,
|
||||
max_digits=10,
|
||||
validators=[django.core.validators.MinValueValidator(0)],
|
||||
),
|
||||
),
|
||||
("scope", models.CharField(editable=False, max_length=64)),
|
||||
("revision", models.UUIDField(default=uuid.uuid4, editable=False)),
|
||||
],
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name="orderitem",
|
||||
name="total_cost",
|
||||
field=models.DecimalField(
|
||||
blank=True,
|
||||
decimal_places=2,
|
||||
max_digits=10,
|
||||
null=True,
|
||||
validators=[django.core.validators.MinValueValidator(0)],
|
||||
verbose_name="Gesamtpreis der Position",
|
||||
),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="orderitem",
|
||||
constraint=models.CheckConstraint(
|
||||
condition=models.Q(
|
||||
("total_cost__gte", 0), ("total_cost__isnull", True), _connector="OR"
|
||||
),
|
||||
name="orderitem_nonnegative_total_cost",
|
||||
),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="shoppinglisttotal",
|
||||
constraint=models.CheckConstraint(
|
||||
condition=models.Q(("pk", 1)), name="shopping_list_single_total"
|
||||
),
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name="shoppinglisttotal",
|
||||
constraint=models.CheckConstraint(
|
||||
condition=models.Q(("amount__gte", 0)), name="shopping_list_total_nonnegative"
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -16,6 +16,8 @@ from django.utils.functional import cached_property
|
||||
|
||||
from .bambu_color_names import bambu_color_label
|
||||
|
||||
MAX_ORDER_AMOUNT = Decimal("99999999.99")
|
||||
|
||||
|
||||
class Manufacturer(models.Model):
|
||||
name = models.CharField("Hersteller", max_length=100, unique=True)
|
||||
@@ -426,6 +428,14 @@ class OrderItem(QuantityPosition):
|
||||
preferred_spool_type = models.CharField(max_length=10, choices=Variant.SpoolType, blank=True)
|
||||
allow_alternative_spool = models.BooleanField(default=False)
|
||||
ordered_at = models.DateTimeField("Bestellt am", null=True, blank=True)
|
||||
total_cost = models.DecimalField(
|
||||
"Gesamtpreis der Position",
|
||||
max_digits=10,
|
||||
decimal_places=2,
|
||||
null=True,
|
||||
blank=True,
|
||||
validators=[MinValueValidator(0)],
|
||||
)
|
||||
handed_over_at = models.DateTimeField("Übergeben am", null=True, blank=True)
|
||||
cancelled_at = models.DateTimeField("Storniert am", null=True, blank=True)
|
||||
catalog_snapshot = models.JSONField(default=dict, blank=True, editable=False)
|
||||
@@ -441,6 +451,10 @@ class OrderItem(QuantityPosition):
|
||||
|
||||
class Meta(QuantityPosition.Meta):
|
||||
constraints = [
|
||||
models.CheckConstraint(
|
||||
condition=models.Q(total_cost__gte=0) | models.Q(total_cost__isnull=True),
|
||||
name="orderitem_nonnegative_total_cost",
|
||||
),
|
||||
models.CheckConstraint(
|
||||
condition=models.Q(preferred_spool_type__in=["", "spool", "refill"]),
|
||||
name="orderitem_valid_preferred_spool",
|
||||
@@ -565,6 +579,22 @@ class OrderAdjustment(models.Model):
|
||||
ordering = ["-created_at", "-pk"]
|
||||
|
||||
|
||||
class ShoppingListTotal(models.Model):
|
||||
SINGLETON_PK = 1
|
||||
|
||||
amount = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(0)])
|
||||
scope = models.CharField(max_length=64, editable=False)
|
||||
revision = models.UUIDField(default=uuid4, editable=False)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.CheckConstraint(condition=models.Q(pk=1), name="shopping_list_single_total"),
|
||||
models.CheckConstraint(
|
||||
condition=models.Q(amount__gte=0), name="shopping_list_total_nonnegative"
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
class Printer(models.Model):
|
||||
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||
manufacturer = models.CharField("Hersteller", max_length=100)
|
||||
|
||||
+41
-7
@@ -3,6 +3,7 @@ import json
|
||||
import os
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
@@ -12,6 +13,7 @@ from django.shortcuts import get_object_or_404
|
||||
from django.utils import timezone
|
||||
|
||||
from .models import (
|
||||
MAX_ORDER_AMOUNT,
|
||||
EmptySpool,
|
||||
InventoryItem,
|
||||
MarketplaceOffer,
|
||||
@@ -150,6 +152,7 @@ def add_quantity(
|
||||
variant__product_type_id=variant.product_type_id,
|
||||
variant__color_id=variant.color_id,
|
||||
allow_alternative_spool=allow_alternative_spool,
|
||||
total_cost__isnull=True,
|
||||
)
|
||||
.order_by("pk")
|
||||
.first()
|
||||
@@ -203,11 +206,11 @@ def _increment_position(positions, quantity, **lookup):
|
||||
return position if created else _increase_quantity(position, quantity)
|
||||
|
||||
|
||||
def _increase_quantity(position, quantity):
|
||||
def _increase_quantity(position, quantity, *, update_fields=()):
|
||||
if position.quantity + quantity > 9999:
|
||||
raise ValidationError("Die Gesamtstückzahl darf höchstens 9999 betragen.")
|
||||
position.quantity += quantity
|
||||
position.save(update_fields=["quantity"])
|
||||
position.save(update_fields=["quantity", *update_fields])
|
||||
return position
|
||||
|
||||
|
||||
@@ -312,12 +315,14 @@ def record_order_arrival(item_id, expected_revision, quantity):
|
||||
raise ValidationError("Die Menge muss zwischen 1 und der bestellten Stückzahl liegen.")
|
||||
if quantity == item.quantity:
|
||||
return _apply_order_status(item, OrderItem.Status.ARRIVED, None)
|
||||
total_cost = _split_order_cost(item, quantity)
|
||||
item.quantity -= quantity
|
||||
item.save(update_fields=["quantity"])
|
||||
item.save(update_fields=["quantity", "total_cost"])
|
||||
return OrderItem.objects.create(
|
||||
owner_id=item.owner_id,
|
||||
variant_id=item.variant_id,
|
||||
quantity=quantity,
|
||||
total_cost=total_cost,
|
||||
status=OrderItem.Status.ARRIVED,
|
||||
ordered_at=item.ordered_at,
|
||||
catalog_snapshot=item.catalog_details,
|
||||
@@ -333,6 +338,15 @@ def order_group_snapshot(entries):
|
||||
return hashlib.sha256(json.dumps(rows).encode()).hexdigest()
|
||||
|
||||
|
||||
def shopping_list_cost_scope(entries):
|
||||
rows = sorted(
|
||||
(entry.pk, entry.variant_id, entry.quantity)
|
||||
for entry in entries
|
||||
if entry.status != OrderItem.Status.UNAVAILABLE
|
||||
)
|
||||
return hashlib.sha256(json.dumps(rows).encode()).hexdigest()
|
||||
|
||||
|
||||
def person_order_items(owner_id):
|
||||
return OrderItem.objects.filter(owner_id=owner_id).exclude(
|
||||
status__in=OrderItem.HISTORY_STATUSES
|
||||
@@ -431,12 +445,14 @@ def _complete_order_handover(item, quantity):
|
||||
)
|
||||
_record_stock_movement(stock, StockMovement.Kind.HANDOVER, quantity)
|
||||
if quantity < item.quantity:
|
||||
total_cost = _split_order_cost(item, quantity)
|
||||
item.quantity -= quantity
|
||||
item.save(update_fields=["quantity"])
|
||||
item.save(update_fields=["quantity", "total_cost"])
|
||||
return OrderItem.objects.create(
|
||||
owner_id=item.owner_id,
|
||||
variant_id=item.variant_id,
|
||||
quantity=quantity,
|
||||
total_cost=total_cost,
|
||||
status=OrderItem.Status.HANDED_OVER,
|
||||
ordered_at=item.ordered_at,
|
||||
catalog_snapshot=item.catalog_details,
|
||||
@@ -470,6 +486,16 @@ def _complete_order_handover(item, quantity):
|
||||
return item
|
||||
|
||||
|
||||
def _split_order_cost(item, quantity):
|
||||
if item.total_cost is None:
|
||||
return None
|
||||
share = (item.total_cost * quantity / item.quantity).quantize(
|
||||
Decimal("0.01"), rounding=ROUND_HALF_UP
|
||||
)
|
||||
item.total_cost -= share
|
||||
return share
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def undo_order_handover(item_id, expected_revision):
|
||||
item = get_object_or_404(OrderItem.objects.select_for_update(), pk=item_id)
|
||||
@@ -524,9 +550,17 @@ def undo_order_handover(item_id, expected_revision):
|
||||
handover_stock_revision=stock.revision
|
||||
)
|
||||
if remainder is not None:
|
||||
_increase_quantity(remainder, item.quantity)
|
||||
item.delete()
|
||||
return
|
||||
if item.total_cost is None and remainder.total_cost is None:
|
||||
_increase_quantity(remainder, item.quantity)
|
||||
item.delete()
|
||||
return
|
||||
if item.total_cost is not None and remainder.total_cost is not None:
|
||||
total_cost = item.total_cost + remainder.total_cost
|
||||
if total_cost <= MAX_ORDER_AMOUNT:
|
||||
remainder.total_cost = total_cost
|
||||
_increase_quantity(remainder, item.quantity, update_fields=["total_cost"])
|
||||
item.delete()
|
||||
return
|
||||
item.status = previous_status
|
||||
item.handed_over_at = None
|
||||
item.handover_previous_status = ""
|
||||
|
||||
@@ -669,6 +669,40 @@ td.quantity {
|
||||
background: var(--control-bg);
|
||||
color: var(--ink);
|
||||
}
|
||||
.order-amount-form input[type="text"] {
|
||||
width: 7.5rem;
|
||||
min-height: 36px;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--control-border);
|
||||
border-radius: 8px;
|
||||
background: var(--control-bg);
|
||||
color: var(--ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.order-amount-total {
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.order-missing-costs {
|
||||
display: block;
|
||||
font-weight: 400;
|
||||
text-transform: none;
|
||||
}
|
||||
.order-list-amount {
|
||||
padding: 16px 20px;
|
||||
}
|
||||
.order-list-amount label {
|
||||
display: block;
|
||||
font-weight: 650;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.order-list-amount-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.order-status-form button {
|
||||
justify-self: start;
|
||||
min-height: 34px;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
from datetime import UTC, datetime
|
||||
from decimal import Decimal
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import Client
|
||||
from django.urls import reverse
|
||||
|
||||
from filament.models import InventoryItem, OrderItem, StockMovement, Variant
|
||||
from filament.models import InventoryItem, OrderItem, ShoppingListTotal, StockMovement, Variant
|
||||
from filament.services import add_quantity
|
||||
|
||||
from .base import CatalogTestCase
|
||||
@@ -14,7 +15,7 @@ from .base import CatalogTestCase
|
||||
class SharedOrderTests(CatalogTestCase):
|
||||
def person_status_payload(self, owner, status):
|
||||
response = self.client.get(reverse("orders"))
|
||||
_, _, _, snapshot = next(
|
||||
_, _, _, snapshot, _, _ = next(
|
||||
group for group in response.context["groups"] if group[1][0].owner_id == owner.pk
|
||||
)
|
||||
return reverse("person_order_status", args=[owner.pk]), {
|
||||
@@ -279,6 +280,156 @@ class SharedOrderTests(CatalogTestCase):
|
||||
self.assertEqual(second.status, OrderItem.Status.OPEN)
|
||||
source = target
|
||||
|
||||
def test_manual_position_amounts_are_validated_and_summed_by_person(self):
|
||||
priced = OrderItem.objects.create(owner=self.bob, variant=self.spool, quantity=3)
|
||||
free = OrderItem.objects.create(owner=self.bob, variant=self.refill, quantity=1)
|
||||
OrderItem.objects.create(owner=self.bob, variant=self.black_spool, quantity=1)
|
||||
OrderItem.objects.create(
|
||||
owner=self.bob,
|
||||
variant=self.black_spool,
|
||||
quantity=2,
|
||||
status=OrderItem.Status.UNAVAILABLE,
|
||||
total_cost=Decimal("25.00"),
|
||||
)
|
||||
OrderItem.objects.create(
|
||||
owner=self.alice, variant=self.spool, quantity=1, total_cost=Decimal("8.00")
|
||||
)
|
||||
orders = reverse("orders")
|
||||
route = reverse("order_amount", args=[priced.pk])
|
||||
self.client.force_login(self.alice)
|
||||
self.assertEqual(self.client.get(route).status_code, 405)
|
||||
data = {"amount": "31,50", "expected_revision": priced.revision}
|
||||
for invalid in ("-1,00", "31,505", "abc"):
|
||||
result = self.client.post(route, data | {"amount": invalid}, follow=True)
|
||||
self.assertContains(result, "zwei Nachkommastellen")
|
||||
self.assertIsNone(OrderItem.objects.get(pk=priced.pk).total_cost)
|
||||
self.assertRedirects(self.client.post(route, data), orders)
|
||||
self.assertRedirects(
|
||||
self.client.post(
|
||||
reverse("order_amount", args=[free.pk]),
|
||||
{
|
||||
"amount": "0",
|
||||
"expected_revision": free.revision,
|
||||
},
|
||||
),
|
||||
orders,
|
||||
)
|
||||
stale = self.client.post(route, data | {"amount": "33,00"}, follow=True)
|
||||
self.assertContains(stale, "Position wurde inzwischen geändert")
|
||||
listing = self.client.get(orders)
|
||||
self.assertContains(listing, "31,50 €")
|
||||
self.assertContains(listing, "Ein Betrag fehlt")
|
||||
self.assertEqual(
|
||||
{
|
||||
username: (cost, missing)
|
||||
for username, _, _, _, cost, missing in listing.context["groups"]
|
||||
},
|
||||
{self.alice.username: (Decimal("8.00"), 0), self.bob.username: (Decimal("31.50"), 1)},
|
||||
)
|
||||
self.assertEqual(OrderItem.objects.get(pk=free.pk).total_cost, Decimal("0.00"))
|
||||
priced.refresh_from_db()
|
||||
self.assertRedirects(
|
||||
self.client.post(route, {"amount": "", "expected_revision": priced.revision}), orders
|
||||
)
|
||||
self.assertIsNone(OrderItem.objects.get(pk=priced.pk).total_cost)
|
||||
|
||||
def test_consolidated_manual_total_is_shared_and_marks_a_changed_list(self):
|
||||
order = OrderItem.objects.create(owner=self.alice, variant=self.spool, quantity=1)
|
||||
self.client.force_login(self.alice)
|
||||
listing = reverse("order_shopping_list", query={"q": "10100"})
|
||||
url = reverse("shopping_list_total", query={"q": "10100"})
|
||||
scope = self.client.get(listing).context["cost_scope"]
|
||||
self.assertEqual(
|
||||
scope, self.client.get(reverse("order_shopping_list")).context["cost_scope"]
|
||||
)
|
||||
values = {"amount": "44,20", "expected_scope": scope, "expected_revision": ""}
|
||||
self.assertRedirects(self.client.post(url, values), listing)
|
||||
total = ShoppingListTotal.objects.get()
|
||||
self.assertEqual(total.amount, Decimal("44.20"))
|
||||
self.client.force_login(self.bob)
|
||||
self.assertContains(self.client.get(listing), 'value="44,20"')
|
||||
self.assertFalse(self.client.get(listing).context["cost_scope_changed"])
|
||||
order.status = OrderItem.Status.ORDERED
|
||||
order.save(update_fields=["status"])
|
||||
self.assertFalse(self.client.get(listing).context["cost_scope_changed"])
|
||||
OrderItem.objects.create(owner=self.bob, variant=self.refill, quantity=1)
|
||||
page = self.client.get(listing)
|
||||
self.assertContains(page, "Bestellliste hat sich seit der letzten Eingabe geändert")
|
||||
stale = self.client.post(
|
||||
url, values | {"expected_revision": total.revision, "amount": "45,00"}, follow=True
|
||||
)
|
||||
self.assertContains(stale, "Bestellliste wurde inzwischen geändert")
|
||||
values = {
|
||||
"amount": "49,90",
|
||||
"expected_scope": page.context["cost_scope"],
|
||||
"expected_revision": total.revision,
|
||||
}
|
||||
self.assertRedirects(self.client.post(url, values), listing)
|
||||
self.assertFalse(self.client.get(listing).context["cost_scope_changed"])
|
||||
total.refresh_from_db()
|
||||
self.assertEqual(total.amount, Decimal("49.90"))
|
||||
self.assertRedirects(
|
||||
self.client.post(url, values | {"amount": "", "expected_revision": total.revision}),
|
||||
listing,
|
||||
)
|
||||
self.assertFalse(ShoppingListTotal.objects.exists())
|
||||
|
||||
def test_partial_arrival_and_handover_preserve_exact_position_cost(self):
|
||||
ordered = OrderItem.objects.create(
|
||||
owner=self.alice,
|
||||
variant=self.spool,
|
||||
quantity=3,
|
||||
status=OrderItem.Status.ORDERED,
|
||||
total_cost=Decimal("20.00"),
|
||||
)
|
||||
self.client.force_login(self.alice)
|
||||
orders = reverse("orders")
|
||||
self.assertRedirects(
|
||||
self.client.post(
|
||||
reverse("order_arrival", args=[ordered.pk]),
|
||||
{
|
||||
"quantity": 2,
|
||||
"expected_revision": ordered.revision,
|
||||
},
|
||||
),
|
||||
orders,
|
||||
)
|
||||
ordered.refresh_from_db()
|
||||
arrived = OrderItem.objects.get(status=OrderItem.Status.ARRIVED)
|
||||
self.assertEqual(
|
||||
(ordered.total_cost, arrived.total_cost), (Decimal("6.67"), Decimal("13.33"))
|
||||
)
|
||||
url, data = self.handover_confirmation(arrived)
|
||||
self.assertRedirects(self.client.post(url, data | {"handover_quantity": 1}), orders)
|
||||
handed = OrderItem.objects.get(status=OrderItem.Status.HANDED_OVER)
|
||||
arrived.refresh_from_db()
|
||||
self.assertEqual(
|
||||
(arrived.total_cost, handed.total_cost), (Decimal("6.66"), Decimal("6.67"))
|
||||
)
|
||||
self.assertContains(self.client.get(reverse("order_history")), "6,67 €")
|
||||
undo = reverse("order_handover_undo", args=[handed.pk])
|
||||
self.assertRedirects(self.client.post(undo, {"expected_revision": handed.revision}), orders)
|
||||
arrived.refresh_from_db()
|
||||
self.assertEqual((arrived.quantity, arrived.total_cost), (2, Decimal("13.33")))
|
||||
|
||||
def test_adding_or_editing_quantity_does_not_reuse_an_outdated_cost(self):
|
||||
priced = OrderItem.objects.create(
|
||||
owner=self.alice, variant=self.spool, quantity=2, total_cost=Decimal("25.00")
|
||||
)
|
||||
new = add_quantity(OrderItem, self.alice, self.spool, 1)
|
||||
priced.refresh_from_db()
|
||||
self.assertNotEqual(new.pk, priced.pk)
|
||||
self.assertEqual((priced.quantity, priced.total_cost), (2, Decimal("25.00")))
|
||||
self.client.force_login(self.alice)
|
||||
response = self.client.post(
|
||||
reverse("order_edit", args=[priced.pk]),
|
||||
{"quantity": 3, "expected_quantity": 2},
|
||||
follow=True,
|
||||
)
|
||||
self.assertContains(response, "Bitte erfasse den Gesamtpreis der Position neu.")
|
||||
priced.refresh_from_db()
|
||||
self.assertEqual((priced.quantity, priced.total_cost), (3, None))
|
||||
|
||||
def test_history_is_shared_and_records_order_and_handover_times(self):
|
||||
url = reverse("order_history")
|
||||
self.assertRedirects(self.client.get(url), f"/anmelden/?next={url}")
|
||||
@@ -628,7 +779,7 @@ class SharedOrderTests(CatalogTestCase):
|
||||
self.assertEqual(
|
||||
{
|
||||
username: {entry.variant_id: entry.quantity for entry in entries}
|
||||
for username, entries, _, _ in response.context["groups"]
|
||||
for username, entries, _, _, _, _ in response.context["groups"]
|
||||
},
|
||||
{"michael": {self.spool.pk: 2}, "person-zwei": {self.spool.pk: 1, self.refill.pk: 4}},
|
||||
)
|
||||
|
||||
+104
-3
@@ -27,6 +27,7 @@ from .forms import (
|
||||
MarketplaceOfferForm,
|
||||
MountRefillForm,
|
||||
OrderAdjustmentForm,
|
||||
OrderAmountForm,
|
||||
OrderArrivalForm,
|
||||
OrderGroupStatusForm,
|
||||
OrderHandoverForm,
|
||||
@@ -40,6 +41,7 @@ from .forms import (
|
||||
SharedModelForm,
|
||||
SharedModelUploadForm,
|
||||
SharingPreferencesForm,
|
||||
ShoppingListAmountForm,
|
||||
SlicerTipForm,
|
||||
UndoOrderHandoverForm,
|
||||
VariantSelectionForm,
|
||||
@@ -56,6 +58,7 @@ from .models import (
|
||||
PrinterNozzle,
|
||||
SharedModel,
|
||||
SharingPreferences,
|
||||
ShoppingListTotal,
|
||||
SlicerTip,
|
||||
StockMovement,
|
||||
Variant,
|
||||
@@ -72,6 +75,7 @@ from .services import (
|
||||
person_order_items,
|
||||
record_order_arrival,
|
||||
remove_inventory_position,
|
||||
shopping_list_cost_scope,
|
||||
take_marketplace_offer,
|
||||
undo_order_handover,
|
||||
update_inventory_position,
|
||||
@@ -256,9 +260,18 @@ def _edit_position(request, pk, positions, back):
|
||||
"Die Stückzahl hat sich geändert. Öffne die Position erneut und prüfe den aktuellen Wert.",
|
||||
)
|
||||
else:
|
||||
item.quantity = form.cleaned_data["quantity"]
|
||||
item.save(update_fields=["quantity"])
|
||||
messages.success(request, "Stückzahl geändert.")
|
||||
quantity = form.cleaned_data["quantity"]
|
||||
if item.quantity != quantity:
|
||||
amount_was_set = item.total_cost is not None
|
||||
item.quantity = quantity
|
||||
item.total_cost = None
|
||||
item.save(update_fields=["quantity", "total_cost"])
|
||||
messages.success(
|
||||
request,
|
||||
"Stückzahl geändert. Bitte erfasse den Gesamtpreis der Position neu."
|
||||
if amount_was_set
|
||||
else "Stückzahl geändert.",
|
||||
)
|
||||
return redirect(back)
|
||||
return render(
|
||||
request,
|
||||
@@ -958,12 +971,18 @@ def orders(request):
|
||||
groups = []
|
||||
for username, items in groupby(entries, key=lambda entry: entry.owner.username):
|
||||
positions = list(items)
|
||||
costs = [
|
||||
entry.total_cost for entry in positions if entry.status != OrderItem.Status.UNAVAILABLE
|
||||
]
|
||||
recorded = [cost for cost in costs if cost is not None]
|
||||
groups.append(
|
||||
(
|
||||
username,
|
||||
positions,
|
||||
sum(position.quantity for position in positions),
|
||||
order_group_snapshot(positions),
|
||||
sum(recorded) if recorded else None,
|
||||
len(costs) - len(recorded),
|
||||
)
|
||||
)
|
||||
return render(
|
||||
@@ -1049,6 +1068,8 @@ def order_shopping_list(request):
|
||||
OrderItem.Status.values.index(group["status"]),
|
||||
)
|
||||
)
|
||||
cost_scope = shopping_list_cost_scope(entries)
|
||||
saved_total = ShoppingListTotal.objects.filter(pk=ShoppingListTotal.SINGLETON_PK).first()
|
||||
return render(
|
||||
request,
|
||||
"filament/order_shopping_list.html",
|
||||
@@ -1057,6 +1078,10 @@ def order_shopping_list(request):
|
||||
"total": total,
|
||||
"search": search,
|
||||
"unavailable": unavailable if not search else 0,
|
||||
"saved_total": saved_total,
|
||||
"cost_scope": cost_scope,
|
||||
"cost_scope_changed": saved_total is not None and saved_total.scope != cost_scope,
|
||||
"cost_url": reverse("shopping_list_total", query={"q": search} if search else None),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -1065,6 +1090,82 @@ def _shopping_search(request):
|
||||
return request.GET.get("q", "").strip()[:200]
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(["POST"])
|
||||
@transaction.atomic
|
||||
def shopping_list_total(request):
|
||||
search = _shopping_search(request)
|
||||
back_url = reverse("order_shopping_list", query={"q": search} if search else None)
|
||||
form = ShoppingListAmountForm(request.POST)
|
||||
if not form.is_valid():
|
||||
messages.error(
|
||||
request, "Bitte gib einen gültigen Betrag mit bis zu zwei Nachkommastellen ein."
|
||||
)
|
||||
return redirect(back_url)
|
||||
saved = (
|
||||
ShoppingListTotal.objects.select_for_update()
|
||||
.filter(pk=ShoppingListTotal.SINGLETON_PK)
|
||||
.first()
|
||||
)
|
||||
current_revision = saved.revision if saved else None
|
||||
if current_revision != form.cleaned_data["expected_revision"]:
|
||||
messages.error(
|
||||
request, "Der Gesamtbetrag wurde inzwischen geändert. Bitte prüfe den aktuellen Wert."
|
||||
)
|
||||
return redirect(back_url)
|
||||
amount = form.cleaned_data["amount"]
|
||||
if amount is None:
|
||||
if saved:
|
||||
saved.delete()
|
||||
messages.success(request, "Gesamtbetrag entfernt.")
|
||||
return redirect(back_url)
|
||||
entries = OrderItem.objects.exclude(status__in=OrderItem.HISTORY_STATUSES).order_by()
|
||||
scope = shopping_list_cost_scope(entries)
|
||||
if scope != form.cleaned_data["expected_scope"]:
|
||||
messages.error(
|
||||
request,
|
||||
"Die Bestellliste wurde inzwischen geändert. Bitte prüfe den Betrag für die aktuelle Liste.",
|
||||
)
|
||||
return redirect(back_url)
|
||||
ShoppingListTotal.objects.update_or_create(
|
||||
pk=ShoppingListTotal.SINGLETON_PK,
|
||||
defaults={"amount": amount, "scope": scope, "revision": uuid4()},
|
||||
)
|
||||
messages.success(request, "Gesamtbetrag gespeichert.")
|
||||
return redirect(back_url)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(["POST"])
|
||||
@transaction.atomic
|
||||
def order_amount(request, pk):
|
||||
entry = get_object_or_404(
|
||||
OrderItem.objects.select_for_update().exclude(status__in=OrderItem.HISTORY_STATUSES),
|
||||
pk=pk,
|
||||
)
|
||||
form = OrderAmountForm(request.POST)
|
||||
if not form.is_valid():
|
||||
messages.error(
|
||||
request, "Bitte gib einen gültigen Betrag mit bis zu zwei Nachkommastellen ein."
|
||||
)
|
||||
elif entry.revision != form.cleaned_data["expected_revision"]:
|
||||
messages.error(
|
||||
request, "Die Position wurde inzwischen geändert. Bitte prüfe den aktuellen Wert."
|
||||
)
|
||||
else:
|
||||
amount = form.cleaned_data["amount"]
|
||||
if entry.total_cost != amount:
|
||||
entry.total_cost = amount
|
||||
entry.save(update_fields=["total_cost"])
|
||||
messages.success(
|
||||
request,
|
||||
"Gesamtpreis der Position gespeichert."
|
||||
if amount is not None
|
||||
else "Gesamtpreis der Position entfernt.",
|
||||
)
|
||||
return redirect("orders")
|
||||
|
||||
|
||||
def _shopping_status_choices(source, available=True):
|
||||
return [
|
||||
status
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<div class="table-wrap">
|
||||
<table aria-label="Bestellhistorie">
|
||||
<thead>
|
||||
<tr><th>Bestellt am</th><th>Für wen</th><th>Stück</th><th>Produktart</th><th>Farbe</th><th>Artikelnr.</th><th>Spulenausführung</th><th>Status</th><th>{% if cancelled %}Storniert{% else %}Übergeben{% endif %} am</th><th scope="col"><span class="sr-only">Aktionen</span></th></tr>
|
||||
<tr><th>Bestellt am</th><th>Für wen</th><th>Stück</th><th>Produktart</th><th>Farbe</th><th>Artikelnr.</th><th>Spulenausführung</th><th>Gesamtpreis</th><th>Status</th><th>{% if cancelled %}Storniert{% else %}Übergeben{% endif %} am</th><th scope="col"><span class="sr-only">Aktionen</span></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for entry in page %}
|
||||
@@ -28,6 +28,7 @@
|
||||
<td><div class="variant-preview">{% include "filament/variant_thumbnail.html" with variant=catalog only %}<strong>{{ catalog.color }}</strong></div></td>
|
||||
<td class="article-number">{{ catalog.article_number|default:"–" }}</td>
|
||||
<td><span class="badge">{{ catalog.spool }}</span></td>
|
||||
<td class="order-amount-total">{% if entry.total_cost is not None %}{{ entry.total_cost|floatformat:2 }} €{% else %}–{% endif %}</td>
|
||||
<td><span class="badge">{{ entry.get_status_display }}</span></td>
|
||||
<td class="history-date">
|
||||
{% if entry.cancelled_at %}<time datetime="{{ entry.cancelled_at|date:'c' }}">{{ entry.cancelled_at|date:"d.m.Y" }}<small>{{ entry.cancelled_at|date:"H:i" }} Uhr</small></time>
|
||||
|
||||
@@ -57,5 +57,21 @@
|
||||
{% else %}
|
||||
<section class="panel"><div class="empty"><h2>{% if search %}Keine laufenden Positionen zu diesen Artikelnummern{% else %}Keine laufenden Bestellpositionen{% endif %}</h2></div></section>
|
||||
{% endif %}
|
||||
<section class="panel order-list-amount" id="shopping-list-amount" data-order-anchor>
|
||||
<form class="order-amount-form" method="post" action="{{ cost_url }}" data-order-scroll>
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="expected_revision" value="{{ saved_total.revision }}">
|
||||
<input type="hidden" name="expected_scope" value="{{ cost_scope }}">
|
||||
<label for="shopping-total-amount">Gesamtbetrag der Sammelbestellung (€)</label>
|
||||
<div class="order-list-amount-controls">
|
||||
<input id="shopping-total-amount" name="amount" type="text" inputmode="decimal" maxlength="12" placeholder="0,00" value="{{ saved_total.amount|floatformat:2 }}">
|
||||
<button class="button secondary" type="submit">Gesamtbetrag speichern</button>
|
||||
</div>
|
||||
{% if cost_scope_changed %}
|
||||
<p class="warning" role="status">Die Bestellliste hat sich seit der letzten Eingabe geändert. Bitte prüfe den Gesamtbetrag.</p>
|
||||
{% endif %}
|
||||
{% if search %}<small>Der Betrag gilt für die gesamte Sammelbestellung.</small>{% endif %}
|
||||
</form>
|
||||
</section>
|
||||
<script src="{% static 'filament/order_scroll.js' %}" defer></script>
|
||||
{% endblock %}
|
||||
@@ -14,7 +14,7 @@
|
||||
<section class="stat"><span>Verschiedene Varianten</span><strong>{{ variant_count }}</strong></section>
|
||||
<section class="stat"><span>Personen mit Bestellwünschen</span><strong>{{ groups|length }}</strong></section>
|
||||
</div>
|
||||
{% for username, entries, roll_count, snapshot in groups %}
|
||||
{% for username, entries, roll_count, snapshot, costs, missing_costs in groups %}
|
||||
<section class="panel">
|
||||
<div id="order-owner-{{ entries.0.owner_id }}" class="panel-heading order-person-heading" data-order-anchor>
|
||||
<h2 id="order-person-{{ forloop.counter }}">Bestellwunsch · {{ username }} · ×{{ roll_count }}</h2>
|
||||
@@ -32,7 +32,7 @@
|
||||
<div class="table-wrap">
|
||||
<table class="order-table" aria-labelledby="order-person-{{ forloop.counter }}">
|
||||
<thead>
|
||||
<tr><th>Stück</th><th>Produktart</th><th>Farbe</th><th title="Hersteller-Farbcode">Artikelnr.</th><th>Spulenausführung</th><th>Status</th><th><span class="sr-only">Aktionen</span></th></tr>
|
||||
<tr><th>Stück</th><th>Produktart</th><th>Farbe</th><th title="Hersteller-Farbcode">Artikelnr.</th><th>Spulenausführung</th><th>Status</th><th>Gesamtpreis (€)</th><th><span class="sr-only">Aktionen</span></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for entry in entries %}
|
||||
@@ -78,6 +78,15 @@
|
||||
<button class="button secondary" type="submit">Speichern</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<form class="order-status-form order-amount-form" method="post" action="{% url 'order_amount' entry.pk %}" data-order-scroll>
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="expected_revision" value="{{ entry.revision }}">
|
||||
<label class="sr-only" for="order-amount-{{ entry.pk }}">Gesamtpreis in Euro für {{ entry.quantity }} × {{ entry.variant }} · {{ username }}</label>
|
||||
<input id="order-amount-{{ entry.pk }}" name="amount" type="text" inputmode="decimal" maxlength="12" placeholder="0,00" value="{{ entry.total_cost|floatformat:2 }}">
|
||||
<button class="button secondary" type="submit">Betrag speichern</button>
|
||||
</form>
|
||||
</td>
|
||||
<td class="actions">
|
||||
{% if entry.owner_id == user.pk and entry.is_pending %}
|
||||
<a href="{% url 'order_edit' entry.pk %}" data-order-scroll>Ändern</a>
|
||||
@@ -98,6 +107,14 @@
|
||||
{% endwith %}
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<th colspan="6" scope="row">Gesamtkosten
|
||||
{% if missing_costs %}<small class="order-missing-costs">{% if missing_costs == 1 %}Ein Betrag fehlt{% else %}{{ missing_costs }} Beträge fehlen{% endif %}</small>{% endif %}
|
||||
</th>
|
||||
<td colspan="2" class="order-amount-total">{% if costs is not None %}{{ costs|floatformat:2 }} €{% else %}–{% endif %}</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
Reference in new issue
Block a user