From c8e47fd95ecf2e4e6661714322cd6233d5895a8a Mon Sep 17 00:00:00 2001 From: Stephen Early Date: Sat, 25 Jan 2025 09:38:54 +0000 Subject: [PATCH] Deal with creating a duplicate stock type through the web interface Creating a duplicate stock type no longer crashes. Instead it redirects to the existing stock type page with a helpful error message. Closes #265 on github. --- quicktill/tillweb/views.py | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/quicktill/tillweb/views.py b/quicktill/tillweb/views.py index f67e915..2b41ece 100644 --- a/quicktill/tillweb/views.py +++ b/quicktill/tillweb/views.py @@ -1384,16 +1384,31 @@ def create_stocktype(request, info): form = NewStockTypeForm(request.POST) if form.is_valid(): cd = form.cleaned_data - s = StockType( - department=cd['department'], - manufacturer=cd['manufacturer'], - name=cd['name'], - abv=cd['abv'], - unit=cd['unit'], - saleprice=cd['saleprice'], - ) - td.s.add(s) - td.s.flush() + try: + s = StockType( + department=cd['department'], + manufacturer=cd['manufacturer'], + name=cd['name'], + abv=cd['abv'], + unit=cd['unit'], + saleprice=cd['saleprice'], + ) + td.s.add(s) + td.s.commit() + except sqlalchemy.exc.IntegrityError: + td.s.rollback() + messages.error( + request, "Could not create a new stock type: there is " + "another stock type that's an exact match for the new " + "details. This stock type is shown below.") + s = td.s.query(StockType)\ + .filter(StockType.department == cd['department'])\ + .filter(StockType.manufacturer == cd['manufacturer'])\ + .filter(StockType.name == cd['name'])\ + .filter(StockType.abv == cd['abv'])\ + .filter(StockType.unit == cd['unit'])\ + .one() + return HttpResponseRedirect(s.get_absolute_url()) user.log(f"Created stock type {s.logref}") td.s.commit() messages.success(request, "New stock type created")