shimatta-kenkyusho/shimatta_kenkyusho/parts/forms.py

107 lines
3.3 KiB
Python

from django import forms
from django.core.exceptions import ValidationError
from parts import models as parts_models
class MyTestForm(forms.Form):
pass
class AddSubStorageForm(forms.Form):
storage_name = forms.CharField(label="storage_name", initial='')
responsible = forms.CharField(label='responsible_user')
class DeleteStockForm(forms.Form):
stock_uuid = forms.UUIDField()
class EditWatermarkForm(forms.Form):
stock_uuid = forms.UUIDField()
watermark_active = forms.BooleanField(required=False) #If it is false, the webbrowser won't send it at all. Therefore we have to set it to required=False
watermark = forms.IntegerField(min_value=0)
def clean(self):
cleaned_data = super().clean()
id = cleaned_data.get("stock_uuid")
if not id:
raise ValidationError("No stock UUID given")
stock = None
try:
stock = parts_models.Stock.objects.get(id=id)
except:
raise ValidationError("Stock with uuid %s does not exist" % (id))
cleaned_data['stock'] = stock
return cleaned_data
def save(self):
stock = self.cleaned_data['stock']
active = self.cleaned_data['watermark_active']
watermark = self.cleaned_data['watermark']
if not active:
watermark = -1
stock.watermark = watermark
stock.save()
class EditStockAmountForm(forms.Form):
stock_uuid = forms.UUIDField()
amount = forms.IntegerField(min_value=0)
def clean(self):
cleaned_data = super().clean()
id = cleaned_data.get("stock_uuid")
if not id:
raise ValidationError("No stock UUID given")
stock = None
try:
stock = parts_models.Stock.objects.get(id=id)
except:
raise ValidationError("Stock with uuid %s does not exist" % (id))
cleaned_data['stock'] = stock
return cleaned_data
def save(self, increase: bool):
stock = self.cleaned_data['stock']
amount = self.cleaned_data['amount']
if not increase:
amount = -amount
return stock.atomic_increment(amount)
class AddStockForm(forms.Form):
watermark_active = forms.BooleanField(required=False)
watermark = forms.IntegerField(min_value=0, required=True, initial=0)
amount = forms.IntegerField(min_value=0, required=True, initial=1)
component_uuid = forms.UUIDField(required=True)
def clean(self):
cleaned_data = super().clean()
id = cleaned_data.get('component_uuid')
if not id:
raise ValidationError('No valid component selected!')
component = None
try:
component = parts_models.Component.objects.get(id=id)
except:
raise ValidationError("Invalid component selected!")
cleaned_data['component'] = component
return cleaned_data
def save(self, storage):
component = self.cleaned_data.get('component')
amount = self.cleaned_data.get('amount')
watermark = -1
if self.cleaned_data.get('watermark-active'):
watermark = self.cleaned_data.get('watermark')
new_stock = parts_models.Stock.objects.create(storage=storage, component=component, watermark=watermark, amount=amount)
new_stock.save()