update all storagelocation / unit routes to support new tables (AFLOW-23)

This commit is contained in:
Sören Oesterwind 2023-07-10 15:34:04 +02:00
parent a79a1eab81
commit 1605987952
5 changed files with 189 additions and 84 deletions

View File

@ -72,7 +72,7 @@ export function parseIntRelation(data: string, relation_name: string = 'id', doN
// This can be used by prisma to connect relations // This can be used by prisma to connect relations
// If the incoming data is null or empty, return a prisma disconnect object instead of a connect one // If the incoming data is null or empty, return a prisma disconnect object instead of a connect one
if (data === null || data === '') { if (data === null || data === '' || data === "undefined") {
if (doNotDisconnect) { if (doNotDisconnect) {
return undefined; return undefined;
} }

View File

@ -150,37 +150,16 @@
> >
</div> </div>
</div> </div>
<table class="table align-middle"> <table class="table align-middle" id="itemList" data-sortable="true" data-search-highlight="true" data-pagination="true" data-page-size="25" data-remember-order="true">
<thead> <thead>
<tr> <tr>
<th scope="col">Name</th> <th scope="col" data-field="name" data-sortable="true">Name</th>
<th scope="col">Storage Unit</th> <th scope="col" data-field="storageUnit" data-sortable="true">Storage Unit</th>
<th scope="col">Actions</th> <th scope="col" data-field="actions" data-sortable="false" data-searchable="false" data-width="160">Actions</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<% it.storLocs.forEach(function(locations){ %>
<tr id="listEntry-<%= locations.id %>">
<td scope="row" data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="ID: <%= locations.id %>"><%= locations.name %></td>
<td>
<% if (locations.storageUnit == null) { %>
<i>No storage unit connected</i>
<% } else { %> <%= locations.storageUnit.name %> <% } %>
</td>
<td>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#storageLocationModal" onclick="primeEdit(); getDataForEditLoc('<%= locations.id %>')">
<i class="bi bi-pencil"></i>
</button>
<button
class="btn btn-danger"
onclick="preFillDeleteModalNxt('<%= locations.id %>','storageLocations','Storage Location')"
data-bs-toggle="modal"
data-bs-target="#staticBackdrop">
<i class="bi bi-trash"></i>
</button>
</td>
</tr>
<% }) %>
</tbody> </tbody>
</table> </table>
</div> </div>
@ -195,29 +174,15 @@
<a class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#storageUnitModal" onclick="primeCreateNew()"><i class="bi bi-building-add"></i> Create new unit</a> <a class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#storageUnitModal" onclick="primeCreateNew()"><i class="bi bi-building-add"></i> Create new unit</a>
</div> </div>
</div> </div>
<table class="table align-middle"> <table class="table align-middle" id="itemListUnit" data-sortable="true" data-search-highlight="true" data-pagination="true" data-page-size="25" data-remember-order="true">
<thead> <thead>
<tr> <tr>
<th scope="col">Name</th> <th scope="col" data-field="name" data-sortable="true">Name</th>
<th scope="col">Address</th> <th scope="col "data-field="address" data-sortable="true">Address</th>
<th scope="col">Actions</th> <th scope="col" data-field="actions" data-searchable="false" data-width="160">Actions</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<% it.storUnits.forEach(function(units){ %>
<tr id="listEntry-<%= units.id %>">
<td scope="row" data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="ID: <%= units.id %>"><%= units.name %></td>
<td><%= units.contactInfo.street %> <%= units.contactInfo.houseNumber %>, <%= units.contactInfo.city %> <%= units.contactInfo.country %></td>
<td>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#storageUnitModal" onclick="primeEdit(); getDataForEdit('<%= units.id %>')">
<i class="bi bi-pencil"></i>
</button>
<button class="btn btn-danger" onclick="preFillDeleteModalNxt('<%= units.id %>', 'storageUnits', 'Storage Unit')" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
<i class="bi bi-trash"></i>
</button>
</td>
</tr>
<% }) %>
</tbody> </tbody>
</table> </table>
</div> </div>

View File

@ -1,9 +1,19 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
import { prisma, __path, log } from '../../../index.js'; import { prisma, __path, log } from '../../../index.js';
import { parseIntOrUndefined } from '../../../assets/helper.js'; import { parseIntOrUndefined, parseDynamicSortBy, parseIntRelation } from '../../../assets/helper.js';
// Get storageLocation. // Get storageLocation.
function get(req: Request, res: Response) { async function get(req: Request, res: Response) {
if (req.query.sort === undefined) {
req.query.sort = 'id';
}
if (req.query.order === undefined) {
req.query.order = 'asc';
}
if (req.query.search === undefined) {
req.query.search = '';
}
if (req.query.getAll === undefined) { if (req.query.getAll === undefined) {
// Check if required fields are present. // Check if required fields are present.
if (!req.query.id) { if (!req.query.id) {
@ -32,16 +42,39 @@ function get(req: Request, res: Response) {
res.status(500).json({ status: 'ERROR', errorcode: 'DB_ERROR', error: err, message: 'An error occurred during the database operation' }); res.status(500).json({ status: 'ERROR', errorcode: 'DB_ERROR', error: err, message: 'An error occurred during the database operation' });
}); });
} else { } else {
// Get all items
const itemCountNotFiltered = await prisma.storageLocation.count({});
// Get all items (filtered)
const itemCountFiltered = await prisma.storageLocation.count({
where: {
name: {
// @ts-ignore
contains: req.query.search.length > 0 ? req.query.search : ''
}
},
orderBy: parseDynamicSortBy(req.query.sort.toString(), req.query.order.toString())
});
prisma.storageLocation prisma.storageLocation
.findMany({ .findMany({
take: parseIntOrUndefined(req.query.limit),
skip: parseIntOrUndefined(req.query.offset),
where: {
name: {
// @ts-ignore
contains: req.query.search.length > 0 ? req.query.search : ''
}
},
// Get storageUnit from relation. // Get storageUnit from relation.
include: { include: {
storageUnit: true storageUnit: true
} },
orderBy: parseDynamicSortBy(req.query.sort.toString(), req.query.order.toString()),
}) })
.then((items) => { .then((items) => {
if (items) { if (items) {
res.status(200).json(items); res.status(200).json({ total: itemCountFiltered, totalNotFiltered: itemCountNotFiltered, items: items });
} else { } else {
res.status(410).json({ status: 'ERROR', errorcode: 'NOT_EXISTING', message: 'storageLocation does not exist' }); res.status(410).json({ status: 'ERROR', errorcode: 'NOT_EXISTING', message: 'storageLocation does not exist' });
} }
@ -124,7 +157,7 @@ async function patch(req: Request, res: Response) {
}, },
data: { data: {
name: req.body.name, name: req.body.name,
storageUnitId: parseIntOrUndefined(req.body.storageUnitId) storageUnit: parseIntRelation(req.body.storageUnitId)
}, },
select: { select: {
id: true id: true

View File

@ -1,9 +1,19 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
import { prisma, __path, log } from '../../../index.js'; import { prisma, __path, log } from '../../../index.js';
import { contactType } from '@prisma/client'; import { contactType } from '@prisma/client';
import { parseDynamicSortBy, parseIntOrUndefined } from '../../../assets/helper.js';
// Get storageUnit. // Get storageUnit.
function get(req: Request, res: Response) { async function get(req: Request, res: Response) {
if (req.query.sort === undefined) {
req.query.sort = 'id';
}
if (req.query.order === undefined) {
req.query.order = 'asc';
}
if (req.query.search === undefined) {
req.query.search = '';
}
if (req.query.getAll === undefined) { if (req.query.getAll === undefined) {
// Check if required fields are present. // Check if required fields are present.
if (!req.query.id) { if (!req.query.id) {
@ -33,17 +43,40 @@ function get(req: Request, res: Response) {
res.status(500).json({ status: 'ERROR', errorcode: 'DB_ERROR', error: err, message: 'An error occurred during the database operation' }); res.status(500).json({ status: 'ERROR', errorcode: 'DB_ERROR', error: err, message: 'An error occurred during the database operation' });
}); });
} else { } else {
// Get all items
const itemCountNotFiltered = await prisma.storageUnit.count({});
// Get all items (filtered)
const itemCountFiltered = await prisma.storageUnit.count({
where: {
name: {
// @ts-ignore
contains: req.query.search.length > 0 ? req.query.search : ''
}
},
orderBy: parseDynamicSortBy(req.query.sort.toString(), req.query.order.toString())
});
prisma.storageUnit prisma.storageUnit
.findMany({ .findMany({
take: parseIntOrUndefined(req.query.limit),
skip: parseIntOrUndefined(req.query.offset),
// Get contactInfo and StorageLocation from relation. // Get contactInfo and StorageLocation from relation.
include: { include: {
contactInfo: true, contactInfo: true,
StorageLocation: true StorageLocation: true
} },
where: {
name: {
// @ts-ignore
contains: req.query.search.length > 0 ? req.query.search : ''
}
},
orderBy: parseDynamicSortBy(req.query.sort.toString(), req.query.order.toString())
}) })
.then((items) => { .then((items) => {
if (items) { if (items) {
res.status(200).json(items); res.status(200).json({ total: itemCountFiltered, totalNotFiltered: itemCountNotFiltered, items: items });
} else { } else {
res.status(410).json({ status: 'ERROR', errorcode: 'NOT_EXISTING', message: 'storageUnit does not exist' }); res.status(410).json({ status: 'ERROR', errorcode: 'NOT_EXISTING', message: 'storageUnit does not exist' });
} }

View File

@ -2,6 +2,8 @@
// This magic js codes enables anchor links to work with bootstrap tabs // This magic js codes enables anchor links to work with bootstrap tabs
// Taken from https://stackoverflow.com/a/9393768/11317151 (and edited, like a lot) // Taken from https://stackoverflow.com/a/9393768/11317151 (and edited, like a lot)
const FLAG_supports_new_data_loader = true;
// Also update on location change // Also update on location change
window.addEventListener( window.addEventListener(
'hashchange', 'hashchange',
@ -29,9 +31,9 @@ function primeCreateNew() {
const form = document.getElementById('storageUnitModalForm'); const form = document.getElementById('storageUnitModalForm');
const form2 = document.getElementById('storageLocationModalForm'); const form2 = document.getElementById('storageLocationModalForm');
document.getElementById('createNewLocationSelection').disabled = false; document.getElementById('createNewLocationSelection').disabled = false;
document.getElementById('storageUnitModalLocationSelectText').innerText= "Select or create a new location."; document.getElementById('storageUnitModalLocationSelectText').innerText = 'Select or create a new location.';
document.getElementById('storageUnitModalLabel').innerText = "Create new storage unit"; document.getElementById('storageUnitModalLabel').innerText = 'Create new storage unit';
document.getElementById('storageLocationModalTitle').innerText = "Create new storage location"; document.getElementById('storageLocationModalTitle').innerText = 'Create new storage location';
form.setAttribute('method', 'POST'); form.setAttribute('method', 'POST');
form2.setAttribute('method', 'POST'); form2.setAttribute('method', 'POST');
return true; return true;
@ -42,25 +44,25 @@ function primeEdit() {
const form2 = document.getElementById('storageLocationModalForm'); const form2 = document.getElementById('storageLocationModalForm');
// Disable create new location // Disable create new location
document.getElementById('createNewLocationSelection').disabled = true; document.getElementById('createNewLocationSelection').disabled = true;
document.getElementById('storageUnitModalLocationSelectText').innerText= "While editing you can only select already existing locations. Use the settings to create new ones."; document.getElementById('storageUnitModalLocationSelectText').innerText = 'While editing you can only select already existing locations. Use the settings to create new ones.';
document.getElementById('storageUnitModalLabel').innerText = "Edit a storage unit"; document.getElementById('storageUnitModalLabel').innerText = 'Edit a storage unit';
document.getElementById('storageLocationModalTitle').innerText = "Edit a storage location" document.getElementById('storageLocationModalTitle').innerText = 'Edit a storage location';
document.getElementById('storageUnitModalLocationSelect').selectedIndex = 1 document.getElementById('storageUnitModalLocationSelect').selectedIndex = 1;
handleSelector() handleSelector();
form.setAttribute('method', 'PATCH'); form.setAttribute('method', 'PATCH');
form2.setAttribute('method', 'PATCH'); form2.setAttribute('method', 'PATCH');
return true; return true;
} }
function handleSelector(){ function handleSelector() {
const selector = document.getElementById('storageUnitModalLocationSelect') const selector = document.getElementById('storageUnitModalLocationSelect');
const value = selector.options[selector.selectedIndex].value; const value = selector.options[selector.selectedIndex].value;
if(value == "META_CREATENEW") { if (value == 'META_CREATENEW') {
$('#storageUnitModalContactInfoCreator').removeClass('d-none') $('#storageUnitModalContactInfoCreator').removeClass('d-none');
$('.requireOnCreate').attr('required', true) $('.requireOnCreate').attr('required', true);
} else { } else {
$('#storageUnitModalContactInfoCreator').addClass('d-none') $('#storageUnitModalContactInfoCreator').addClass('d-none');
$('.requireOnCreate').attr('required', false) $('.requireOnCreate').attr('required', false);
} }
} }
@ -69,7 +71,6 @@ function getDataForEdit(id) {
type: 'get', type: 'get',
url: `/api/v1/storageUnits?id=${id}`, url: `/api/v1/storageUnits?id=${id}`,
success: function (result) { success: function (result) {
// Get elements inside the editCategoryModal // Get elements inside the editCategoryModal
const modal_unitName = document.getElementById('storageUnitModalName'); const modal_unitName = document.getElementById('storageUnitModalName');
const modal_unitLocation = document.getElementById('storageUnitModalLocationSelect'); const modal_unitLocation = document.getElementById('storageUnitModalLocationSelect');
@ -80,15 +81,13 @@ function getDataForEdit(id) {
modal_unitId.value = result.id; modal_unitId.value = result.id;
// Select the correct location from the select based on the value of the option // Select the correct location from the select based on the value of the option
for(var i, j = 0; i = modal_unitLocation.options[j]; j++) { for (var i, j = 0; (i = modal_unitLocation.options[j]); j++) {
if(i.value == result.contactInfoId) { if (i.value == result.contactInfoId) {
console.log("Found it"); console.log('Found it');
modal_unitLocation.selectedIndex = j; modal_unitLocation.selectedIndex = j;
break; break;
} }
} }
}, },
error: function (data) { error: function (data) {
console.log('!!!! ERROR !!!!', data); console.log('!!!! ERROR !!!!', data);
@ -96,18 +95,16 @@ function getDataForEdit(id) {
$('.loader-overlay').removeClass('active'); $('.loader-overlay').removeClass('active');
// Close the modal // Close the modal
$('.modal').modal('hide'); $('.modal').modal('hide');
createNewToast('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. The storage unit does no longer exist.', "text-bg-danger") createNewToast('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. The storage unit does no longer exist.', 'text-bg-danger');
} }
}); });
} }
function getDataForEditLoc(id) { function getDataForEditLoc(id) {
$.ajax({ $.ajax({
type: 'get', type: 'get',
url: `/api/v1/storageLocations?id=${id}`, url: `/api/v1/storageLocations?id=${id}`,
success: function (result) { success: function (result) {
// Get elements inside the editCategoryModal // Get elements inside the editCategoryModal
const modal_locationName = document.getElementById('storageLocationModalName'); const modal_locationName = document.getElementById('storageLocationModalName');
const modal_locationUnitSel = document.getElementById('storageLocationModalUnit'); const modal_locationUnitSel = document.getElementById('storageLocationModalUnit');
@ -118,15 +115,13 @@ function getDataForEditLoc(id) {
modal_locationId.value = result.id; modal_locationId.value = result.id;
// Select the correct location from the select based on the value of the option // Select the correct location from the select based on the value of the option
for(var i, j = 0; i = modal_locationUnitSel.options[j]; j++) { for (var i, j = 0; (i = modal_locationUnitSel.options[j]); j++) {
if(i.value == result.storageUnitId) { if (i.value == result.storageUnitId) {
console.log("Found it"); console.log('Found it');
modal_locationUnitSel.selectedIndex = j; modal_locationUnitSel.selectedIndex = j;
break; break;
} }
} }
}, },
error: function (data) { error: function (data) {
console.log('!!!! ERROR !!!!', data); console.log('!!!! ERROR !!!!', data);
@ -134,9 +129,88 @@ function getDataForEditLoc(id) {
$('.loader-overlay').removeClass('active'); $('.loader-overlay').removeClass('active');
// Close the modal // Close the modal
$('.modal').modal('hide'); $('.modal').modal('hide');
createNewToast('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. The storage unit does no longer exist.', "text-bg-danger") createNewToast('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. The storage unit does no longer exist.', 'text-bg-danger');
} }
}); });
} }
handleSelector() const itemList = $('#itemList');
const itemListUnit = $('#itemListUnit');
// itemList.empty();
itemListUnit.bootstrapTable({ url: '/api/v1/storageUnits?getAll=true', search: true, showRefresh: true, responseHandler: dataResponseHandlerUnit, sidePagination: 'server', serverSort: true, silentSort: false });
itemList.bootstrapTable({ url: '/api/v1/storageLocations?getAll=true', search: true, showRefresh: true, responseHandler: dataResponseHandler, sidePagination: 'server', serverSort: true, silentSort: false });
setTimeout(() => {
activateTooltips();
}, 1000);
function loadPageData() {
// itemList.empty();
itemList.bootstrapTable('refresh');
itemListUnit.bootstrapTable('refresh');
setTimeout(() => {
activateTooltips();
}, 1000);
}
function dataResponseHandler(json) {
// console.log(json)
totalNotFiltered = json.totalNotFiltered;
total = json.total;
json = json.items;
json.forEach((item) => {
colorStatus = '';
item.actions = `
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#storageLocationModal" onclick="primeEdit(); getDataForEditLoc('${item.id}')">
<i class="bi bi-pencil"></i>
</button>
<button class="btn btn-danger" onclick="preFillDeleteModalNxt('${item.id}','storageLocations','Storage Location')" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
<i class="bi bi-trash"></i>
</button>`;
if (item.storageUnit == null) {
item.storageUnit = '<i>No storage unit assigned</i>';
} else {
item.storageUnit = item.storageUnit.name;
console.log(item.storageUnit);
}
// item.SKU = `<p data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="ID: ${item.id}">${item.SKU}</p>`
});
///// --------------------------------- /////
setTimeout(() => {
activateTooltips();
}, 200);
return { rows: json, total: total, totalNotFiltered: totalNotFiltered, totalRows: total };
}
function dataResponseHandlerUnit(json) {
// console.log(json)
totalNotFiltered = json.totalNotFiltered;
total = json.total;
json = json.items;
json.forEach((item) => {
colorStatus = '';
item.actions = `
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#storageUnitModal" onclick="primeEdit(); getDataForEdit('${item.id}')">
<i class="bi bi-pencil"></i>
</button>
<button class="btn btn-danger" onclick="preFillDeleteModalNxt('${item.id}','storageUnits','Storage Unit')" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
<i class="bi bi-trash"></i>
</button>`;
if (item.contactInfo == null) {
item.address = '<i>No address assigned</i>';
} else {
item.address = `${item.contactInfo.street} ${item.contactInfo.houseNumber}, ${item.contactInfo.city} ${item.contactInfo.country}`;
}
// item.SKU = `<p data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="ID: ${item.id}">${item.SKU}</p>`
});
///// --------------------------------- /////
setTimeout(() => {
activateTooltips();
}, 200);
return { rows: json, total: total, totalNotFiltered: totalNotFiltered, totalRows: total };
}
handleSelector();