Implemented storageUnit api / Added error handling

- AFLOW-13
- Added check if an category entry already exists.
- Update precheck if all IDs are existing
This commit is contained in:
Leon Meier 2023-05-16 17:44:31 +02:00
parent b514e81764
commit 33b6856b25
7 changed files with 299 additions and 52 deletions

View File

@ -62,8 +62,8 @@
<div class="mb-3"> <div class="mb-3">
<label for="storageUnitModalLocationSelect" class="form-label">Storage Location</label> <label for="storageUnitModalLocationSelect" class="form-label">Storage Location</label>
<select class="form-select" id="storageUnitModalLocationSelect" name="location" onchange="handleSelector()" required> <select class="form-select" id="storageUnitModalLocationSelect" name="locationId" onchange="handleSelector()" required>
<option value="META_CREATENEW"> Create new location</option> <option value="META_CREATENEW" id="createNewLocationSelection"> Create new location</option>
<% it.address.forEach(function(address){ %> <% it.address.forEach(function(address){ %>
<option value="<%= address.id %>"><%= address.street %> <%= address.houseNumber %>, <%= address.city %> <%= address.country %></option> <option value="<%= address.id %>"><%= address.street %> <%= address.houseNumber %>, <%= address.city %> <%= address.country %></option>
<% }) %> <% }) %>
@ -71,6 +71,7 @@
<!--<input type="text" class="form-control" id="storageUnitModalLocationSelect" name="select" required />--> <!--<input type="text" class="form-control" id="storageUnitModalLocationSelect" name="select" required />-->
<div id="storageUnitModalLocationSelectText" class="form-text">Select or create a new address.</div> <div id="storageUnitModalLocationSelectText" class="form-text">Select or create a new address.</div>
<input type="hidden" id="storageUnitModalLocationSelectHidden" name="id" />
</div> </div>
<div id="storageUnitModalContactInfoCreator" class="d-none"> <div id="storageUnitModalContactInfoCreator" class="d-none">
@ -82,13 +83,13 @@
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="storageUnitModalHouseNumber" class="form-label">Housenumber</label> <label for="storageUnitModalHouseNumber" class="form-label">Housenumber</label>
<input type="text" class="form-control requireOnCreate" id="storageUnitModalHouseNumber" name="housenumber" /> <input type="text" class="form-control requireOnCreate" id="storageUnitModalHouseNumber" name="houseNumber" />
<div id="storageUnitModalHouseNumberText" class="form-text">6a</div> <div id="storageUnitModalHouseNumberText" class="form-text">6a</div>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="storageUnitModalzipcode" class="form-label">Zipcode</label> <label for="storageUnitModalzipcode" class="form-label">Zipcode</label>
<input type="text" class="form-control requireOnCreate" id="storageUnitModalzipcode" name="zipcode" /> <input type="text" class="form-control requireOnCreate" id="storageUnitModalzipcode" name="zipCode" />
<div id="storageUnitModalzipcodeText" class="form-text">123456</div> <div id="storageUnitModalzipcodeText" class="form-text">123456</div>
</div> </div>
@ -195,10 +196,10 @@
<td scope="row" data-bs-toggle="tooltip" data-bs-placement="left" data-bs-title="ID: <%= units.id %>"><%= units.name %></td> <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><%= units.contactInfo.street %> <%= units.contactInfo.houseNumber %>, <%= units.contactInfo.city %> <%= units.contactInfo.country %></td>
<td> <td>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#storageUnitModal" onclick="primeEdit(); getDataForEdit('<%= units.name %>')"> <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#storageUnitModal" onclick="primeEdit(); getDataForEdit('<%= units.id %>')">
<i class="bi bi-pencil"></i> <i class="bi bi-pencil"></i>
</button> </button>
<button class="btn btn-danger" onclick="preFillDeleteModal('<%= units.name %>')" data-bs-toggle="modal" data-bs-target="#staticBackdrop"><i class="bi bi-trash"></i></button> <button class="btn btn-danger" onclick="preFillDeleteModal('<%= units.id %>')" data-bs-toggle="modal" data-bs-target="#staticBackdrop"><i class="bi bi-trash"></i></button>
</td> </td>
</tr> </tr>
<% }) %> <% }) %>

View File

@ -11,6 +11,7 @@
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" /> <link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<script src="/js/normalizeToast.js"></script>
<script src="/static/jquery/dist/jquery.min.js"></script> <script src="/static/jquery/dist/jquery.min.js"></script>
<link href="/static/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" /> <link href="/static/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="/static/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet" /> <link href="/static/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet" />

View File

@ -1,18 +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';
// Get storageUnit. // Get storageUnit.
function get(req: Request, res: Response) { function get(req: Request, res: Response) {
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.name) { if (!req.query.id) {
res.status(400).render(__path + '/src/frontend/errors/400.eta.html'); res.status(400).render(__path + '/src/frontend/errors/400.eta.html');
return; return;
} }
prisma.storageUnit prisma.storageUnit
.findUnique({ .findUnique({
where: { where: {
name: req.query.name.toString() id: parseInt(req.query.id.toString())
}, },
// Get category name from relation. // Get category name from relation.
include: { include: {
@ -54,36 +55,120 @@ function get(req: Request, res: Response) {
// Create storageUnit. // Create storageUnit.
function post(req: Request, res: Response) { function post(req: Request, res: Response) {
log.web.debug(JSON.stringify(req.body)); // If the frontend wants to create a StorageUnit with non-existing ContactInfo.
/* // Check if required fields are present. if (req.body.locationId === 'META_CREATENEW') {
if (!req.body.name) { // Check if required fields are present.
if (!req.body.street || !req.body.houseNumber || !req.body.zipCode || !req.body.city || !req.body.country || !req.body.name) {
res.status(400).render(__path + '/src/frontend/errors/400.eta.html');
return;
}
// Create storageUnit and location.
prisma.storageUnit
.create({
data: {
name: req.body.name,
contactInfo: {
create: {
type: contactType.storageUnit,
street: req.body.street,
houseNumber: req.body.houseNumber,
zipCode: req.body.zipCode,
city: req.body.city,
country: req.body.country
}
}
}
})
.then(() => {
res.status(201).json({ status: 'created' });
})
.catch((err) => {
// Check if an entry already exists.
if (err.code === 'P2002') {
// P2002 -> "Unique constraint failed on the {constraint}"
// https://www.prisma.io/docs/reference/api-reference/error-reference
res.status(409).json({ error: 'storageUnit already exists.' });
} else {
log.db.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}
});
} else {
// Check if required fields are present.
if (!req.body.name || !req.body.locationId) {
res.status(400).render(__path + '/src/frontend/errors/400.eta.html');
return;
}
// Create storageUnit with existing location.
prisma.storageUnit
.create({
data: {
name: req.body.name,
contactInfo: {
connect: {
id: parseInt(req.body.locationId)
}
}
}
})
.then(() => {
res.status(201).json({ status: 'created' });
})
.catch((err) => {
// Check if an entry already exists.
if (err.code === 'P2002') {
// P2002 -> "Unique constraint failed on the {constraint}"
// https://www.prisma.io/docs/reference/api-reference/error-reference
res.status(409).json({ error: 'storageUnit already exists.' });
} else {
log.db.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}
});
}
}
// Update storageUnit. -> Only existing contactInfo.
async function patch(req: Request, res: Response) {
// Check if required fields are present.
if (!req.body.id || !req.body.name || !req.body.locationId) {
res.status(400).render(__path + '/src/frontend/errors/400.eta.html'); res.status(400).render(__path + '/src/frontend/errors/400.eta.html');
return; return;
} }
// Save data. // Check if the storageUnit id exists. If not return 410 Gone.
prisma.storageUnit try {
.create({ const result = await prisma.storageUnit.findUnique({
data: { where: {
name: req.body.name id: parseInt(req.body.id)
} }
}) });
.then(() => {
res.status(201).json({ status: 'created' });
})
.catch((err) => {
// TODO Catch if is a duplicate error and show a message to the user
log.db.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}); */
}
// Update category. if (result === null) {
function patch(req: Request, res: Response) { res.status(410).json({ error: 'storageUnit does not exist.' });
// Check if required fields are present. return;
if (!req.body.id || !req.body.name) { }
res.status(400).render(__path + '/src/frontend/errors/400.eta.html'); } catch (err) {
return; log.db.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}
// Check if the locationId(contactInfo) exists. If not return 410 Gone.
try {
const result = await prisma.contactInfo.findUnique({
where: {
id: parseInt(req.body.locationId)
}
});
if (result === null) {
res.status(410).json({ error: 'locationId does not exist.' });
return;
}
} catch (err) {
log.db.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
} }
prisma.storageUnit prisma.storageUnit
@ -92,20 +177,31 @@ function patch(req: Request, res: Response) {
id: parseInt(req.body.id) id: parseInt(req.body.id)
}, },
data: { data: {
name: req.body.name name: req.body.name,
contactInfo: {
connect: {
id: parseInt(req.body.locationId)
}
}
} }
}) })
.then(() => { .then(() => {
res.status(201).json({ status: 'updated' }); res.status(201).json({ status: 'updated' });
}) })
.catch((err) => { .catch((err) => {
// TODO Catch if is a duplicate error and show a message to the user // Check if an entry already exists.
log.db.error(err); if (err.code === 'P2002') {
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err }); // P2002 -> "Unique constraint failed on the {constraint}"
// https://www.prisma.io/docs/reference/api-reference/error-reference
res.status(409).json({ error: 'storageUnit already exists.' });
} else {
log.db.error(err);
res.status(500).render(__path + '/src/frontend/errors/dbError.eta.html', { error: err });
}
}); });
} }
// Delete category. // Delete storageUnit.
async function del(req: Request, res: Response) { async function del(req: Request, res: Response) {
// Check if required fields are present. // Check if required fields are present.
if (!req.body.id) { if (!req.body.id) {
@ -122,7 +218,7 @@ async function del(req: Request, res: Response) {
}); });
if (result === null) { if (result === null) {
res.status(410).json({ error: 'Storage Unit does not exist.' }); res.status(410).json({ error: 'storageUnit does not exist.' });
return; return;
} }
} catch (err) { } catch (err) {
@ -137,7 +233,7 @@ async function del(req: Request, res: Response) {
} }
}) })
.then(() => { .then(() => {
res.status(201).json({ status: 'deleted' }); res.status(200).json({ status: 'deleted' });
}) })
.catch((err) => { .catch((err) => {
log.db.error(err); log.db.error(err);

View File

@ -20,7 +20,7 @@ function getDataForEdit(name) {
$('.loader-overlay').removeClass('active'); $('.loader-overlay').removeClass('active');
// Close the modal // Close the modal
$('.modal').modal('hide'); $('.modal').modal('hide');
$('#generalToast').removeClass('text-bg-primary'); normalizeToast()
$('#generalToast').addClass('text-bg-danger'); $('#generalToast').addClass('text-bg-danger');
$('#generalToast').toast('show'); $('#generalToast').toast('show');
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. The category does no longer exist.'); $('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. The category does no longer exist.');
@ -81,14 +81,13 @@ function deleteEntry(id) {
error: function (data) { error: function (data) {
// hide the staticBackdrop modal // hide the staticBackdrop modal
$('#staticBackdrop').modal('hide'); $('#staticBackdrop').modal('hide');
$('#generalToast').removeClass('text-bg-primary'); normalizeToast()
$('#generalToast').addClass('text-bg-danger'); $('#generalToast').addClass('text-bg-danger');
$('#generalToast').toast('show'); $('#generalToast').toast('show');
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. Please try again later.'); $('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. Please try again later.');
setTimeout(() => { setTimeout(() => {
$('#generalToast').toast('hide'); $('#generalToast').toast('hide');
$('#generalToast').removeClass('text-bg-danger');
$('#generalToast').addClass('text-bg-primary');
}, 3000); }, 3000);
} }
}); });
@ -118,7 +117,7 @@ function preFillDeleteModal(name) {
document.getElementById('deleteNamePlaceholder').innerText = 'Deleted'; document.getElementById('deleteNamePlaceholder').innerText = 'Deleted';
$('#staticBackdrop').modal('hide'); $('#staticBackdrop').modal('hide');
$('#generalToast').removeClass('text-bg-primary'); normalizeToast()
$('#generalToast').addClass('text-bg-danger'); $('#generalToast').addClass('text-bg-danger');
$('#generalToast').toast('show'); $('#generalToast').toast('show');
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. The category does no longer exist.'); $('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. The category does no longer exist.');

View File

@ -26,6 +26,9 @@ $('.nav-link').on('click', function (e) {
function primeCreateNew() { function primeCreateNew() {
const form = document.getElementById('storageUnitModalForm'); const form = document.getElementById('storageUnitModalForm');
const form2 = document.getElementById('storageLocationModal'); const form2 = document.getElementById('storageLocationModal');
document.getElementById('createNewLocationSelection').disabled = false;
document.getElementById('storageUnitModalLocationSelectText').innerText= "Select or create a new location.";
document.getElementById('storageUnitModalLabel').innerText = "Create new storage unit";
form.setAttribute('method', 'POST'); form.setAttribute('method', 'POST');
form2.setAttribute('method', 'POST'); form2.setAttribute('method', 'POST');
return true; return true;
@ -34,6 +37,12 @@ function primeCreateNew() {
function primeEdit() { function primeEdit() {
const form = document.getElementById('storageUnitModalForm'); const form = document.getElementById('storageUnitModalForm');
const form2 = document.getElementById('storageLocationModal'); const form2 = document.getElementById('storageLocationModal');
// Disable create new location
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('storageUnitModalLabel').innerText = "Edit a storage unit";
document.getElementById('storageUnitModalLocationSelect').value = 1
handleSelector()
form.setAttribute('method', 'PATCH'); form.setAttribute('method', 'PATCH');
form2.setAttribute('method', 'PATCH'); form2.setAttribute('method', 'PATCH');
return true; return true;
@ -52,4 +61,135 @@ function handleSelector(){
console.log(value); console.log(value);
} }
function preFillDeleteModal(id) {
$.ajax({
type: 'get',
url: `/api/v1/storageUnits?id=${id}`,
success: function (data) {
const result = JSON.parse(data);
// Get elements inside the editCategoryModal
const modal_categoryName = document.getElementById('deleteNamePlaceholder');
const modal_deleteButton = document.getElementById('deleteActionBtn');
//const modal_categoryDescription = document.getElementById('editCategoryModalDescription');
//const modal_categoryid = document.getElementById('editCategoryModalId');
modal_categoryName.innerText = result.name;
modal_deleteButton.setAttribute('onclick', `deleteEntry(${result.id})`);
//modal_categoryDescription.value = result.description;
//modal_categoryid.value = result.id;
},
error: function (data) {
console.log('!!!! ERROR !!!!', data);
document.getElementById('deleteNamePlaceholder').innerText = 'Deleted';
$('#staticBackdrop').modal('hide');
normalizeToast()
$('#generalToast').addClass('text-bg-danger');
$('#generalToast').toast('show');
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. The storageUnit does no longer exist.');
setTimeout(() => {
window.location.reload();
}, 3000);
}
});
}
function deleteEntry(id) {
$.ajax({
type: 'delete',
url: `/api/v1/storageUnits`,
data: { id: id },
success: function (data) {
$('#staticBackdrop').modal('hide');
normalizeToast()
$('#generalToast').addClass('text-bg-success');
$('#generalToast').toast('show');
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-check2"></i> Storage Unit deleted successfully.');
confetti({
spread: 360,
ticks: 100,
gravity: 0.1,
decay: 0.94,
startVelocity: 30,
particleCount: 20,
scalar: 2,
shapes: ['text'],
shapeOptions: {
text: {
value: ['❌', '🗑️', '🚫']
}
}
});
setTimeout(() => {
$('#generalToast').toast('hide');
window.location.reload();
}, 2000);
},
error: function (data) {
// hide the staticBackdrop modal
$('#staticBackdrop').modal('hide');
normalizeToast()
$('#generalToast').addClass('text-bg-danger');
$('#generalToast').toast('show');
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. Please try again later.');
setTimeout(() => {
$('#generalToast').toast('hide');
}, 3000);
}
});
}
function getDataForEdit(id) {
$.ajax({
type: 'get',
url: `/api/v1/storageUnits?id=${id}`,
success: function (data) {
const result = JSON.parse(data);
// Get elements inside the editCategoryModal
const modal_unitName = document.getElementById('storageUnitModalName');
const modal_unitLocation = document.getElementById('storageUnitModalLocationSelect');
const modal_unitId = document.getElementById('storageUnitModalLocationSelectHidden');
// const modal_categoryid = document.getElementById('editCategoryModalId');
modal_unitName.value = result.name;
modal_unitId.value = result.id;
// 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++) {
console.log(i.value, result.contactInfoId);
if(i.value == result.contactInfoId) {
console.log("Found it");
modal_unitLocation.selectedIndex = j;
break;
}
}
},
error: function (data) {
console.log('!!!! ERROR !!!!', data);
// Hide overlay with spinner
$('.loader-overlay').removeClass('active');
// Close the modal
$('.modal').modal('hide');
normalizeToast()
$('#generalToast').addClass('text-bg-danger');
$('#generalToast').toast('show');
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. The storage unit does no longer exist.');
setTimeout(() => {
window.location.reload();
}, 3000);
}
});
}
handleSelector() handleSelector()

View File

@ -26,14 +26,12 @@ $('.frontendForm').each(function() {
// Clear all fields // Clear all fields
form.find('input, textarea').val(''); form.find('input, textarea').val('');
$('#generalToast').removeClass('text-bg-primary'); normalizeToast()
$('#generalToast').addClass('text-bg-success'); $('#generalToast').addClass('text-bg-success');
$('#generalToast').toast('show'); $('#generalToast').toast('show');
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-check2"></i> Changes saved successfully.'); $('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-check2"></i> Changes saved successfully.');
setTimeout(() => { setTimeout(() => {
$('#generalToast').toast('hide');; $('#generalToast').toast('hide');;
$('#generalToast').removeClass('text-bg-success');
$('#generalToast').addClass('text-bg-primary');
window.location.reload(); window.location.reload();
}, 1500); }, 1500);
}, },
@ -41,15 +39,20 @@ $('.frontendForm').each(function() {
console.log('error'); console.log('error');
// Hide overlay with spinner // Hide overlay with spinner
$('.loader-overlay').removeClass('loaderActive'); $('.loader-overlay').removeClass('loaderActive');
$('#generalToast').removeClass('text-bg-primary'); // Check for response code 409
normalizeToast()
$('#generalToast').addClass('text-bg-danger'); $('#generalToast').addClass('text-bg-danger');
$('#generalToast').toast('show'); $('#generalToast').toast('show');
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. Please try again later.');
if (data.status == 409) {
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> The element you tried to create already exists.');
}else {
$('#generalToast').children('.d-flex').children('.toast-body').html('<i class="bi bi-exclamation-triangle-fill"></i> Something went wrong. Please try again later.');
}
setTimeout(() => { setTimeout(() => {
$('#generalToast').toast('hide'); $('#generalToast').toast('hide');
$('#generalToast').removeClass('text-bg-danger');
$('#generalToast').addClass('text-bg-primary');
}, 3000); }, 3000);
} }
}); });

View File

@ -0,0 +1,7 @@
function normalizeToast(){
$('#generalToast').removeClass('text-bg-primary');
$('#generalToast').removeClass('text-bg-success');
$('#generalToast').removeClass('text-bg-danger');
$('#generalToast').removeClass('text-bg-warning');
$('#generalToast').removeClass('text-bg-info');
}