diff --git a/ereuse_devicehub/inventory/forms.py b/ereuse_devicehub/inventory/forms.py index 0357e19f..bc26f600 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.only_unassigned = kwargs.pop('only_unassigned', True) 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.only_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 70c058a4..5ed4247a 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,60 +41,64 @@ 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, only_unassigned=True): super().get_context() lots = self.context['lots'] - form_filter = FilterForm(lots, lot_id) + form_filter = FilterForm(lots, lot_id, only_unassigned=only_unassigned) 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() - 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 = '' - action_devices = form_new_action.devices.data - list_devices = [] - if action_devices: - list_devices.extend([int(x) for x in action_devices.split(",")]) + 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(), 'lot': lot, - 'tags': tags, - 'list_devices': list_devices, + 'tags': self.get_user_tags(), + 'list_devices': self.get_selected_devices(form_new_action), + 'unassigned_devices': only_unassigned, } ) 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): - self.get_context(lot_id) + 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/static/js/main_inventory.build.js b/ereuse_devicehub/static/js/main_inventory.build.js index 09006905..48ab00a7 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"); } } @@ -95,32 +95,56 @@ 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 itemListCheckChanged() { - const listDevices = TableController.getAllDevicesInCurrentPage(); - const isAllChecked = listDevices.map(itm => itm.checked); + function softInit() { + TableController.getAllDevices().forEach(item => { + item.addEventListener("click", itemListCheckChanged); + }); // https://github.com/fiduswriter/Simple-DataTables/wiki/Events - 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; - alertInfoDevices.classList.add("d-none"); - } else { - btnSelectAll.indeterminate = true; - alertInfoDevices.classList.add("d-none"); - } + 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"); + + if (TableController.getSelectedDevices().length <= 0) { + alertInfoDevices.classList.add("d-none"); + } else { + 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 => { - item.addEventListener("click", itemListCheckChanged); - }); btnSelectAll.addEventListener("click", event => { const checkedState = event.target.checked; TableController.getAllDevicesInCurrentPage().forEach(ckeckbox => { @@ -134,12 +158,12 @@ window.addEventListener("DOMContentLoaded", () => { ckeckbox.checked = !checkState; }); itemListCheckChanged(); - }); // https://github.com/fiduswriter/Simple-DataTables/wiki/Events + }); + softInit(); + itemListCheckChanged(); +}; - table.on("datatable.page", () => itemListCheckChanged()); - table.on("datatable.perpage", () => itemListCheckChanged()); - table.on("datatable.update", () => itemListCheckChanged()); -}); +window.addEventListener("DOMContentLoaded", () => selectorController()); function deviceSelect() { const devices_count = TableController.getSelectedDevices().length; @@ -327,25 +351,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,23 +473,20 @@ 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 + }); // // 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 bec04232..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; @@ -425,22 +438,23 @@ 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; + + // Re-init SelectorController + selectorController("softInit"); } } diff --git a/ereuse_devicehub/templates/ereuse_devicehub/base_site.html b/ereuse_devicehub/templates/ereuse_devicehub/base_site.html index fe014107..acf6efa2 100644 --- a/ereuse_devicehub/templates/ereuse_devicehub/base_site.html +++ b/ereuse_devicehub/templates/ereuse_devicehub/base_site.html @@ -64,6 +64,16 @@