From 6eb3c62b83363e9ebd405dfe9726377e77f2337f Mon Sep 17 00:00:00 2001 From: Santiago L Date: Tue, 22 Feb 2022 11:12:15 +0100 Subject: [PATCH 1/8] Update ereuse_devicehub/inventory/forms.py --- ereuse_devicehub/inventory/forms.py | 1 + 1 file changed, 1 insertion(+) diff --git a/ereuse_devicehub/inventory/forms.py b/ereuse_devicehub/inventory/forms.py index e6b6bb05..a997040e 100644 --- a/ereuse_devicehub/inventory/forms.py +++ b/ereuse_devicehub/inventory/forms.py @@ -727,6 +727,7 @@ class TradeForm(NewActionForm): code = self.code.data if user_from and user_to: + # both users exist, no further action is necessary return # Creating receiver phantom account From 2cff0499cbf3a0295e57f667fef0828e8fe673b4 Mon Sep 17 00:00:00 2001 From: Santiago L Date: Tue, 22 Feb 2022 11:13:00 +0100 Subject: [PATCH 2/8] Apply suggestions from code review --- ereuse_devicehub/inventory/forms.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ereuse_devicehub/inventory/forms.py b/ereuse_devicehub/inventory/forms.py index a997040e..79744842 100644 --- a/ereuse_devicehub/inventory/forms.py +++ b/ereuse_devicehub/inventory/forms.py @@ -730,7 +730,7 @@ class TradeForm(NewActionForm): # both users exist, no further action is necessary return - # Creating receiver phantom account + # Create receiver (to) phantom account if user_from and not user_to: assert g.user.email == user_from user = self.create_user(code) @@ -738,7 +738,7 @@ class TradeForm(NewActionForm): self.user_to = user return - # Creating supplier phantom account + # Create supplier (from) phantom account if not user_from and user_to: assert g.user.email == user_to user = self.create_user(code) From 96a240b3cd066265d215dab9094097d4543d904d Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Tue, 22 Feb 2022 11:15:37 +0100 Subject: [PATCH 3/8] drop enconded as unicode --- ereuse_devicehub/inventory/forms.py | 106 ++++++++++++++-------------- 1 file changed, 53 insertions(+), 53 deletions(-) diff --git a/ereuse_devicehub/inventory/forms.py b/ereuse_devicehub/inventory/forms.py index e6b6bb05..b51097d5 100644 --- a/ereuse_devicehub/inventory/forms.py +++ b/ereuse_devicehub/inventory/forms.py @@ -32,8 +32,8 @@ from ereuse_devicehub.resources.user.exceptions import InsufficientPermission class LotDeviceForm(FlaskForm): - lot = StringField(u'Lot', [validators.UUID()]) - devices = StringField(u'Devices', [validators.length(min=1)]) + lot = StringField('Lot', [validators.UUID()]) + devices = StringField('Devices', [validators.length(min=1)]) def validate(self, extra_validators=None): is_valid = super().validate(extra_validators) @@ -68,7 +68,7 @@ class LotDeviceForm(FlaskForm): class LotForm(FlaskForm): - name = StringField(u'Name', [validators.length(min=1)]) + name = StringField('Name', [validators.length(min=1)]) def __init__(self, *args, **kwargs): self.id = kwargs.pop('id', None) @@ -103,7 +103,7 @@ class LotForm(FlaskForm): class UploadSnapshotForm(FlaskForm): - snapshot = MultipleFileField(u'Select a Snapshot File', [validators.DataRequired()]) + snapshot = MultipleFileField('Select a Snapshot File', [validators.DataRequired()]) def validate(self, extra_validators=None): is_valid = super().validate(extra_validators) @@ -227,27 +227,27 @@ class UploadSnapshotForm(FlaskForm): class NewDeviceForm(FlaskForm): - type = StringField(u'Type', [validators.DataRequired()]) - label = StringField(u'Label') - serial_number = StringField(u'Seria Number', [validators.DataRequired()]) - model = StringField(u'Model', [validators.DataRequired()]) - manufacturer = StringField(u'Manufacturer', [validators.DataRequired()]) - appearance = StringField(u'Appearance', [validators.Optional()]) - functionality = StringField(u'Functionality', [validators.Optional()]) - brand = StringField(u'Brand') - generation = IntegerField(u'Generation') - version = StringField(u'Version') - weight = FloatField(u'Weight', [validators.DataRequired()]) - width = FloatField(u'Width', [validators.DataRequired()]) - height = FloatField(u'Height', [validators.DataRequired()]) - depth = FloatField(u'Depth', [validators.DataRequired()]) - variant = StringField(u'Variant', [validators.Optional()]) - sku = StringField(u'SKU', [validators.Optional()]) - image = StringField(u'Image', [validators.Optional(), validators.URL()]) - imei = IntegerField(u'IMEI', [validators.Optional()]) - meid = StringField(u'MEID', [validators.Optional()]) - resolution = IntegerField(u'Resolution width', [validators.Optional()]) - screen = FloatField(u'Screen size', [validators.Optional()]) + type = StringField('Type', [validators.DataRequired()]) + label = StringField('Label') + serial_number = StringField('Seria Number', [validators.DataRequired()]) + model = StringField('Model', [validators.DataRequired()]) + manufacturer = StringField('Manufacturer', [validators.DataRequired()]) + appearance = StringField('Appearance', [validators.Optional()]) + functionality = StringField('Functionality', [validators.Optional()]) + brand = StringField('Brand') + generation = IntegerField('Generation') + version = StringField('Version') + weight = FloatField('Weight', [validators.DataRequired()]) + width = FloatField('Width', [validators.DataRequired()]) + height = FloatField('Height', [validators.DataRequired()]) + depth = FloatField('Depth', [validators.DataRequired()]) + variant = StringField('Variant', [validators.Optional()]) + sku = StringField('SKU', [validators.Optional()]) + image = StringField('Image', [validators.Optional(), validators.URL()]) + imei = IntegerField('IMEI', [validators.Optional()]) + meid = StringField('MEID', [validators.Optional()]) + resolution = IntegerField('Resolution width', [validators.Optional()]) + screen = FloatField('Screen size', [validators.Optional()]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -387,7 +387,7 @@ class NewDeviceForm(FlaskForm): class TagForm(FlaskForm): - code = StringField(u'Code', [validators.length(min=1)]) + code = StringField('Code', [validators.length(min=1)]) def validate(self, extra_validators=None): error = ["This value is being used"] @@ -415,7 +415,7 @@ class TagForm(FlaskForm): class TagUnnamedForm(FlaskForm): - amount = IntegerField(u'amount') + amount = IntegerField('amount') def save(self): num = self.amount.data @@ -427,8 +427,8 @@ class TagUnnamedForm(FlaskForm): class TagDeviceForm(FlaskForm): - tag = SelectField(u'Tag', choices=[]) - device = StringField(u'Device', [validators.Optional()]) + tag = SelectField('Tag', choices=[]) + device = StringField('Device', [validators.Optional()]) def __init__(self, *args, **kwargs): self.delete = kwargs.pop('delete', None) @@ -481,19 +481,19 @@ class TagDeviceForm(FlaskForm): class NewActionForm(FlaskForm): - name = StringField(u'Name', [validators.length(max=50)], + name = StringField('Name', [validators.length(max=50)], description="A name or title of the event. Something to look for.") devices = HiddenField() - date = DateField(u'Date', [validators.Optional()], + date = DateField('Date', [validators.Optional()], description="""When the action ends. For some actions like booking the time when it expires, for others like renting the time that the end rents. For specific actions, it is the time in which they are carried out; differs from created in that created is where the system receives the action.""") - severity = SelectField(u'Severity', choices=[(v.name, v.name) for v in Severity], + severity = SelectField('Severity', choices=[(v.name, v.name) for v in Severity], description="""An indicator that evaluates the execution of the event. For example, failed events are set to Error""") - description = TextAreaField(u'Description') + description = TextAreaField('Description') lot = HiddenField() type = HiddenField() @@ -544,11 +544,11 @@ class NewActionForm(FlaskForm): class AllocateForm(NewActionForm): - start_time = DateField(u'Start time') - end_time = DateField(u'End time') - final_user_code = StringField(u'Final user code', [validators.length(max=50)]) - transaction = StringField(u'Transaction', [validators.length(max=50)]) - end_users = IntegerField(u'End users') + start_time = DateField('Start time') + end_time = DateField('End time') + final_user_code = StringField('Final user code', [validators.length(max=50)]) + transaction = StringField('Transaction', [validators.length(max=50)]) + end_users = IntegerField('End users') def validate(self, extra_validators=None): is_valid = super().validate(extra_validators) @@ -569,17 +569,17 @@ class AllocateForm(NewActionForm): class DataWipeDocumentForm(Form): - date = DateField(u'Date', [validators.Optional()], + date = DateField('Date', [validators.Optional()], description="Date when was data wipe") - url = URLField(u'Url', [validators.Optional()], + url = URLField('Url', [validators.Optional()], description="Url where the document resides") - success = BooleanField(u'Success', [validators.Optional()], + success = BooleanField('Success', [validators.Optional()], description="The erase was success or not?") - software = StringField(u'Software', [validators.Optional()], + software = StringField('Software', [validators.Optional()], description="Which software has you use for erase the disks") - id_document = StringField(u'Document Id', [validators.Optional()], + id_document = StringField('Document Id', [validators.Optional()], description="Identification number of document") - file_name = FileField(u'File', [validators.DataRequired()], + file_name = FileField('File', [validators.DataRequired()], description="""This file is not stored on our servers, it is only used to generate a digital signature and obtain the name of the file.""") @@ -637,16 +637,16 @@ class DataWipeForm(NewActionForm): class TradeForm(NewActionForm): - user_from = StringField(u'Supplier', [validators.Optional()], + user_from = StringField('Supplier', [validators.Optional()], description="Please enter the supplier's email address", render_kw={'data-email': ""}) - user_to = StringField(u'Receiver', [validators.Optional()], + user_to = StringField('Receiver', [validators.Optional()], description="Please enter the receiver's email address", render_kw={'data-email': ""}) - confirm = BooleanField(u'Confirm', [validators.Optional()], + confirm = BooleanField('Confirm', [validators.Optional()], default=True, description="I need confirmation from the other user for every device and document.") - code = StringField(u'Code', [validators.Optional()], + code = StringField('Code', [validators.Optional()], description="If you don't need confirm, you need put a code for trace the user in the statistics.") def __init__(self, *args, **kwargs): @@ -774,19 +774,19 @@ class TradeForm(NewActionForm): class TradeDocumentForm(FlaskForm): - url = URLField(u'Url', [validators.Optional()], + url = URLField('Url', [validators.Optional()], render_kw={'class': "form-control"}, description="Url where the document resides") - description = StringField(u'Description', [validators.Optional()], + description = StringField('Description', [validators.Optional()], render_kw={'class': "form-control"}, description="") - id_document = StringField(u'Document Id', [validators.Optional()], + id_document = StringField('Document Id', [validators.Optional()], render_kw={'class': "form-control"}, description="Identification number of document") - date = DateField(u'Date', [validators.Optional()], + date = DateField('Date', [validators.Optional()], render_kw={'class': "form-control"}, description="") - file_name = FileField(u'File', [validators.DataRequired()], + file_name = FileField('File', [validators.DataRequired()], render_kw={'class': "form-control"}, description="""This file is not stored on our servers, it is only used to generate a digital signature and obtain the name of the file.""") From 88deb71a261b12c000aa32bb589d3171da27dec5 Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Tue, 22 Feb 2022 11:24:11 +0100 Subject: [PATCH 4/8] changes of review --- ereuse_devicehub/inventory/forms.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/ereuse_devicehub/inventory/forms.py b/ereuse_devicehub/inventory/forms.py index 4271191b..521487ee 100644 --- a/ereuse_devicehub/inventory/forms.py +++ b/ereuse_devicehub/inventory/forms.py @@ -19,6 +19,7 @@ from wtforms import (BooleanField, DateField, FileField, FloatField, Form, HiddenField, IntegerField, MultipleFileField, SelectField, StringField, TextAreaField, URLField, validators) from wtforms.fields import FormField +from wtforms.validators import ValidationError from ereuse_devicehub.resources.device.sync import Sync from ereuse_devicehub.resources.documents.models import DataWipeDocument @@ -685,7 +686,8 @@ class TradeForm(NewActionForm): return is_valid def save(self, commit=True): - self.create_phantom_account() + if not self.confirm.data: + self.create_phantom_account() self.prepare_instance() self.create_automatic_trade() @@ -719,8 +721,9 @@ class TradeForm(NewActionForm): """ # Checks - if self.confirm.data or not self.code.data: - return + if self.code.data: + msg = "If you don't want confirm, you need a code" + return ValidationError(msg) user_from = self.user_from.data user_to = self.user_to.data @@ -745,7 +748,7 @@ class TradeForm(NewActionForm): self.user_from = user self.user_to = g.user - def create_user(self, code): + def get_or_create_user(self, code): email = "{}_{}@dhub.com".format(str(g.user.id), code) user = User.query.filter_by(email=email).first() if not user: From 90eb279008f2e555fede9c2d73ac79765a048e4f Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Tue, 22 Feb 2022 11:31:11 +0100 Subject: [PATCH 5/8] fix get_or_create_user --- ereuse_devicehub/inventory/forms.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ereuse_devicehub/inventory/forms.py b/ereuse_devicehub/inventory/forms.py index 521487ee..8d0107b0 100644 --- a/ereuse_devicehub/inventory/forms.py +++ b/ereuse_devicehub/inventory/forms.py @@ -736,7 +736,7 @@ class TradeForm(NewActionForm): # Create receiver (to) phantom account if user_from and not user_to: assert g.user.email == user_from - user = self.create_user(code) + user = self.get_or_create_user(code) self.user_from = g.user self.user_to = user return @@ -744,7 +744,7 @@ class TradeForm(NewActionForm): # Create supplier (from) phantom account if not user_from and user_to: assert g.user.email == user_to - user = self.create_user(code) + user = self.get_or_create_user(code) self.user_from = user self.user_to = g.user From bacf14ece8c128a78f7f91d5982b33951ae075ed Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Tue, 22 Feb 2022 11:55:01 +0100 Subject: [PATCH 6/8] Fix method call to `get_or_create_user()` --- ereuse_devicehub/inventory/forms.py | 317 ++++++++++++++++++---------- 1 file changed, 202 insertions(+), 115 deletions(-) diff --git a/ereuse_devicehub/inventory/forms.py b/ereuse_devicehub/inventory/forms.py index 521487ee..02cba588 100644 --- a/ereuse_devicehub/inventory/forms.py +++ b/ereuse_devicehub/inventory/forms.py @@ -3,33 +3,35 @@ import json from json.decoder import JSONDecodeError from boltons.urlutils import URL +from flask import g, request +from flask_wtf import FlaskForm +from sqlalchemy.util import OrderedSet +from wtforms import ( + BooleanField, DateField, FileField, FloatField, Form, HiddenField, + IntegerField, MultipleFileField, SelectField, StringField, TextAreaField, + URLField, validators) +from wtforms.fields import FormField +from wtforms.validators import ValidationError + from ereuse_devicehub.db import db from ereuse_devicehub.resources.action.models import RateComputer, Snapshot from ereuse_devicehub.resources.action.rate.v1_0 import CannotRate from ereuse_devicehub.resources.action.schemas import \ Snapshot as SnapshotSchema -from ereuse_devicehub.resources.action.views.snapshot import move_json, save_json -from ereuse_devicehub.resources.device.models import (SAI, Cellphone, Computer, - Device, Keyboard, MemoryCardReader, - Monitor, Mouse, Smartphone, Tablet) -from flask import g, request -from flask_wtf import FlaskForm -from sqlalchemy.util import OrderedSet -from wtforms import (BooleanField, DateField, FileField, FloatField, Form, - HiddenField, IntegerField, MultipleFileField, SelectField, - StringField, TextAreaField, URLField, validators) -from wtforms.fields import FormField -from wtforms.validators import ValidationError - +from ereuse_devicehub.resources.action.views.snapshot import ( + move_json, save_json) +from ereuse_devicehub.resources.device.models import ( + SAI, Cellphone, Computer, Device, Keyboard, MemoryCardReader, Monitor, + Mouse, Smartphone, Tablet) from ereuse_devicehub.resources.device.sync import Sync from ereuse_devicehub.resources.documents.models import DataWipeDocument from ereuse_devicehub.resources.enums import Severity, SnapshotSoftware from ereuse_devicehub.resources.hash_reports import insert_hash from ereuse_devicehub.resources.lot.models import Lot from ereuse_devicehub.resources.tag.model import Tag -from ereuse_devicehub.resources.user.models import User from ereuse_devicehub.resources.tradedocument.models import TradeDocument from ereuse_devicehub.resources.user.exceptions import InsufficientPermission +from ereuse_devicehub.resources.user.models import User class LotDeviceForm(FlaskForm): @@ -42,12 +44,19 @@ class LotDeviceForm(FlaskForm): if not is_valid: return False - self._lot = Lot.query.filter(Lot.id == self.lot.data).filter( - Lot.owner_id == g.user.id).one() + self._lot = ( + Lot.query.filter(Lot.id == self.lot.data) + .filter(Lot.owner_id == g.user.id) + .one() + ) devices = set(self.devices.data.split(",")) - self._devices = Device.query.filter(Device.id.in_(devices)).filter( - Device.owner_id == g.user.id).distinct().all() + self._devices = ( + Device.query.filter(Device.id.in_(devices)) + .filter(Device.owner_id == g.user.id) + .distinct() + .all() + ) return bool(self._devices) @@ -75,8 +84,11 @@ class LotForm(FlaskForm): self.id = kwargs.pop('id', None) self.instance = None if self.id: - self.instance = Lot.query.filter(Lot.id == self.id).filter( - Lot.owner_id == g.user.id).one() + self.instance = ( + Lot.query.filter(Lot.id == self.id) + .filter(Lot.owner_id == g.user.id) + .one() + ) super().__init__(*args, **kwargs) if self.instance and not self.name.data: self.name.data = self.instance.name @@ -172,7 +184,9 @@ class UploadSnapshotForm(FlaskForm): # this is a copy adaptated from ereuse_devicehub.resources.action.views.snapshot device = snapshot_json.pop('device') # type: Computer components = None - if snapshot_json['software'] == (SnapshotSoftware.Workbench or SnapshotSoftware.WorkbenchAndroid): + if snapshot_json['software'] == ( + SnapshotSoftware.Workbench or SnapshotSoftware.WorkbenchAndroid + ): components = snapshot_json.pop('components', None) # type: List[Component] if isinstance(device, Computer) and device.hid: device.add_mac_to_hid(components_snap=components) @@ -182,7 +196,9 @@ class UploadSnapshotForm(FlaskForm): actions_device = set(e for e in device.actions_one) device.actions_one.clear() if components: - actions_components = tuple(set(e for e in c.actions_one) for c in components) + actions_components = tuple( + set(e for e in c.actions_one) for c in components + ) for component in components: component.actions_one.clear() @@ -252,14 +268,16 @@ class NewDeviceForm(FlaskForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - self.devices = {"Smartphone": Smartphone, - "Tablet": Tablet, - "Cellphone": Cellphone, - "Monitor": Monitor, - "Mouse": Mouse, - "Keyboard": Keyboard, - "SAI": SAI, - "MemoryCardReader": MemoryCardReader} + self.devices = { + "Smartphone": Smartphone, + "Tablet": Tablet, + "Cellphone": Cellphone, + "Monitor": Monitor, + "Mouse": Mouse, + "Keyboard": Keyboard, + "SAI": SAI, + "MemoryCardReader": MemoryCardReader, + } if not self.generation.data: self.generation.data = 1 @@ -336,29 +354,31 @@ class NewDeviceForm(FlaskForm): 'software': 'Web', 'version': '11.0', 'device': { - 'type': self.type.data, - 'model': self.model.data, - 'manufacturer': self.manufacturer.data, - 'serialNumber': self.serial_number.data, - 'brand': self.brand.data, - 'version': self.version.data, - 'generation': self.generation.data, - 'sku': self.sku.data, - 'weight': self.weight.data, - 'width': self.width.data, - 'height': self.height.data, - 'depth': self.depth.data, - 'variant': self.variant.data, - 'image': self.image.data - } + 'type': self.type.data, + 'model': self.model.data, + 'manufacturer': self.manufacturer.data, + 'serialNumber': self.serial_number.data, + 'brand': self.brand.data, + 'version': self.version.data, + 'generation': self.generation.data, + 'sku': self.sku.data, + 'weight': self.weight.data, + 'width': self.width.data, + 'height': self.height.data, + 'depth': self.depth.data, + 'variant': self.variant.data, + 'image': self.image.data, + }, } if self.appearance.data or self.functionality.data: - json_snapshot['device']['actions'] = [{ - 'type': 'VisualTest', - 'appearanceRange': self.appearance.data, - 'functionalityRange': self.functionality.data - }] + json_snapshot['device']['actions'] = [ + { + 'type': 'VisualTest', + 'appearanceRange': self.appearance.data, + 'functionalityRange': self.functionality.data, + } + ] upload_form = UploadSnapshotForm() upload_form.sync = Sync() @@ -395,7 +415,7 @@ class TagForm(FlaskForm): is_valid = super().validate(extra_validators) if not is_valid: return False - tag = Tag.query.filter(Tag.id==self.code.data).all() + tag = Tag.query.filter(Tag.id == self.code.data).all() if tag: self.code.errors = error return False @@ -438,9 +458,13 @@ class TagDeviceForm(FlaskForm): super().__init__(*args, **kwargs) if self.delete: - tags = Tag.query.filter(Tag.owner_id==g.user.id).filter(Tag.device_id==self.device_id) + tags = Tag.query.filter(Tag.owner_id == g.user.id).filter( + Tag.device_id == self.device_id + ) else: - tags = Tag.query.filter(Tag.owner_id==g.user.id).filter(Tag.device_id==None) + tags = Tag.query.filter(Tag.owner_id == g.user.id).filter( + Tag.device_id == None + ) self.tag.choices = [(tag.id, tag.id) for tag in tags] @@ -450,8 +474,11 @@ class TagDeviceForm(FlaskForm): if not is_valid: return False - self._tag = Tag.query.filter(Tag.id == self.tag.data).filter( - Tag.owner_id == g.user.id).one() + self._tag = ( + Tag.query.filter(Tag.id == self.tag.data) + .filter(Tag.owner_id == g.user.id) + .one() + ) if not self.delete and self._tag.device_id: self.tag.errors = [("This tag is actualy in use.")] @@ -465,8 +492,11 @@ class TagDeviceForm(FlaskForm): if self.device_id or self.device.data: self.device_id = self.device_id or self.device.data - self._device = Device.query.filter(Device.id == self.device_id).filter( - Device.owner_id == g.user.id).one() + self._device = ( + Device.query.filter(Device.id == self.device_id) + .filter(Device.owner_id == g.user.id) + .one() + ) return True @@ -482,18 +512,27 @@ class TagDeviceForm(FlaskForm): class NewActionForm(FlaskForm): - name = StringField('Name', [validators.length(max=50)], - description="A name or title of the event. Something to look for.") + name = StringField( + 'Name', + [validators.length(max=50)], + description="A name or title of the event. Something to look for.", + ) devices = HiddenField() - date = DateField('Date', [validators.Optional()], - description="""When the action ends. For some actions like booking + date = DateField( + 'Date', + [validators.Optional()], + description="""When the action ends. For some actions like booking the time when it expires, for others like renting the time that the end rents. For specific actions, it is the time in which they are carried out; differs from created - in that created is where the system receives the action.""") - severity = SelectField('Severity', choices=[(v.name, v.name) for v in Severity], - description="""An indicator that evaluates the execution of the event. - For example, failed events are set to Error""") + in that created is where the system receives the action.""", + ) + severity = SelectField( + 'Severity', + choices=[(v.name, v.name) for v in Severity], + description="""An indicator that evaluates the execution of the event. + For example, failed events are set to Error""", + ) description = TextAreaField('Description') lot = HiddenField() type = HiddenField() @@ -507,8 +546,11 @@ class NewActionForm(FlaskForm): self._devices = OrderedSet() if self.devices.data: devices = set(self.devices.data.split(",")) - self._devices = OrderedSet(Device.query.filter(Device.id.in_(devices)).filter( - Device.owner_id == g.user.id).all()) + self._devices = OrderedSet( + Device.query.filter(Device.id.in_(devices)) + .filter(Device.owner_id == g.user.id) + .all() + ) if not self._devices: return False @@ -570,19 +612,31 @@ class AllocateForm(NewActionForm): class DataWipeDocumentForm(Form): - date = DateField('Date', [validators.Optional()], - description="Date when was data wipe") - url = URLField('Url', [validators.Optional()], - description="Url where the document resides") - success = BooleanField('Success', [validators.Optional()], - description="The erase was success or not?") - software = StringField('Software', [validators.Optional()], - description="Which software has you use for erase the disks") - id_document = StringField('Document Id', [validators.Optional()], - description="Identification number of document") - file_name = FileField('File', [validators.DataRequired()], - description="""This file is not stored on our servers, it is only used to - generate a digital signature and obtain the name of the file.""") + date = DateField( + 'Date', [validators.Optional()], description="Date when was data wipe" + ) + url = URLField( + 'Url', [validators.Optional()], description="Url where the document resides" + ) + success = BooleanField( + 'Success', [validators.Optional()], description="The erase was success or not?" + ) + software = StringField( + 'Software', + [validators.Optional()], + description="Which software has you use for erase the disks", + ) + id_document = StringField( + 'Document Id', + [validators.Optional()], + description="Identification number of document", + ) + file_name = FileField( + 'File', + [validators.DataRequired()], + description="""This file is not stored on our servers, it is only used to + generate a digital signature and obtain the name of the file.""", + ) def validate(self, extra_validators=None): is_valid = super().validate(extra_validators) @@ -638,23 +692,39 @@ class DataWipeForm(NewActionForm): class TradeForm(NewActionForm): - user_from = StringField('Supplier', [validators.Optional()], - description="Please enter the supplier's email address", - render_kw={'data-email': ""}) - user_to = StringField('Receiver', [validators.Optional()], - description="Please enter the receiver's email address", - render_kw={'data-email': ""}) - confirm = BooleanField('Confirm', [validators.Optional()], - default=True, - description="I need confirmation from the other user for every device and document.") - code = StringField('Code', [validators.Optional()], - description="If you don't need confirm, you need put a code for trace the user in the statistics.") + user_from = StringField( + 'Supplier', + [validators.Optional()], + description="Please enter the supplier's email address", + render_kw={'data-email': ""}, + ) + user_to = StringField( + 'Receiver', + [validators.Optional()], + description="Please enter the receiver's email address", + render_kw={'data-email': ""}, + ) + confirm = BooleanField( + 'Confirm', + [validators.Optional()], + default=True, + description="I need confirmation from the other user for every device and document.", + ) + code = StringField( + 'Code', + [validators.Optional()], + description="If you don't need confirm, you need put a code for trace the user in the statistics.", + ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user_from.render_kw['data-email'] = g.user.email self.user_to.render_kw['data-email'] = g.user.email - self._lot = Lot.query.filter(Lot.id==self.lot.data).filter(Lot.owner_id==g.user.id).one() + self._lot = ( + Lot.query.filter(Lot.id == self.lot.data) + .filter(Lot.owner_id == g.user.id) + .one() + ) def validate(self, extra_validators=None): is_valid = self.generic_validation(extra_validators=extra_validators) @@ -665,8 +735,12 @@ class TradeForm(NewActionForm): self.code.errors = ["If you don't want confirm, you need a code"] is_valid = False - if self.confirm.data and not (email_from and email_to) or email_to == email_from or \ - g.user.email not in [email_from, email_to]: + if ( + self.confirm.data + and not (email_from and email_to) + or email_to == email_from + or g.user.email not in [email_from, email_to] + ): errors = ["If you want confirm, you need a correct email"] self.user_to.errors = errors @@ -736,16 +810,14 @@ class TradeForm(NewActionForm): # Create receiver (to) phantom account if user_from and not user_to: assert g.user.email == user_from - user = self.create_user(code) self.user_from = g.user - self.user_to = user + self.user_to = self.get_or_create_user(code) return # Create supplier (from) phantom account if not user_from and user_to: assert g.user.email == user_to - user = self.create_user(code) - self.user_from = user + self.user_from = self.get_or_create_user(code) self.user_to = g.user def get_or_create_user(self, code): @@ -778,27 +850,42 @@ class TradeForm(NewActionForm): class TradeDocumentForm(FlaskForm): - url = URLField('Url', [validators.Optional()], - render_kw={'class': "form-control"}, - description="Url where the document resides") - description = StringField('Description', [validators.Optional()], - render_kw={'class': "form-control"}, - description="") - id_document = StringField('Document Id', [validators.Optional()], - render_kw={'class': "form-control"}, - description="Identification number of document") - date = DateField('Date', [validators.Optional()], - render_kw={'class': "form-control"}, - description="") - file_name = FileField('File', [validators.DataRequired()], - render_kw={'class': "form-control"}, - description="""This file is not stored on our servers, it is only used to - generate a digital signature and obtain the name of the file.""") + url = URLField( + 'Url', + [validators.Optional()], + render_kw={'class': "form-control"}, + description="Url where the document resides", + ) + description = StringField( + 'Description', + [validators.Optional()], + render_kw={'class': "form-control"}, + description="", + ) + id_document = StringField( + 'Document Id', + [validators.Optional()], + render_kw={'class': "form-control"}, + description="Identification number of document", + ) + date = DateField( + 'Date', + [validators.Optional()], + render_kw={'class': "form-control"}, + description="", + ) + file_name = FileField( + 'File', + [validators.DataRequired()], + render_kw={'class': "form-control"}, + description="""This file is not stored on our servers, it is only used to + generate a digital signature and obtain the name of the file.""", + ) def __init__(self, *args, **kwargs): lot_id = kwargs.pop('lot') super().__init__(*args, **kwargs) - self._lot = Lot.query.filter(Lot.id==lot_id).one() + self._lot = Lot.query.filter(Lot.id == lot_id).one() def validate(self, extra_validators=None): is_valid = super().validate(extra_validators) From d4e61d992b90ba40cbb6e684c8152e1abc8ec7fb Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Tue, 22 Feb 2022 12:04:26 +0100 Subject: [PATCH 7/8] Raise error if trying to save when validation has failed --- ereuse_devicehub/inventory/forms.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/ereuse_devicehub/inventory/forms.py b/ereuse_devicehub/inventory/forms.py index 02cba588..41120358 100644 --- a/ereuse_devicehub/inventory/forms.py +++ b/ereuse_devicehub/inventory/forms.py @@ -732,7 +732,7 @@ class TradeForm(NewActionForm): email_to = self.user_to.data if not self.confirm.data and not self.code.data: - self.code.errors = ["If you don't want confirm, you need a code"] + self.code.errors = ["If you don't want to confirm, you need a code"] is_valid = False if ( @@ -757,9 +757,15 @@ class TradeForm(NewActionForm): self.db_user_to = user_to self.db_user_from = user_from + self.has_errors = not is_valid return is_valid def save(self, commit=True): + if self.has_errors: + raise ValueError( + "The %s could not be saved because the data didn't validate." + % (self.instance._meta.object_name) + ) if not self.confirm.data: self.create_phantom_account() self.prepare_instance() @@ -794,11 +800,6 @@ class TradeForm(NewActionForm): The same if exist to but not from """ - # Checks - if self.code.data: - msg = "If you don't want confirm, you need a code" - return ValidationError(msg) - user_from = self.user_from.data user_to = self.user_to.data code = self.code.data From c54d9a902c6cdbd70b8c8b65c96dc0b2f8c0c6da Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Fri, 25 Feb 2022 09:49:15 +0100 Subject: [PATCH 8/8] fix bug in trade template --- ereuse_devicehub/templates/inventory/device_list.html | 4 +--- ereuse_devicehub/templates/inventory/trade.html | 3 +++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/ereuse_devicehub/templates/inventory/device_list.html b/ereuse_devicehub/templates/inventory/device_list.html index ce3350af..9f8af548 100644 --- a/ereuse_devicehub/templates/inventory/device_list.html +++ b/ereuse_devicehub/templates/inventory/device_list.html @@ -352,9 +352,7 @@ {% include "inventory/actions.html" %} {% include "inventory/allocate.html" %} {% include "inventory/data_wipe.html" %} -{% if lot and lot.is_temporary %} - {% include "inventory/trade.html" %} -{% endif %} +{% include "inventory/trade.html" %} diff --git a/ereuse_devicehub/templates/inventory/trade.html b/ereuse_devicehub/templates/inventory/trade.html index 42b39aa0..66d061fe 100644 --- a/ereuse_devicehub/templates/inventory/trade.html +++ b/ereuse_devicehub/templates/inventory/trade.html @@ -55,4 +55,7 @@ +{% else %} +