From 7ee2f2962bb2884b1a4f333728b96f1ac1bf4bc0 Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Wed, 11 May 2022 11:48:53 +0200 Subject: [PATCH 01/18] add view for download Workbench settings --- .../templates/ereuse_devicehub/base_site.html | 10 ++ .../templates/workbench/settings.html | 59 ++++++++++++ ereuse_devicehub/workbench/__init__.py | 0 ereuse_devicehub/workbench/views.py | 94 +++++++++++++++++++ examples/app.py | 2 + tests/conftest.py | 2 + 6 files changed, 167 insertions(+) create mode 100644 ereuse_devicehub/templates/workbench/settings.html create mode 100644 ereuse_devicehub/workbench/__init__.py create mode 100644 ereuse_devicehub/workbench/views.py diff --git a/ereuse_devicehub/templates/ereuse_devicehub/base_site.html b/ereuse_devicehub/templates/ereuse_devicehub/base_site.html index fe014107..1774e6df 100644 --- a/ereuse_devicehub/templates/ereuse_devicehub/base_site.html +++ b/ereuse_devicehub/templates/ereuse_devicehub/base_site.html @@ -64,6 +64,16 @@ +
  • + + + Workbench Settings + +
  • +
  • + +
  • +
  • diff --git a/ereuse_devicehub/templates/workbench/settings.html b/ereuse_devicehub/templates/workbench/settings.html new file mode 100644 index 00000000..80278615 --- /dev/null +++ b/ereuse_devicehub/templates/workbench/settings.html @@ -0,0 +1,59 @@ +{% extends "ereuse_devicehub/base_site.html" %} +{% block main %} + +
    +

    {{ title }}

    + +
    + +
    +
    +
    + +
    +
    + +
    +
    Download your settings for Workbench
    +

    Please select one of this options

    +
    +
    + +
    +

    Download the settings for register devices and erase disks. This is less safe and more fast.

    +
    +
    +
    + +
    +

    Download the settings for register devices and erase disks. This is more safe and more slow.

    +
    +
    +
    + +
    + +
    + +
    + +
    +
    +
    +
    +{% endblock main %} diff --git a/ereuse_devicehub/workbench/__init__.py b/ereuse_devicehub/workbench/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/ereuse_devicehub/workbench/views.py b/ereuse_devicehub/workbench/views.py new file mode 100644 index 00000000..ccbdbdc5 --- /dev/null +++ b/ereuse_devicehub/workbench/views.py @@ -0,0 +1,94 @@ +import time + +import flask +from flask import Blueprint +from flask import current_app as app +from flask import g, make_response, request +from flask_login import login_required + +from ereuse_devicehub import auth +from ereuse_devicehub.db import db +from ereuse_devicehub.resources.enums import SessionType +from ereuse_devicehub.resources.user.models import Session +from ereuse_devicehub.views import GenericMixView + +workbench = Blueprint('workbench', __name__, url_prefix='/workbench') + + +class SettingsView(GenericMixView): + decorators = [login_required] + template_name = 'workbench/settings.html' + page_title = "Workbench Settings" + + def dispatch_request(self): + self.get_context() + self.context.update( + { + 'page_title': self.page_title, + } + ) + + self.opt = request.values.get('opt') + if self.opt in ['register', 'soft', 'hard']: + return self.download() + + return flask.render_template(self.template_name, **self.context) + + def download(self): + self.wbContext = { + 'token': self.get_token(), + 'host': app.config['HOST'], + 'inventory': app.config['SCHEMA'], + 'benchmark': False, + 'stress_test': 1, + 'erase': '', + 'steps': 0, + 'leading_zeros': False, + } + options = {"register": self.register, "soft": self.soft, "hard": self.hard} + return options[self.opt]() + + def register(self): + data = flask.render_template('workbench/wbSettings.ini', **self.wbContext) + return self.response_download(data) + + def soft(self): + self.wbContext['erase'] = 'EraseBasic' + self.wbContext['steps'] = 1 + data = flask.render_template('workbench/wbSettings.ini', **self.wbContext) + return self.response_download(data) + + def hard(self): + self.wbContext['erase'] = 'EraseSectors' + self.wbContext['steps'] = 1 + self.wbContext['leading_zeros'] = True + data = flask.render_template('workbench/wbSettings.ini', **self.wbContext) + return self.response_download(data) + + def response_download(self, data): + bfile = str.encode(data) + output = make_response(bfile) + output.headers['Content-Disposition'] = 'attachment; filename=settings.ini' + output.headers['Content-type'] = 'text/plain' + return output + + def get_token(self): + if not g.user.sessions: + ses = Session(user=g.user) + db.session.add(ses) + db.session.commit() + + tk = '' + now = time.time() + for s in g.user.sessions: + if s.type == SessionType.Internal and (s.expired == 0 or s.expired > now): + tk = s.token + break + + assert tk != '' + + token = auth.Auth.encode(tk) + return token + + +workbench.add_url_rule('/settings/', view_func=SettingsView.as_view('settings')) diff --git a/examples/app.py b/examples/app.py index 415d86ce..b0c9b253 100644 --- a/examples/app.py +++ b/examples/app.py @@ -10,11 +10,13 @@ from ereuse_devicehub.devicehub import Devicehub from ereuse_devicehub.inventory.views import devices from ereuse_devicehub.labels.views import labels from ereuse_devicehub.views import core +from ereuse_devicehub.workbench.views import workbench app = Devicehub(inventory=DevicehubConfig.DB_SCHEMA) app.register_blueprint(core) app.register_blueprint(devices) app.register_blueprint(labels) +app.register_blueprint(workbench) # configure & enable CSRF of Flask-WTF # NOTE: enable by blueprint to exclude API views diff --git a/tests/conftest.py b/tests/conftest.py index a8d04506..53fdbaa9 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -24,6 +24,7 @@ from ereuse_devicehub.resources.enums import SessionType from ereuse_devicehub.resources.tag import Tag from ereuse_devicehub.resources.user.models import Session, User from ereuse_devicehub.views import core +from ereuse_devicehub.workbench.views import workbench STARTT = datetime(year=2000, month=1, day=1, hour=1) """A dummy starting time to use in tests.""" @@ -58,6 +59,7 @@ def _app(config: TestConfig) -> Devicehub: app.register_blueprint(core) app.register_blueprint(devices) app.register_blueprint(labels) + app.register_blueprint(workbench) app.config["SQLALCHEMY_RECORD_QUERIES"] = True app.config['PROFILE'] = True # app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30]) From 0e75865757446ba53e2091339a3fe1b5232c5886 Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Wed, 11 May 2022 11:58:54 +0200 Subject: [PATCH 02/18] fix settings.html --- ereuse_devicehub/templates/workbench/settings.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ereuse_devicehub/templates/workbench/settings.html b/ereuse_devicehub/templates/workbench/settings.html index 80278615..6fbeb592 100644 --- a/ereuse_devicehub/templates/workbench/settings.html +++ b/ereuse_devicehub/templates/workbench/settings.html @@ -28,9 +28,9 @@

    Download the settings only for register devices.

    -
    +

    Download the settings for register devices and erase disks. This is less safe and more fast.

    @@ -38,7 +38,7 @@

    Download the settings for register devices and erase disks. This is more safe and more slow.

    From ce001b64aa66b4779f2e5c3891c66c82f69c6727 Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Wed, 11 May 2022 12:39:23 +0200 Subject: [PATCH 03/18] add test for wbsettings --- tests/test_render_2_0.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/test_render_2_0.py b/tests/test_render_2_0.py index 9a52b89f..38dc12cd 100644 --- a/tests/test_render_2_0.py +++ b/tests/test_render_2_0.py @@ -842,3 +842,27 @@ def test_action_datawipe(user3: UserClientFlask): assert dev.actions[-1].type == 'DataWipe' assert 'Action "DataWipe" created successfully!' in body assert dev.devicehub_id in body + + +@pytest.mark.mvp +@pytest.mark.usefixtures(conftest.app_context.__name__) +def test_wb_settings(user3: UserClientFlask): + uri = '/workbench/settings/' + body, status = user3.get(uri) + + assert status == '200 OK' + assert "Download your settings for Workbench" in body + assert "Workbench Settings" in body + + +@pytest.mark.mvp +@pytest.mark.usefixtures(conftest.app_context.__name__) +def test_wb_settings_register(user3: UserClientFlask): + uri = '/workbench/settings/?opt=register' + body, status = user3.get(uri) + + assert status == '200 OK' + assert "WB_BENCHMARK = False" in body + assert "WB_ERASE = \n" in body + assert "WB_ERASE_STEPS = 0" in body + assert "WB_ERASE_LEADING_ZEROS = False" in body From b8e980cabeab2490aa228824a6ab3ade698b8a7d Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Wed, 11 May 2022 13:14:11 +0200 Subject: [PATCH 04/18] fixed tests --- .../templates/workbench/wbSettings.ini | 18 ++++++++++++++++++ tests/test_basic.py | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 ereuse_devicehub/templates/workbench/wbSettings.ini diff --git a/ereuse_devicehub/templates/workbench/wbSettings.ini b/ereuse_devicehub/templates/workbench/wbSettings.ini new file mode 100644 index 00000000..ea45e547 --- /dev/null +++ b/ereuse_devicehub/templates/workbench/wbSettings.ini @@ -0,0 +1,18 @@ +[settings] + +DH_TOKEN = {{token}} + +DH_HOST = {{host}} +DH_DATABASE = {{inventory}} +DEVICEHUB_URL = https://${DB_HOST}/${DB_DATABASE}/ + + +WB_BENCHMARK = {{ benchmark }} +WB_STRESS_TEST = {{ stress_test }} +WB_SMART_TEST = short + +WB_ERASE = {{ erase }} +WB_ERASE_STEPS = {{ steps }} +WB_ERASE_LEADING_ZEROS = {{ leading_zeros }} + +WB_DEBUG = True diff --git a/tests/test_basic.py b/tests/test_basic.py index 4329d996..f9960219 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -19,7 +19,7 @@ def test_dependencies(): # Simplejson has a different signature than stdlib json # should be fixed though # noinspection PyUnresolvedReferences - import simplejson + import simplejson # noqa: F401 # noinspection PyArgumentList @@ -87,6 +87,7 @@ def test_api_docs(client: Client): '/users/login/', '/users/logout/', '/versions/', + '/workbench/settings/', } assert docs['info'] == {'title': 'Devicehub', 'version': '0.2'} assert docs['components']['securitySchemes']['bearerAuth'] == { From 3e33b7d63bf8f3a3e2ec6569e1caee002bffb884 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Wed, 13 Apr 2022 09:44:30 +0200 Subject: [PATCH 05/18] Refactor DeviceListMix: split code in smaller methods --- ereuse_devicehub/inventory/views.py | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/ereuse_devicehub/inventory/views.py b/ereuse_devicehub/inventory/views.py index a09f4f5b..795e8266 100644 --- a/ereuse_devicehub/inventory/views.py +++ b/ereuse_devicehub/inventory/views.py @@ -46,11 +46,6 @@ class DeviceListMix(GenericMixView): form_filter = FilterForm(lots, lot_id) devices = form_filter.search() lot = None - tags = ( - Tag.query.filter(Tag.owner_id == current_user.id) - .filter(Tag.device_id.is_(None)) - .order_by(Tag.id.asc()) - ) if lot_id: lot = lots.filter(Lot.id == lot_id).one() @@ -67,10 +62,6 @@ class DeviceListMix(GenericMixView): form_new_allocate = AllocateForm() form_new_datawipe = DataWipeForm() form_new_trade = '' - action_devices = form_new_action.devices.data - list_devices = [] - if action_devices: - list_devices.extend([int(x) for x in action_devices.split(",")]) self.context.update( { @@ -83,13 +74,27 @@ class DeviceListMix(GenericMixView): 'form_filter': form_filter, 'form_print_labels': PrintLabelsForm(), 'lot': lot, - 'tags': tags, - 'list_devices': list_devices, + 'tags': self.get_user_tags(), + 'list_devices': self.get_selected_devices(form_new_action), } ) return self.context + def get_user_tags(self): + return ( + Tag.query.filter(Tag.owner_id == current_user.id) + .filter(Tag.device_id.is_(None)) + .order_by(Tag.id.asc()) + ) + + def get_selected_devices(self, action_form): + """Retrieve selected devices (when action form is submited)""" + action_devices = action_form.devices.data + if action_devices: + return [int(x) for x in action_devices.split(",")] + return [] + class DeviceListView(DeviceListMix): def dispatch_request(self, lot_id=None): From 4ffbeec29d71f7f0adafaf62646498bbed197fe6 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Thu, 12 May 2022 14:23:01 +0200 Subject: [PATCH 06/18] Refactor form initialization --- ereuse_devicehub/inventory/views.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/ereuse_devicehub/inventory/views.py b/ereuse_devicehub/inventory/views.py index 795e8266..92a16ff8 100644 --- a/ereuse_devicehub/inventory/views.py +++ b/ereuse_devicehub/inventory/views.py @@ -49,27 +49,22 @@ class DeviceListMix(GenericMixView): if lot_id: lot = lots.filter(Lot.id == lot_id).one() - form_new_action = NewActionForm(lot=lot.id) - form_new_allocate = AllocateForm(lot=lot.id) - form_new_datawipe = DataWipeForm(lot=lot.id) form_new_trade = TradeForm( lot=lot.id, user_to=g.user.email, user_from=g.user.email, ) else: - form_new_action = NewActionForm() - form_new_allocate = AllocateForm() - form_new_datawipe = DataWipeForm() form_new_trade = '' + form_new_action = NewActionForm(lot=lot_id) self.context.update( { 'devices': devices, 'form_tag_device': TagDeviceForm(), 'form_new_action': form_new_action, - 'form_new_allocate': form_new_allocate, - 'form_new_datawipe': form_new_datawipe, + 'form_new_allocate': AllocateForm(lot=lot_id), + 'form_new_datawipe': DataWipeForm(lot=lot_id), 'form_new_trade': form_new_trade, 'form_filter': form_filter, 'form_print_labels': PrintLabelsForm(), From 9e779d279c7abfba6cb2b4cdedae8182dc7fa242 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Thu, 12 May 2022 14:42:55 +0200 Subject: [PATCH 07/18] Allow retrieving all devices of a user --- ereuse_devicehub/inventory/forms.py | 7 ++++--- ereuse_devicehub/inventory/views.py | 8 +++++--- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/ereuse_devicehub/inventory/forms.py b/ereuse_devicehub/inventory/forms.py index 062d185c..fffefa39 100644 --- a/ereuse_devicehub/inventory/forms.py +++ b/ereuse_devicehub/inventory/forms.py @@ -133,6 +133,7 @@ class FilterForm(FlaskForm): super().__init__(*args, **kwargs) self.lots = lots self.lot_id = lot_id + self.unassigned = kwargs.pop('unassigned', False) self._get_types() def _get_types(self): @@ -148,9 +149,9 @@ class FilterForm(FlaskForm): device_ids = (d.id for d in self.lot.devices) self.devices = Device.query.filter(Device.id.in_(device_ids)) else: - self.devices = Device.query.filter(Device.owner_id == g.user.id).filter_by( - lots=None - ) + self.devices = Device.query.filter(Device.owner_id == g.user.id) + if self.unassigned: + self.devices = self.devices.filter_by(lots=None) def search(self): self.filter_from_lots() diff --git a/ereuse_devicehub/inventory/views.py b/ereuse_devicehub/inventory/views.py index 92a16ff8..e11e9d2c 100644 --- a/ereuse_devicehub/inventory/views.py +++ b/ereuse_devicehub/inventory/views.py @@ -40,10 +40,10 @@ logger = logging.getLogger(__name__) class DeviceListMix(GenericMixView): template_name = 'inventory/device_list.html' - def get_context(self, lot_id): + def get_context(self, lot_id, unassigned=False): super().get_context() lots = self.context['lots'] - form_filter = FilterForm(lots, lot_id) + form_filter = FilterForm(lots, lot_id, unassigned=unassigned) devices = form_filter.search() lot = None @@ -71,6 +71,7 @@ class DeviceListMix(GenericMixView): 'lot': lot, 'tags': self.get_user_tags(), 'list_devices': self.get_selected_devices(form_new_action), + 'unassigned_devices': unassigned, } ) @@ -93,7 +94,8 @@ class DeviceListMix(GenericMixView): class DeviceListView(DeviceListMix): def dispatch_request(self, lot_id=None): - self.get_context(lot_id) + unassigned = request.args.get('unassigned', False) + self.get_context(lot_id, unassigned) return flask.render_template(self.template_name, **self.context) From 290c260511968df70ddd8721f71feae3cb05d41b Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Thu, 12 May 2022 14:43:41 +0200 Subject: [PATCH 08/18] Update breadcrum: All devices VS Unassigned --- ereuse_devicehub/templates/inventory/device_list.html | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ereuse_devicehub/templates/inventory/device_list.html b/ereuse_devicehub/templates/inventory/device_list.html index a3c13576..1c129d97 100644 --- a/ereuse_devicehub/templates/inventory/device_list.html +++ b/ereuse_devicehub/templates/inventory/device_list.html @@ -7,7 +7,11 @@
    -
    - -
    -

    Download the settings for register devices and erase disks. This is less safe and more fast.

    -
    -
    -
    - -
    -

    Download the settings for register devices and erase disks. This is more safe and more slow.

    -
    -
    diff --git a/ereuse_devicehub/templates/workbench/wbSettings.ini b/ereuse_devicehub/templates/workbench/wbSettings.ini index ea45e547..8ce2cf40 100644 --- a/ereuse_devicehub/templates/workbench/wbSettings.ini +++ b/ereuse_devicehub/templates/workbench/wbSettings.ini @@ -1,18 +1,4 @@ [settings] -DH_TOKEN = {{token}} - -DH_HOST = {{host}} -DH_DATABASE = {{inventory}} -DEVICEHUB_URL = https://${DB_HOST}/${DB_DATABASE}/ - - -WB_BENCHMARK = {{ benchmark }} -WB_STRESS_TEST = {{ stress_test }} -WB_SMART_TEST = short - -WB_ERASE = {{ erase }} -WB_ERASE_STEPS = {{ steps }} -WB_ERASE_LEADING_ZEROS = {{ leading_zeros }} - -WB_DEBUG = True +TOKEN = {{ token }} +URL = {{ url }} diff --git a/ereuse_devicehub/workbench/views.py b/ereuse_devicehub/workbench/views.py index ccbdbdc5..ef0c5f8b 100644 --- a/ereuse_devicehub/workbench/views.py +++ b/ereuse_devicehub/workbench/views.py @@ -35,36 +35,18 @@ class SettingsView(GenericMixView): return flask.render_template(self.template_name, **self.context) def download(self): + url = "https://{}/api/".format(app.config['HOST']) self.wbContext = { 'token': self.get_token(), - 'host': app.config['HOST'], - 'inventory': app.config['SCHEMA'], - 'benchmark': False, - 'stress_test': 1, - 'erase': '', - 'steps': 0, - 'leading_zeros': False, + 'url': url, } - options = {"register": self.register, "soft": self.soft, "hard": self.hard} + options = {"register": self.register} return options[self.opt]() def register(self): data = flask.render_template('workbench/wbSettings.ini', **self.wbContext) return self.response_download(data) - def soft(self): - self.wbContext['erase'] = 'EraseBasic' - self.wbContext['steps'] = 1 - data = flask.render_template('workbench/wbSettings.ini', **self.wbContext) - return self.response_download(data) - - def hard(self): - self.wbContext['erase'] = 'EraseSectors' - self.wbContext['steps'] = 1 - self.wbContext['leading_zeros'] = True - data = flask.render_template('workbench/wbSettings.ini', **self.wbContext) - return self.response_download(data) - def response_download(self, data): bfile = str.encode(data) output = make_response(bfile) From 3a2e0bd61a818642463627c3c2e61f4e80b027b0 Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Thu, 12 May 2022 17:25:02 +0200 Subject: [PATCH 11/18] fixing bugs --- ereuse_devicehub/workbench/views.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ereuse_devicehub/workbench/views.py b/ereuse_devicehub/workbench/views.py index ef0c5f8b..95b8c009 100644 --- a/ereuse_devicehub/workbench/views.py +++ b/ereuse_devicehub/workbench/views.py @@ -29,13 +29,13 @@ class SettingsView(GenericMixView): ) self.opt = request.values.get('opt') - if self.opt in ['register', 'soft', 'hard']: + if self.opt in ['register']: return self.download() return flask.render_template(self.template_name, **self.context) def download(self): - url = "https://{}/api/".format(app.config['HOST']) + url = "https://{}/api/inventory/".format(app.config['HOST']) self.wbContext = { 'token': self.get_token(), 'url': url, From 3c02a5480f557a203de4e7ba5844ee483da11fbe Mon Sep 17 00:00:00 2001 From: Cayo Puigdefabregas Date: Thu, 12 May 2022 17:42:26 +0200 Subject: [PATCH 12/18] fixed test render wbsettings --- tests/test_render_2_0.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/test_render_2_0.py b/tests/test_render_2_0.py index 38dc12cd..083d82ee 100644 --- a/tests/test_render_2_0.py +++ b/tests/test_render_2_0.py @@ -862,7 +862,6 @@ def test_wb_settings_register(user3: UserClientFlask): body, status = user3.get(uri) assert status == '200 OK' - assert "WB_BENCHMARK = False" in body - assert "WB_ERASE = \n" in body - assert "WB_ERASE_STEPS = 0" in body - assert "WB_ERASE_LEADING_ZEROS = False" in body + assert "TOKEN = " in body + assert "URL = https://" in body + assert "/api/inventory/" in body From cea1c2b7175321c09053e803b664dc47dc983d0b Mon Sep 17 00:00:00 2001 From: RubenPX Date: Thu, 12 May 2022 18:44:02 +0200 Subject: [PATCH 13/18] full table replacament --- .../static/js/main_inventory.build.js | 94 +++++++++++++------ ereuse_devicehub/static/js/main_inventory.js | 20 ++-- 2 files changed, 73 insertions(+), 41 deletions(-) diff --git a/ereuse_devicehub/static/js/main_inventory.build.js b/ereuse_devicehub/static/js/main_inventory.build.js index 09006905..a58a8260 100644 --- a/ereuse_devicehub/static/js/main_inventory.build.js +++ b/ereuse_devicehub/static/js/main_inventory.build.js @@ -2,7 +2,7 @@ function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { _classCheckPrivateStaticAccess(receiver, classConstructor); _classCheckPrivateStaticFieldDescriptor(descriptor, "get"); return _classApplyDescriptorGet(receiver, descriptor); } -function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { if (descriptor === undefined) { throw new TypeError(`attempted to ${ action } private static field before its declaration`); } } +function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { if (descriptor === undefined) { throw new TypeError("attempted to " + action + " private static field before its declaration"); } } function _classCheckPrivateStaticAccess(receiver, classConstructor) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } } @@ -100,22 +100,32 @@ window.addEventListener("DOMContentLoaded", () => { const alertInfoDevices = document.getElementById("select-devices-info"); function itemListCheckChanged() { - const listDevices = TableController.getAllDevicesInCurrentPage(); - const isAllChecked = listDevices.map(itm => itm.checked); + alertInfoDevices.innerHTML = "Selected devices: ".concat(TableController.getSelectedDevices().length, "\n ").concat(TableController.getAllDevices().length != TableController.getSelectedDevices().length ? "Select all devices (".concat(TableController.getAllDevices().length, ")") : "Cancel selection"); - if (isAllChecked.every(bool => bool == true)) { - btnSelectAll.checked = true; - btnSelectAll.indeterminate = false; - alertInfoDevices.innerHTML = "Selected devices: ".concat(TableController.getSelectedDevices().length, "\n ").concat(TableController.getAllDevices().length != TableController.getSelectedDevices().length ? "Select all devices (".concat(TableController.getAllDevices().length, ")") : "Cancel selection"); - alertInfoDevices.classList.remove("d-none"); - } else if (isAllChecked.every(bool => bool == false)) { - btnSelectAll.checked = false; - btnSelectAll.indeterminate = false; + if (TableController.getSelectedDevices().length <= 0) { alertInfoDevices.classList.add("d-none"); } else { - btnSelectAll.indeterminate = true; - alertInfoDevices.classList.add("d-none"); + alertInfoDevices.classList.remove("d-none"); } + + if (TableController.getAllDevices().length == TableController.getSelectedDevices().length) { + btnSelectAll.checked = true; + btnSelectAll.indeterminate = false; + } else if (TableController.getAllSelectedDevicesInCurrentPage().length > 0) { + btnSelectAll.indeterminate = true; + } else { + btnSelectAll.checked = false; + btnSelectAll.indeterminate = false; + } + + if (TableController.getAllDevices().length == 0) { + btnSelectAll.checked = false; + btnSelectAll.disabled = true; + } else { + btnSelectAll.disabled = false; + } + + get_device_list(); } TableController.getAllDevices().forEach(item => { @@ -139,6 +149,7 @@ window.addEventListener("DOMContentLoaded", () => { table.on("datatable.page", () => itemListCheckChanged()); table.on("datatable.perpage", () => itemListCheckChanged()); table.on("datatable.update", () => itemListCheckChanged()); + itemListCheckChanged(); }); function deviceSelect() { @@ -327,25 +338,44 @@ async function processSelectedDevices() { const lotID = lot.id; const srcElement = event.srcElement.parentElement.children[0]; const checked = !srcElement.checked; + const { + indeterminate + } = srcElement; const found = this.list.filter(list => list.lot.id == lotID)[0]; if (checked) { if (found && found.type == "Remove") { - found.type = "Add"; + const affectedDevices = found.devices.filter(dev => found.lot.devices.includes(dev.id)); + + if (affectedDevices.length > 0 && found.indeterminate == false) { + // Remove action from list + actions.list = actions.list.filter(x => x.lot.id != found.lot.id); + } else { + found.type = "Add"; + } } else { this.list.push({ type: "Add", lot, - devices: selectedDevices + devices: selectedDevices, + indeterminate }); } } else if (found && found.type == "Add") { - found.type = "Remove"; + const affectedDevices = found.devices.filter(dev => !found.lot.devices.includes(dev.id)); + + if (affectedDevices.length > 0 && found.indeterminate == false) { + // Remove action from list + actions.list = actions.list.filter(x => x.lot.id != found.lot.id); + } else { + found.type = "Remove"; + } } else { this.list.push({ type: "Remove", lot, - devices: selectedDevices + devices: selectedDevices, + indeterminate }); } @@ -430,19 +460,23 @@ async function processSelectedDevices() { const newRequest = await Api.doRequest(window.location); const tmpDiv = document.createElement("div"); tmpDiv.innerHTML = newRequest; - const newTable = Array.from(tmpDiv.querySelectorAll("table.table > tbody > tr .deviceSelect")).map(x => x.attributes["data-device-dhid"].value); // https://github.com/fiduswriter/Simple-DataTables/wiki/rows()#removeselect-arraynumber - - const rowsToRemove = []; - - for (let i = 0; i < table.activeRows.length; i++) { - const row = table.activeRows[i]; - - if (!newTable.includes(row.querySelector("input").attributes["data-device-dhid"].value)) { - rowsToRemove.push(i); - } - } - - table.rows().remove(rowsToRemove); // Restore state of checkbox + const newTable = document.createElement("table"); + newTable.innerHTML = tmpDiv.querySelector("table").innerHTML; + newTable.classList = "table"; + const oldTable = document.querySelector(".dataTable-wrapper"); + oldTable.parentElement.replaceChild(newTable, oldTable); + table = new simpleDatatables.DataTable(newTable, { + perPage: 20 + }); // https://github.com/fiduswriter/Simple-DataTables/wiki/rows()#removeselect-arraynumber + // const rowsToRemove = [] + // for (let i = 0; i < table.activeRows.length; i++) { + // const row = table.activeRows[i]; + // if (!newTable.includes(row.querySelector("input").attributes["data-device-dhid"].value)) { + // rowsToRemove.push(i) + // } + // } + // table.rows().remove(rowsToRemove); + // // Restore state of checkbox const selectAllBTN = document.getElementById("SelectAllBTN"); selectAllBTN.checked = false; diff --git a/ereuse_devicehub/static/js/main_inventory.js b/ereuse_devicehub/static/js/main_inventory.js index bec04232..00b90cd4 100644 --- a/ereuse_devicehub/static/js/main_inventory.js +++ b/ereuse_devicehub/static/js/main_inventory.js @@ -425,19 +425,17 @@ async function processSelectedDevices() { const tmpDiv = document.createElement("div") tmpDiv.innerHTML = newRequest - const newTable = Array.from(tmpDiv.querySelectorAll("table.table > tbody > tr .deviceSelect")).map(x => x.attributes["data-device-dhid"].value) + + const newTable = document.createElement("table") + newTable.innerHTML = tmpDiv.querySelector("table").innerHTML + newTable.classList = "table" - // https://github.com/fiduswriter/Simple-DataTables/wiki/rows()#removeselect-arraynumber - const rowsToRemove = [] - for (let i = 0; i < table.activeRows.length; i++) { - const row = table.activeRows[i]; - if (!newTable.includes(row.querySelector("input").attributes["data-device-dhid"].value)) { - rowsToRemove.push(i) - } - } - table.rows().remove(rowsToRemove); + const oldTable = document.querySelector(".dataTable-wrapper") + oldTable.parentElement.replaceChild(newTable, oldTable) - // Restore state of checkbox + table = new simpleDatatables.DataTable(newTable, {perPage: 20}) + + // // Restore state of checkbox const selectAllBTN = document.getElementById("SelectAllBTN"); selectAllBTN.checked = false; selectAllBTN.indeterminate = false; From 6a408a08c782ea41c4663110866f1753a764dc3d Mon Sep 17 00:00:00 2001 From: RubenPX Date: Thu, 12 May 2022 18:44:26 +0200 Subject: [PATCH 14/18] set const table to var This allow modify variable --- ereuse_devicehub/templates/inventory/device_list.html | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/ereuse_devicehub/templates/inventory/device_list.html b/ereuse_devicehub/templates/inventory/device_list.html index 0f022fd6..84294c48 100644 --- a/ereuse_devicehub/templates/inventory/device_list.html +++ b/ereuse_devicehub/templates/inventory/device_list.html @@ -357,6 +357,14 @@ {{ dev.verbose_name }} + {% if dev.lots | length > 0 %} +
    +
    + {% for lot in dev.lots %} + {{ lot.name }} + {% endfor %} +
    + {% endif %} @@ -430,7 +438,7 @@ From c7e050182885543033ab61129ef73b8f59669519 Mon Sep 17 00:00:00 2001 From: RubenPX Date: Thu, 12 May 2022 18:58:06 +0200 Subject: [PATCH 15/18] add soft init to reassign events --- .../static/js/main_inventory.build.js | 48 +++++++++++-------- ereuse_devicehub/static/js/main_inventory.js | 38 ++++++++++----- 2 files changed, 54 insertions(+), 32 deletions(-) diff --git a/ereuse_devicehub/static/js/main_inventory.build.js b/ereuse_devicehub/static/js/main_inventory.build.js index a58a8260..48ab00a7 100644 --- a/ereuse_devicehub/static/js/main_inventory.build.js +++ b/ereuse_devicehub/static/js/main_inventory.build.js @@ -95,10 +95,27 @@ var _tableRowsPage = { writable: true, value: () => table.pages[table.rows().dt.currentPage - 1] }; -window.addEventListener("DOMContentLoaded", () => { + +const selectorController = action => { const btnSelectAll = document.getElementById("SelectAllBTN"); const alertInfoDevices = document.getElementById("select-devices-info"); + function softInit() { + TableController.getAllDevices().forEach(item => { + item.addEventListener("click", itemListCheckChanged); + }); // https://github.com/fiduswriter/Simple-DataTables/wiki/Events + + table.on("datatable.page", () => itemListCheckChanged()); + table.on("datatable.perpage", () => itemListCheckChanged()); + table.on("datatable.update", () => itemListCheckChanged()); + } + + if (action == "softInit") { + softInit(); + itemListCheckChanged(); + return; + } + function itemListCheckChanged() { alertInfoDevices.innerHTML = "Selected devices: ".concat(TableController.getSelectedDevices().length, "\n ").concat(TableController.getAllDevices().length != TableController.getSelectedDevices().length ? "Select all devices (".concat(TableController.getAllDevices().length, ")") : "Cancel selection"); @@ -128,9 +145,6 @@ window.addEventListener("DOMContentLoaded", () => { get_device_list(); } - TableController.getAllDevices().forEach(item => { - item.addEventListener("click", itemListCheckChanged); - }); btnSelectAll.addEventListener("click", event => { const checkedState = event.target.checked; TableController.getAllDevicesInCurrentPage().forEach(ckeckbox => { @@ -144,13 +158,12 @@ window.addEventListener("DOMContentLoaded", () => { ckeckbox.checked = !checkState; }); itemListCheckChanged(); - }); // https://github.com/fiduswriter/Simple-DataTables/wiki/Events - - table.on("datatable.page", () => itemListCheckChanged()); - table.on("datatable.perpage", () => itemListCheckChanged()); - table.on("datatable.update", () => itemListCheckChanged()); + }); + softInit(); itemListCheckChanged(); -}); +}; + +window.addEventListener("DOMContentLoaded", () => selectorController()); function deviceSelect() { const devices_count = TableController.getSelectedDevices().length; @@ -467,20 +480,13 @@ async function processSelectedDevices() { oldTable.parentElement.replaceChild(newTable, oldTable); table = new simpleDatatables.DataTable(newTable, { perPage: 20 - }); // https://github.com/fiduswriter/Simple-DataTables/wiki/rows()#removeselect-arraynumber - // const rowsToRemove = [] - // for (let i = 0; i < table.activeRows.length; i++) { - // const row = table.activeRows[i]; - // if (!newTable.includes(row.querySelector("input").attributes["data-device-dhid"].value)) { - // rowsToRemove.push(i) - // } - // } - // table.rows().remove(rowsToRemove); - // // Restore state of checkbox + }); // // Restore state of checkbox const selectAllBTN = document.getElementById("SelectAllBTN"); selectAllBTN.checked = false; - selectAllBTN.indeterminate = false; + selectAllBTN.indeterminate = false; // Re-init SelectorController + + selectorController("softInit"); } } diff --git a/ereuse_devicehub/static/js/main_inventory.js b/ereuse_devicehub/static/js/main_inventory.js index 00b90cd4..7a2ecc93 100644 --- a/ereuse_devicehub/static/js/main_inventory.js +++ b/ereuse_devicehub/static/js/main_inventory.js @@ -78,10 +78,28 @@ class TableController { /** * Select all functionality */ -window.addEventListener("DOMContentLoaded", () => { + +const selectorController = (action) => { const btnSelectAll = document.getElementById("SelectAllBTN"); const alertInfoDevices = document.getElementById("select-devices-info"); + function softInit() { + TableController.getAllDevices().forEach(item => { + item.addEventListener("click", itemListCheckChanged); + }) + + // https://github.com/fiduswriter/Simple-DataTables/wiki/Events + table.on("datatable.page", () => itemListCheckChanged()); + table.on("datatable.perpage", () => itemListCheckChanged()); + table.on("datatable.update", () => itemListCheckChanged()); + } + + if (action == "softInit") { + softInit(); + itemListCheckChanged(); + return; + } + function itemListCheckChanged() { alertInfoDevices.innerHTML = `Selected devices: ${TableController.getSelectedDevices().length} ${TableController.getAllDevices().length != TableController.getSelectedDevices().length @@ -114,11 +132,7 @@ window.addEventListener("DOMContentLoaded", () => { get_device_list(); } - - TableController.getAllDevices().forEach(item => { - item.addEventListener("click", itemListCheckChanged); - }) - + btnSelectAll.addEventListener("click", event => { const checkedState = event.target.checked; TableController.getAllDevicesInCurrentPage().forEach(ckeckbox => { ckeckbox.checked = checkedState }); @@ -131,13 +145,12 @@ window.addEventListener("DOMContentLoaded", () => { itemListCheckChanged() }) - // https://github.com/fiduswriter/Simple-DataTables/wiki/Events - table.on("datatable.page", () => itemListCheckChanged()); - table.on("datatable.perpage", () => itemListCheckChanged()); - table.on("datatable.update", () => itemListCheckChanged()); + softInit(); itemListCheckChanged(); -}) +} + +window.addEventListener("DOMContentLoaded", () => selectorController()); function deviceSelect() { const devices_count = TableController.getSelectedDevices().length; @@ -439,6 +452,9 @@ async function processSelectedDevices() { const selectAllBTN = document.getElementById("SelectAllBTN"); selectAllBTN.checked = false; selectAllBTN.indeterminate = false; + + // Re-init SelectorController + selectorController("softInit"); } } From d54f2166dc1ab28915ed83eb5842e235a6ba3140 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Fri, 13 May 2022 10:22:32 +0200 Subject: [PATCH 16/18] Keep unassigned as default option on device list Unassigned devices are the ones that require user attention and also all devices view will generate larger responses and more server load. --- ereuse_devicehub/inventory/forms.py | 4 ++-- ereuse_devicehub/inventory/views.py | 13 ++++++++----- .../templates/ereuse_devicehub/base_site.html | 4 ++-- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/ereuse_devicehub/inventory/forms.py b/ereuse_devicehub/inventory/forms.py index fffefa39..cec788b4 100644 --- a/ereuse_devicehub/inventory/forms.py +++ b/ereuse_devicehub/inventory/forms.py @@ -133,7 +133,7 @@ class FilterForm(FlaskForm): super().__init__(*args, **kwargs) self.lots = lots self.lot_id = lot_id - self.unassigned = kwargs.pop('unassigned', False) + self.only_unassigned = kwargs.pop('only_unassigned', True) self._get_types() def _get_types(self): @@ -150,7 +150,7 @@ class FilterForm(FlaskForm): self.devices = Device.query.filter(Device.id.in_(device_ids)) else: self.devices = Device.query.filter(Device.owner_id == g.user.id) - if self.unassigned: + if self.only_unassigned: self.devices = self.devices.filter_by(lots=None) def search(self): diff --git a/ereuse_devicehub/inventory/views.py b/ereuse_devicehub/inventory/views.py index e11e9d2c..09e61535 100644 --- a/ereuse_devicehub/inventory/views.py +++ b/ereuse_devicehub/inventory/views.py @@ -1,5 +1,6 @@ import csv import logging +from distutils.util import strtobool from io import StringIO import flask @@ -40,10 +41,10 @@ logger = logging.getLogger(__name__) class DeviceListMix(GenericMixView): template_name = 'inventory/device_list.html' - def get_context(self, lot_id, unassigned=False): + def get_context(self, lot_id, only_unassigned=True): super().get_context() lots = self.context['lots'] - form_filter = FilterForm(lots, lot_id, unassigned=unassigned) + form_filter = FilterForm(lots, lot_id, only_unassigned=only_unassigned) devices = form_filter.search() lot = None @@ -71,7 +72,7 @@ class DeviceListMix(GenericMixView): 'lot': lot, 'tags': self.get_user_tags(), 'list_devices': self.get_selected_devices(form_new_action), - 'unassigned_devices': unassigned, + 'unassigned_devices': only_unassigned, } ) @@ -94,8 +95,10 @@ class DeviceListMix(GenericMixView): class DeviceListView(DeviceListMix): def dispatch_request(self, lot_id=None): - unassigned = request.args.get('unassigned', False) - self.get_context(lot_id, unassigned) + only_unassigned = request.args.get( + 'only_unassigned', default=True, type=strtobool + ) + self.get_context(lot_id, only_unassigned) return flask.render_template(self.template_name, **self.context) diff --git a/ereuse_devicehub/templates/ereuse_devicehub/base_site.html b/ereuse_devicehub/templates/ereuse_devicehub/base_site.html index 2f254204..74147824 100644 --- a/ereuse_devicehub/templates/ereuse_devicehub/base_site.html +++ b/ereuse_devicehub/templates/ereuse_devicehub/base_site.html @@ -104,14 +104,14 @@