resolve conflict

This commit is contained in:
Cayo Puigdefabregas 2022-05-09 16:35:44 +02:00
commit 1d51629796
13 changed files with 384 additions and 142 deletions

View File

@ -27,7 +27,8 @@
"strict": "off", "strict": "off",
"class-methods-use-this": "off", "class-methods-use-this": "off",
"eqeqeq": "warn", "eqeqeq": "warn",
"radix": "warn" "radix": "warn",
"max-classes-per-file": ["error", 2]
}, },
"globals": { "globals": {
"API_URLS": true, "API_URLS": true,

View File

@ -1,4 +1,4 @@
#Devicehub # Devicehub
Devicehub is a distributed IT Asset Management System focused in reusing devices, created under the project [eReuse.org](https://www.ereuse.org) Devicehub is a distributed IT Asset Management System focused in reusing devices, created under the project [eReuse.org](https://www.ereuse.org)

View File

@ -9,6 +9,12 @@ dags-with-materialized-paths-using-postgres-ltree/>`_ you have
a low-level technical implementation of how lots and their a low-level technical implementation of how lots and their
relationships are mapped. relationships are mapped.
Getting lots
************
You can get lots list by ``GET /lots/``
There are one optional filter ``type``, only works with this 3 values ``temporary``, ``incoming`` and ``outgoing``
Create lots Create lots
*********** ***********
You create a lot by ``POST /lots/`` a `JSON Lot object <https:// You create a lot by ``POST /lots/`` a `JSON Lot object <https://
@ -28,7 +34,6 @@ And for devices is all the same:
``POST /lots/<parent-lot-id>/devices/?id=<device-id-1>&id=<device-id-2>``; ``POST /lots/<parent-lot-id>/devices/?id=<device-id-1>&id=<device-id-2>``;
idem for removing devices. idem for removing devices.
Sharing lots Sharing lots
************ ************
Sharing a lot means giving certain permissions to users, like reading Sharing a lot means giving certain permissions to users, like reading

View File

@ -252,7 +252,7 @@ class UserClientFlask:
) )
self.headers = headers self.headers = headers
body = next(body).decode("utf-8") body = next(body).decode("utf-8")
assert "Unassgined" in body assert "Unassigned" in body
def get( def get(
self, self,

View File

@ -58,16 +58,30 @@ from ereuse_devicehub.resources.tradedocument.models import TradeDocument
from ereuse_devicehub.resources.user.models import User from ereuse_devicehub.resources.user.models import User
DEVICES = { DEVICES = {
"All": ["All"], "All": ["All Devices", "All Components"],
"Computer": [ "Computer": [
"All Computers",
"Desktop", "Desktop",
"Laptop", "Laptop",
"Server", "Server",
], ],
"Monitor": ["ComputerMonitor", "Monitor", "TelevisionSet", "Projector"], "Monitor": [
"Mobile, tablet & smartphone": ["Mobile", "Tablet", "Smartphone", "Cellphone"], "All Monitors",
"DataStorage": ["HardDrive", "SolidStateDrive"], "ComputerMonitor",
"Monitor",
"TelevisionSet",
"Projector",
],
"Mobile, tablet & smartphone": [
"All Mobile",
"Mobile",
"Tablet",
"Smartphone",
"Cellphone",
],
"DataStorage": ["All DataStorage", "HardDrive", "SolidStateDrive"],
"Accessories & Peripherals": [ "Accessories & Peripherals": [
"All Peripherals",
"GraphicCard", "GraphicCard",
"Motherboard", "Motherboard",
"NetworkAdapter", "NetworkAdapter",
@ -81,26 +95,101 @@ DEVICES = {
], ],
} }
COMPUTERS = ['Desktop', 'Laptop', 'Server', 'Computer']
COMPONENTS = [
'GraphicCard',
'DataStorage',
'HardDrive',
'DataStorage',
'SolidStateDrive',
'Motherboard',
'NetworkAdapter',
'Processor',
'RamModule',
'SoundCard',
'Display',
'Battery',
'Camera',
]
MONITORS = ["ComputerMonitor", "Monitor", "TelevisionSet", "Projector"]
MOBILE = ["Mobile", "Tablet", "Smartphone", "Cellphone"]
DATASTORAGE = ["HardDrive", "SolidStateDrive"]
PERIPHERALS = [
"GraphicCard",
"Motherboard",
"NetworkAdapter",
"Processor",
"RamModule",
"SoundCard",
"Battery",
"Keyboard",
"Mouse",
"MemoryCardReader",
]
class FilterForm(FlaskForm): class FilterForm(FlaskForm):
filter = SelectField( filter = SelectField(
'', choices=DEVICES, default="Computer", render_kw={'class': "form-select"} '', choices=DEVICES, default="All Computers", render_kw={'class': "form-select"}
) )
def __init__(self, *args, **kwargs): def __init__(self, lots, lot_id, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.lots = lots
self.lot_id = lot_id
self._get_types()
def _get_types(self):
types_of_devices = [item for sublist in DEVICES.values() for item in sublist] types_of_devices = [item for sublist in DEVICES.values() for item in sublist]
dev = request.args.get('filter') dev = request.args.get('filter')
self.device = dev if dev in types_of_devices else None self.device_type = dev if dev in types_of_devices else None
if self.device: if self.device_type:
self.filter.data = self.device self.filter.data = self.device_type
def search(self): def search(self):
if self.device: # Filter from lots
return [self.device] if self.lot_id:
self.lot = self.lots.filter(Lot.id == self.lot_id).one()
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
)
return ['Desktop', 'Laptop', 'Server', 'Computer'] filter_type = None
if self.device_type:
filter_type = [self.device_type]
else:
# Case without Filter
filter_type = COMPUTERS
# Generic Filters
if "All Devices" == self.device_type:
filter_type = None
if "All Components" == self.device_type:
filter_type = COMPONENTS
elif "All Monitors" == self.device_type:
filter_type = MONITORS
elif "All Mobile" == self.device_type:
filter_type = MOBILE
elif "All DataStorage" == self.device_type:
filter_type = DATASTORAGE
elif "All Peripherals" == self.device_type:
filter_type = PERIPHERALS
if filter_type:
self.devices = self.devices.filter(Device.type.in_(filter_type))
return self.devices.order_by(Device.updated.desc())
class LotForm(FlaskForm): class LotForm(FlaskForm):

View File

@ -43,8 +43,8 @@ class DeviceListMix(GenericMixView):
def get_context(self, lot_id): def get_context(self, lot_id):
super().get_context() super().get_context()
lots = self.context['lots'] lots = self.context['lots']
form_filter = FilterForm() form_filter = FilterForm(lots, lot_id)
filter_types = form_filter.search() devices = form_filter.search()
lot = None lot = None
tags = ( tags = (
Tag.query.filter(Tag.owner_id == current_user.id) Tag.query.filter(Tag.owner_id == current_user.id)
@ -54,10 +54,6 @@ class DeviceListMix(GenericMixView):
if lot_id: if lot_id:
lot = lots.filter(Lot.id == lot_id).one() lot = lots.filter(Lot.id == lot_id).one()
devices = lot.devices
if "All" not in filter_types:
devices = [dev for dev in lot.devices if dev.type in filter_types]
devices = sorted(devices, key=lambda x: x.updated, reverse=True)
form_new_action = NewActionForm(lot=lot.id) form_new_action = NewActionForm(lot=lot.id)
form_new_allocate = AllocateForm(lot=lot.id) form_new_allocate = AllocateForm(lot=lot.id)
form_new_datawipe = DataWipeForm(lot=lot.id) form_new_datawipe = DataWipeForm(lot=lot.id)
@ -67,20 +63,6 @@ class DeviceListMix(GenericMixView):
user_from=g.user.email, user_from=g.user.email,
) )
else: else:
if "All" in filter_types:
devices = (
Device.query.filter(Device.owner_id == current_user.id)
.filter_by(lots=None)
.order_by(Device.updated.desc())
)
else:
devices = (
Device.query.filter(Device.owner_id == current_user.id)
.filter_by(lots=None)
.filter(Device.type.in_(filter_types))
.order_by(Device.updated.desc())
)
form_new_action = NewActionForm() form_new_action = NewActionForm()
form_new_allocate = AllocateForm() form_new_allocate = AllocateForm()
form_new_datawipe = DataWipeForm() form_new_datawipe = DataWipeForm()

View File

@ -29,6 +29,7 @@ class LotView(View):
""" """
format = EnumField(LotFormat, missing=None) format = EnumField(LotFormat, missing=None)
search = f.Str(missing=None) search = f.Str(missing=None)
type = f.Str(missing=None)
def post(self): def post(self):
l = request.get_json() l = request.get_json()
@ -88,6 +89,7 @@ class LotView(View):
else: else:
query = Lot.query query = Lot.query
query = self.visibility_filter(query) query = self.visibility_filter(query)
query = self.type_filter(query, args)
if args['search']: if args['search']:
query = query.filter(Lot.name.ilike(args['search'] + '%')) query = query.filter(Lot.name.ilike(args['search'] + '%'))
lots = query.paginate(per_page=6 if args['search'] else query.count()) lots = query.paginate(per_page=6 if args['search'] else query.count())
@ -104,6 +106,21 @@ class LotView(View):
Lot.owner_id == g.user.id)) Lot.owner_id == g.user.id))
return query return query
def type_filter(self, query, args):
lot_type = args.get('type')
# temporary
if lot_type == "temporary":
return query.filter(Lot.trade == None)
if lot_type == "incoming":
return query.filter(Lot.trade and Trade.user_to == g.user)
if lot_type == "outgoing":
return query.filter(Lot.trade and Trade.user_from == g.user)
return query
def query(self, args): def query(self, args):
query = Lot.query.distinct() query = Lot.query.distinct()
return query return query

View File

@ -4,7 +4,7 @@ const Api = {
* @returns get lots * @returns get lots
*/ */
async get_lots() { async get_lots() {
const request = await this.doRequest(API_URLS.lots, "GET", null); const request = await this.doRequest(`${API_URLS.lots}?type=temporary`, "GET", null);
if (request != undefined) return request.items; if (request != undefined) return request.items;
throw request; throw request;
}, },

View File

@ -15,7 +15,7 @@
if (all) { if (all) {
return [...document.querySelectorAll(el)] return [...document.querySelectorAll(el)]
} }
return document.querySelector(el) return document.querySelector(el)
} }
@ -215,34 +215,6 @@
}, 200); }, 200);
} }
/**
* Select all functionality
*/
const btnSelectAll = document.getElementById("SelectAllBTN");
const tableListCheckboxes = document.querySelectorAll(".deviceSelect");
function itemListCheckChanged(event) {
const isAllChecked = Array.from(tableListCheckboxes).map(itm => itm.checked);
if (isAllChecked.every(bool => bool == true)) {
btnSelectAll.checked = true;
btnSelectAll.indeterminate = false;
} else if (isAllChecked.every(bool => bool == false)) {
btnSelectAll.checked = false;
btnSelectAll.indeterminate = false;
} else {
btnSelectAll.indeterminate = true;
}
}
tableListCheckboxes.forEach(item => {
item.addEventListener("click", itemListCheckChanged);
})
btnSelectAll.addEventListener("click", event => {
const checkedState = event.target.checked;
tableListCheckboxes.forEach(ckeckbox => {ckeckbox.checked = checkedState});
})
/** /**
* Avoid hide dropdown when user clicked inside * Avoid hide dropdown when user clicked inside
*/ */

View File

@ -17,8 +17,119 @@ $(document).ready(() => {
// $('#selectLot').selectpicker(); // $('#selectLot').selectpicker();
}) })
class TableController {
static #tableRows = () => table.activeRows.length > 0 ? table.activeRows : [];
static #tableRowsPage = () => table.pages[table.rows().dt.currentPage - 1];
/**
* @returns Selected inputs from device list
*/
static getSelectedDevices() {
if (this.#tableRows() == undefined) return [];
return this.#tableRows()
.filter(element => element.querySelector("input").checked)
.map(element => element.querySelector("input"))
}
/**
* @returns Selected inputs in current page from device list
*/
static getAllSelectedDevicesInCurrentPage() {
if (this.#tableRowsPage() == undefined) return [];
return this.#tableRowsPage()
.filter(element => element.querySelector("input").checked)
.map(element => element.querySelector("input"))
}
/**
* @returns All inputs from device list
*/
static getAllDevices() {
if (this.#tableRows() == undefined) return [];
return this.#tableRows()
.map(element => element.querySelector("input"))
}
/**
* @returns All inputs from current page in device list
*/
static getAllDevicesInCurrentPage() {
if (this.#tableRowsPage() == undefined) return [];
return this.#tableRowsPage()
.map(element => element.querySelector("input"))
}
/**
*
* @param {HTMLElement} DOMElements
* @returns Procesed input atributes to an Object class
*/
static ProcessTR(DOMElements) {
return DOMElements.map(element => {
const info = {}
info.checked = element.checked
Object.values(element.attributes).forEach(attrib => { info[attrib.nodeName.replace(/-/g, "_")] = attrib.nodeValue })
return info
})
}
}
/**
* Select all functionality
*/
window.addEventListener("DOMContentLoaded", () => {
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);
if (isAllChecked.every(bool => bool == true)) {
btnSelectAll.checked = true;
btnSelectAll.indeterminate = false;
alertInfoDevices.innerHTML = `Selected devices: ${TableController.getSelectedDevices().length}
${
TableController.getAllDevices().length != TableController.getSelectedDevices().length
? `<a href="#" class="ml-3">Select all devices (${TableController.getAllDevices().length})</a>`
: "<a href=\"#\" class=\"ml-3\">Cancel selection</a>"
}`;
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")
}
}
TableController.getAllDevices().forEach(item => {
item.addEventListener("click", itemListCheckChanged);
})
btnSelectAll.addEventListener("click", event => {
const checkedState = event.target.checked;
TableController.getAllDevicesInCurrentPage().forEach(ckeckbox => { ckeckbox.checked = checkedState });
itemListCheckChanged()
})
alertInfoDevices.addEventListener("click", () => {
const checkState = TableController.getAllDevices().length == TableController.getSelectedDevices().length
TableController.getAllDevices().forEach(ckeckbox => { 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());
})
function deviceSelect() { function deviceSelect() {
const devices_count = $(".deviceSelect").filter(":checked").length; const devices_count = TableController.getSelectedDevices().length;
get_device_list(); get_device_list();
if (devices_count == 0) { if (devices_count == 0) {
$("#addingLotModal .pol").show(); $("#addingLotModal .pol").show();
@ -60,7 +171,7 @@ function deviceSelect() {
} }
function removeLot() { function removeLot() {
const devices = $(".deviceSelect"); const devices = TableController.getAllDevices();
if (devices.length > 0) { if (devices.length > 0) {
$("#btnRemoveLots .text-danger").show(); $("#btnRemoveLots .text-danger").show();
} else { } else {
@ -70,8 +181,8 @@ function removeLot() {
} }
function removeTag() { function removeTag() {
const devices = $(".deviceSelect").filter(":checked"); const devices = TableController.getSelectedDevices();
const devices_id = $.map(devices, (x) => $(x).attr("data")); const devices_id = devices.map(dev => dev.data);
if (devices_id.length == 1) { if (devices_id.length == 1) {
const url = `/inventory/tag/devices/${devices_id[0]}/del/`; const url = `/inventory/tag/devices/${devices_id[0]}/del/`;
window.location.href = url; window.location.href = url;
@ -81,8 +192,8 @@ function removeTag() {
} }
function addTag() { function addTag() {
const devices = $(".deviceSelect").filter(":checked"); const devices = TableController.getSelectedDevices();
const devices_id = $.map(devices, (x) => $(x).attr("data")); const devices_id = devices.map(dev => dev.data);
if (devices_id.length == 1) { if (devices_id.length == 1) {
$("#addingTagModal .pol").hide(); $("#addingTagModal .pol").hide();
$("#addingTagModal .btn-primary").show(); $("#addingTagModal .btn-primary").show();
@ -137,7 +248,7 @@ function newDataWipe(action) {
} }
function get_device_list() { function get_device_list() {
const devices = $(".deviceSelect").filter(":checked"); const devices = TableController.getSelectedDevices();
/* Insert the correct count of devices in actions form */ /* Insert the correct count of devices in actions form */
const devices_count = devices.length; const devices_count = devices.length;
@ -156,14 +267,15 @@ function get_device_list() {
"Desktop": "<i class='bi bi-building'></i>", "Desktop": "<i class='bi bi-building'></i>",
"Laptop": "<i class='bi bi-laptop'></i>", "Laptop": "<i class='bi bi-laptop'></i>",
}; };
list_devices = devices.map((x) => { list_devices = devices.map((x) => {
let typ = $(devices[x]).data("device-type"); let typ = $(x).data("device-type");
const manuf = $(devices[x]).data("device-manufacturer"); const manuf = $(x).data("device-manufacturer");
const dhid = $(devices[x]).data("device-dhid"); const dhid = $(x).data("device-dhid");
if (computer[typ]) { if (computer[typ]) {
typ = computer[typ]; typ = computer[typ];
}; };
return `${typ } ${ manuf } ${ dhid}`; return `${typ} ${manuf} ${dhid}`;
}); });
description = $.map(list_devices, (x) => x).join(", "); description = $.map(list_devices, (x) => x).join(", ");
@ -171,9 +283,9 @@ function get_device_list() {
} }
function export_file(type_file) { function export_file(type_file) {
const devices = $(".deviceSelect").filter(":checked"); const devices = TableController.getSelectedDevices();
const devices_id = $.map(devices, (x) => $(x).attr("data-device-dhid")).join(","); const devices_id = $.map(devices, (x) => $(x).attr("data-device-dhid")).join(",");
if (devices_id){ if (devices_id) {
const url = `/inventory/export/${type_file}/?ids=${devices_id}`; const url = `/inventory/export/${type_file}/?ids=${devices_id}`;
window.location.href = url; window.location.href = url;
} else { } else {
@ -194,40 +306,29 @@ async function processSelectedDevices() {
/** /**
* Manage the actions that will be performed when applying the changes * Manage the actions that will be performed when applying the changes
* @param {*} ev event (Should be a checkbox type) * @param {EventSource} ev event (Should be a checkbox type)
* @param {string} lotID lot id * @param {Lot} lot lot id
* @param {number} deviceID device id * @param {Device[]} selectedDevices device id
*/ */
manage(event, lotID, deviceListID) { manage(event, lot, selectedDevices) {
event.preventDefault(); event.preventDefault();
const lotID = lot.id;
const srcElement = event.srcElement.parentElement.children[0] const srcElement = event.srcElement.parentElement.children[0]
const {indeterminate} = srcElement;
const checked = !srcElement.checked; const checked = !srcElement.checked;
const found = this.list.filter(list => list.lotID == lotID)[0]; const found = this.list.filter(list => list.lot.id == lotID)[0];
const foundIndex = found != undefined ? this.list.findLastIndex(x => x.lotID == found.lotID) : -1;
if (checked) { if (checked) {
if (found != undefined && found.type == "Remove") { if (found && found.type == "Remove") {
if (found.isFromIndeterminate == true) { found.type = "Add";
found.type = "Add";
this.list[foundIndex] = found;
} else {
this.list = this.list.filter(list => list.lotID != lotID);
}
} else { } else {
this.list.push({ type: "Add", lotID, devices: deviceListID, isFromIndeterminate: indeterminate }); this.list.push({ type: "Add", lot, devices: selectedDevices });
}
} else if (found != undefined && found.type == "Add") {
if (found.isFromIndeterminate == true) {
found.type = "Remove";
this.list[foundIndex] = found;
} else {
this.list = this.list.filter(list => list.lotID != lotID);
}
} else {
this.list.push({ type: "Remove", lotID, devices: deviceListID, isFromIndeterminate: indeterminate });
} }
} else if (found && found.type == "Add") {
found.type = "Remove";
} else {
this.list.push({ type: "Remove", lot, devices: selectedDevices });
}
if (this.list.length > 0) { if (this.list.length > 0) {
document.getElementById("ApplyDeviceLots").classList.remove("disabled"); document.getElementById("ApplyDeviceLots").classList.remove("disabled");
@ -244,7 +345,7 @@ async function processSelectedDevices() {
*/ */
notifyUser(title, toastText, isError) { notifyUser(title, toastText, isError) {
const toast = document.createElement("div"); const toast = document.createElement("div");
toast.classList = `alert alert-dismissible fade show ${ isError ? "alert-danger" : "alert-success"}`; toast.classList = `alert alert-dismissible fade show ${isError ? "alert-danger" : "alert-success"}`;
toast.attributes["data-autohide"] = !isError; toast.attributes["data-autohide"] = !isError;
toast.attributes.role = "alert"; toast.attributes.role = "alert";
toast.style = "margin-left: auto; width: fit-content;"; toast.style = "margin-left: auto; width: fit-content;";
@ -268,17 +369,19 @@ async function processSelectedDevices() {
this.list.forEach(async action => { this.list.forEach(async action => {
if (action.type == "Add") { if (action.type == "Add") {
try { try {
await Api.devices_add(action.lotID, action.devices); const devicesIDs = action.devices.filter(dev => !action.lot.devices.includes(dev.id)).map(dev => dev.id)
this.notifyUser("Devices sucefully aded to selected lot/s", "", false); await Api.devices_add(action.lot.id, devicesIDs);
this.notifyUser("Devices sucefully added to selected lot/s", "", false);
} catch (error) { } catch (error) {
this.notifyUser("Failed to add devices to selected lot/s", error.responseJSON.message, true); this.notifyUser("Failed to add devices to selected lot/s", error.responseJSON.message, true);
} }
} else if (action.type == "Remove") { } else if (action.type == "Remove") {
try { try {
await Api.devices_remove(action.lotID, action.devices); const devicesIDs = action.devices.filter(dev => action.lot.devices.includes(dev.id)).map(dev => dev.id)
await Api.devices_remove(action.lot.id, devicesIDs);
this.notifyUser("Devices sucefully removed from selected lot/s", "", false); this.notifyUser("Devices sucefully removed from selected lot/s", "", false);
} catch (error) { } catch (error) {
this.notifyUser("Fail to remove devices from selected lot/s", error.responseJSON.message, true); this.notifyUser("Failed to remove devices from selected lot/s", error.responseJSON.message, true);
} }
} }
requestCount += 1 requestCount += 1
@ -287,6 +390,7 @@ async function processSelectedDevices() {
this.list = []; this.list = [];
} }
}) })
$("#confirmLotsModal").modal("hide"); // Hide dialog when click "Save changes"
document.getElementById("dropDownLotsSelector").classList.remove("show"); document.getElementById("dropDownLotsSelector").classList.remove("show");
} }
@ -299,15 +403,22 @@ async function processSelectedDevices() {
const tmpDiv = document.createElement("div") const tmpDiv = document.createElement("div")
tmpDiv.innerHTML = newRequest tmpDiv.innerHTML = newRequest
const oldTable = Array.from(document.querySelectorAll("table.table > tbody > tr .deviceSelect")).map(x => x.attributes["data-device-dhid"].value)
const newTable = Array.from(tmpDiv.querySelectorAll("table.table > tbody > tr .deviceSelect")).map(x => x.attributes["data-device-dhid"].value) const newTable = Array.from(tmpDiv.querySelectorAll("table.table > tbody > tr .deviceSelect")).map(x => x.attributes["data-device-dhid"].value)
for (let i = 0; i < oldTable.length; i++) { // https://github.com/fiduswriter/Simple-DataTables/wiki/rows()#removeselect-arraynumber
if (!newTable.includes(oldTable[i])) { const rowsToRemove = []
// variable from device_list.html --> See: ereuse_devicehub\templates\inventory\device_list.html (Ln: 411) for (let i = 0; i < table.activeRows.length; i++) {
table.rows().remove(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;
selectAllBTN.indeterminate = false;
} }
} }
@ -315,14 +426,14 @@ async function processSelectedDevices() {
/** /**
* Generates a list item with a correspondient checkbox state * Generates a list item with a correspondient checkbox state
* @param {String} lotID * @param {Object} lot Lot model server
* @param {String} lotName * @param {Device[]} selectedDevices list selected devices
* @param {Array<number>} selectedDevicesIDs * @param {HTMLElement} elementTarget
* @param {HTMLElement} target * @param {Action[]} actions
*/ */
function templateLot(lot, elementTarget, actions) { function templateLot(lot, selectedDevices, elementTarget, actions) {
elementTarget.innerHTML = "" elementTarget.innerHTML = ""
const {id, name, state} = lot; const { id, name, state } = lot;
const htmlTemplate = `<input class="form-check-input" type="checkbox" id="${id}" style="width: 20px; height: 20px; margin-right: 7px;"> const htmlTemplate = `<input class="form-check-input" type="checkbox" id="${id}" style="width: 20px; height: 20px; margin-right: 7px;">
<label class="form-check-label" for="${id}">${name}</label>`; <label class="form-check-label" for="${id}">${name}</label>`;
@ -345,16 +456,17 @@ async function processSelectedDevices() {
break; break;
} }
doc.children[0].addEventListener("mouseup", (ev) => actions.manage(ev, id, selectedDevicesIDs)); doc.children[0].addEventListener("mouseup", (ev) => actions.manage(ev, lot, selectedDevices));
doc.children[1].addEventListener("mouseup", (ev) => actions.manage(ev, id, selectedDevicesIDs)); doc.children[1].addEventListener("mouseup", (ev) => actions.manage(ev, lot, selectedDevices));
elementTarget.append(doc); elementTarget.append(doc);
} }
const listHTML = $("#LotsSelector") const listHTML = $("#LotsSelector")
// Get selected devices // Get selected devices
const selectedDevicesIDs = $.map($(".deviceSelect").filter(":checked"), (x) => parseInt($(x).attr("data"))); const selectedDevicesID = TableController.ProcessTR(TableController.getSelectedDevices()).map(item => item.data)
if (selectedDevicesIDs.length <= 0) {
if (selectedDevicesID.length <= 0) {
listHTML.html("<li style=\"color: red; text-align: center\">No devices selected</li>"); listHTML.html("<li style=\"color: red; text-align: center\">No devices selected</li>");
return; return;
} }
@ -364,24 +476,65 @@ async function processSelectedDevices() {
if (eventClickActions) { if (eventClickActions) {
document.getElementById("ApplyDeviceLots").removeEventListener(eventClickActions); document.getElementById("ApplyDeviceLots").removeEventListener(eventClickActions);
} }
eventClickActions = document.getElementById("ApplyDeviceLots").addEventListener("click", () => actions.doActions());
eventClickActions = document.getElementById("ApplyDeviceLots").addEventListener("click", () => {
const modal = $("#confirmLotsModal")
modal.modal({ keyboard: false })
let list_changes_html = "";
// {type: ["Remove" | "Add"], "LotID": string, "devices": number[]}
actions.list.forEach(action => {
let type;
let devices;
if (action.type == "Add") {
type = "success";
devices = action.devices.filter(dev => !action.lot.devices.includes(dev.id)) // Only show affected devices
} else {
type = "danger";
devices = action.devices.filter(dev => action.lot.devices.includes(dev.id)) // Only show affected devices
}
list_changes_html += `
<div class="card border-primary mb-3 w-100">
<div class="card-header" title="${action.lotID}">${action.lot.name}</div>
<div class="card-body pt-3">
<p class="card-text">
${devices.map(item => {
const name = `${item.type} ${item.manufacturer} ${item.model}`
return `<span class="badge bg-${type}" title="${name}">${item.devicehubID}</span>`;
}).join(" ")}
</p>
</div>
</div>`;
})
modal.find(".modal-body").html(list_changes_html)
const el = document.getElementById("SaveAllActions")
const elClone = el.cloneNode(true);
el.parentNode.replaceChild(elClone, el);
elClone.addEventListener("click", () => actions.doActions())
modal.modal("show")
// actions.doActions();
});
document.getElementById("ApplyDeviceLots").classList.add("disabled"); document.getElementById("ApplyDeviceLots").classList.add("disabled");
try { try {
listHTML.html("<li style=\"text-align: center\"><div class=\"spinner-border text-info\" style=\"margin: auto\" role=\"status\"></div></li>") listHTML.html("<li style=\"text-align: center\"><div class=\"spinner-border text-info\" style=\"margin: auto\" role=\"status\"></div></li>")
const devices = await Api.get_devices(selectedDevicesIDs); const selectedDevices = await Api.get_devices(selectedDevicesID);
let lots = await Api.get_lots(); let lots = await Api.get_lots();
lots = lots.map(lot => { lots = lots.map(lot => {
lot.devices = devices lot.devices = selectedDevices
.filter(device => device.lots.filter(devicelot => devicelot.id == lot.id).length > 0) .filter(device => device.lots.filter(devicelot => devicelot.id == lot.id).length > 0)
.map(device => parseInt(device.id)); .map(device => parseInt(device.id));
switch (lot.devices.length) { switch (lot.devices.length) {
case 0: case 0:
lot.state = "false"; lot.state = "false";
break; break;
case selectedDevicesIDs.length: case selectedDevicesID.length:
lot.state = "true"; lot.state = "true";
break; break;
default: default:
@ -392,15 +545,14 @@ async function processSelectedDevices() {
return lot; return lot;
}) })
let lotsList = []; let lotsList = [];
lotsList.push(lots.filter(lot => lot.state == "true").sort((a,b) => a.name.localeCompare(b.name))); lotsList.push(lots.filter(lot => lot.state == "true").sort((a, b) => a.name.localeCompare(b.name)));
lotsList.push(lots.filter(lot => lot.state == "indetermined").sort((a,b) => a.name.localeCompare(b.name))); lotsList.push(lots.filter(lot => lot.state == "indetermined").sort((a, b) => a.name.localeCompare(b.name)));
lotsList.push(lots.filter(lot => lot.state == "false").sort((a,b) => a.name.localeCompare(b.name))); lotsList.push(lots.filter(lot => lot.state == "false").sort((a, b) => a.name.localeCompare(b.name)));
lotsList = lotsList.flat(); // flat array lotsList = lotsList.flat(); // flat array
listHTML.html(""); listHTML.html("");
lotsList.forEach(lot => templateLot(lot, listHTML, actions)); lotsList.forEach(lot => templateLot(lot, selectedDevices, listHTML, actions));
} catch (error) { } catch (error) {
console.log(error); console.log(error);
listHTML.html("<li style=\"color: red; text-align: center\">Error feching devices and lots<br>(see console for more details)</li>"); listHTML.html("<li style=\"color: red; text-align: center\">Error feching devices and lots<br>(see console for more details)</li>");

View File

@ -0,0 +1,19 @@
<!-- Modal -->
<div class="modal fade" id="confirmLotsModal" tabindex="-1" role="dialog" aria-labelledby="confirmLotsModal"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Confirm lots changes</h5>
</div>
<div class="modal-body">
IF THIS TEXT APEARS THERE HAS AN ERROR
</div>
<div class="modal-footer">
<button type="button" onclick="$('#confirmLotsModal').modal('hide');" class="btn btn-secondary"
style="margin-right: auto;" data-dismiss="#confirmLotsModal">Cancel</button>
<button type="button" class="btn btn-primary" id="SaveAllActions">Save changes</button>
</div>
</div>
</div>
</div>

View File

@ -7,7 +7,7 @@
<ol class="breadcrumb"> <ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{{ url_for('inventory.devicelist')}}">Inventory</a></li> <li class="breadcrumb-item"><a href="{{ url_for('inventory.devicelist')}}">Inventory</a></li>
{% if not lot %} {% if not lot %}
<li class="breadcrumb-item active">Unassgined</li> <li class="breadcrumb-item active">Unassigned</li>
{% elif lot.is_temporary %} {% elif lot.is_temporary %}
<li class="breadcrumb-item active">Temporary Lot</li> <li class="breadcrumb-item active">Temporary Lot</li>
<li class="breadcrumb-item active">{{ lot.name }}</li> <li class="breadcrumb-item active">{{ lot.name }}</li>
@ -308,6 +308,10 @@
</div> </div>
{% endif %} {% endif %}
<div id="select-devices-info" class="alert alert-info mb-0 mt-3 d-none" role="alert">
If this text is showing is because there are an error
</div>
<div class="tab-content pt-2"> <div class="tab-content pt-2">
<form method="get"> <form method="get">
<div class="d-flex mt-4 mb-4"> <div class="d-flex mt-4 mb-4">
@ -340,7 +344,7 @@
<td> <td>
<input type="checkbox" class="deviceSelect" data="{{ dev.id }}" <input type="checkbox" class="deviceSelect" data="{{ dev.id }}"
data-device-type="{{ dev.type }}" data-device-manufacturer="{{ dev.manufacturer }}" data-device-type="{{ dev.type }}" data-device-manufacturer="{{ dev.manufacturer }}"
data-device-dhid="{{ dev.devicehub_id }}" data-device-dhid="{{ dev.devicehub_id }}" data-device-vname="{{ dev.verbose_name }}"
{% if form_new_allocate.type.data and dev.id in list_devices %} {% if form_new_allocate.type.data and dev.id in list_devices %}
checked="checked" checked="checked"
{% endif %} {% endif %}
@ -365,7 +369,7 @@
{% if not loop.last %},{% endif %} {% if not loop.last %},{% endif %}
{% endfor %} {% endfor %}
</td> </td>
<td>{% if dev.status %}{{ dev.status }}{% endif %}</td> <td>{% if dev.status %}{{ dev.status.type }}{% endif %}</td>
<td>{{ dev.updated.strftime('%H:%M %d-%m-%Y') }}</td> <td>{{ dev.updated.strftime('%H:%M %d-%m-%Y') }}</td>
</tr> </tr>
{% endfor %} {% endfor %}
@ -422,6 +426,7 @@
{% include "inventory/trade.html" %} {% include "inventory/trade.html" %}
{% include "inventory/alert_export_error.html" %} {% include "inventory/alert_export_error.html" %}
{% include "inventory/alert_unlink_tag_error.html" %} {% include "inventory/alert_unlink_tag_error.html" %}
{% include "inventory/alert_lots_changes.html" %}
<!-- Custom Code --> <!-- Custom Code -->
<script> <script>

View File

@ -72,7 +72,7 @@ def test_inventory(user3: UserClientFlask):
body, status = user3.get('/inventory/device/') body, status = user3.get('/inventory/device/')
assert status == '200 OK' assert status == '200 OK'
assert "Unassgined" in body assert "Unassigned" in body
@pytest.mark.mvp @pytest.mark.mvp
@ -184,7 +184,7 @@ def test_inventory_with_device(user3: UserClientFlask):
body, status = user3.get('/inventory/device/') body, status = user3.get('/inventory/device/')
assert status == '200 OK' assert status == '200 OK'
assert "Unassgined" in body assert "Unassigned" in body
assert db_snapthot.device.devicehub_id in body assert db_snapthot.device.devicehub_id in body
@ -197,7 +197,7 @@ def test_inventory_filter(user3: UserClientFlask):
body, status = user3.get(f'/inventory/device/?filter=Laptop&csrf_token={csrf}') body, status = user3.get(f'/inventory/device/?filter=Laptop&csrf_token={csrf}')
assert status == '200 OK' assert status == '200 OK'
assert "Unassgined" in body assert "Unassigned" in body
assert db_snapthot.device.devicehub_id in body assert db_snapthot.device.devicehub_id in body