Skip to content

Commit

Permalink
user can now book Livre
Browse files Browse the repository at this point in the history
  • Loading branch information
dedaleDev committed May 19, 2024
1 parent 1bd5c8e commit ae06eb5
Show file tree
Hide file tree
Showing 8 changed files with 230 additions and 41 deletions.
1 change: 1 addition & 0 deletions database.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class db():
"insertPointDeVente" : "INSERT INTO `Point de vente` (`Adresse`, `Nom`, `Site web`, `Tel`) VALUES (%s,%s,%s,%s);",
"insertUtilisateur" : "INSERT INTO `Utilisateur` (`email`, `mdp`, `Grade`, `Nom`, `Prénom`, `Adresse`, `Tel`) VALUES (%s,%s,%s,%s,%s,%s,%s);",
"insertNote" : "INSERT INTO `Note` (`Note`, `Utilisateur`, `Livre`) values (%s,%s,%s);",
"insertEmprunt" : "INSERT INTO `Emprunt` (`Livre`, `Utilisateur`) VALUES (%s,%s);",
"selectAuteurByNom" : "SELECT * FROM `Auteur` WHERE `Nom` Like %s ORDER BY `ID` ASC;",
"selectAuteurByID" : "SELECT * FROM `Auteur` WHERE `ID` = %s;",
"selectAuteurByPrenom" : "SELECT * FROM `Auteur` WHERE `Prénom` LIKE %s ORDER BY `ID` ASC;",
Expand Down
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def updateJS(conf: dict):
conf : dict, configuration of the server cherrypy"""
try :
api_url = f"http://{conf['global']['server.socket_host']}:{conf['global']['server.socket_port']}"
files = ['www/js/index.js', 'www/js/search.js', 'www/js/livre.js', 'www/js/login.js','www/js/account.js']
files = ['www/js/index.js', 'www/js/search.js', 'www/js/livre.js', 'www/js/login.js','www/js/account.js','www/js/config.js']
for file in files :
with open(file, 'r', encoding='utf-8') as f:
code = f.readlines()
Expand Down
52 changes: 51 additions & 1 deletion server.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,26 @@ def checkLogin(self, email:str, password:str) -> str:
print("\033[31mErreur lors de la tentative de conneion : ",e, e.__traceback__.tb_lineno, user, "\033[0m")
return self.makeResponse(is_error=True, error_message="Oups, une erreur est survenue, veuillez réessayer ultérieurement")

@cherrypy.expose
@cherrypy.tools.json_out()
def isAdmin(self, email:str, password:str) -> str:
try :
self.db.mkRequest("selectUserByEmail", False, email)
user = self.db.cursor.fetchall()
if user is not None and user != () and user != []:
if user[0][1] == password:
if user[0][2] == "admin":
return self.makeResponse(content="success")
else:
return self.makeResponse(is_error=True, error_message="Vous n'êtes pas administrateur")
else:
return self.makeResponse(is_error=True, error_message="Mot de passe incorrect")
else:
return self.makeResponse(is_error=True, error_message="Utilisateur introuvable")
except Exception as e:
print("\033[31mErreur lors de la tentative de conneion : ",e, e.__traceback__.tb_lineno, user, "\033[0m")
return self.makeResponse(is_error=True, error_message="Oups, une erreur est survenue, veuillez réessayer ultérieurement")

@cherrypy.expose
@cherrypy.tools.json_out()
def getUserInfo(self, email:str, password:str) -> str:
Expand Down Expand Up @@ -187,7 +207,37 @@ def updateBestLivres(self) -> str :
return self.makeResponse(content='ok')
except Exception as e:
print("Erreur lors de la mise à jour des livres de la page d'accueil", e, e.__traceback__.tb_lineno)


@cherrypy.expose
@cherrypy.tools.json_out()
def reserveLivre(self, email:str, password:str, isbn:str) -> str:
try :
#check password before
self.db.mkRequest("selectUserByEmail", True, email)
user = self.db.cursor.fetchall()
if user is not None and user != () and user != []:
if user[0][1] == password:
self.db.mkRequest("selectLivreByISBN", False, isbn)
livre = self.db.cursor.fetchall()
if livre is not None and livre != () and livre != []:
self.db.mkRequest("selectEmpruntByUser", True, email)
emprunts = self.db.cursor.fetchall()
if emprunts is not None and emprunts != () and emprunts != []:
for emprunt in emprunts:
if emprunt[0] == isbn:
return self.makeResponse(is_error=True, error_message="Ce livre est déjà réservé")
self.db.mkRequest("insertEmprunt", False, isbn,email)
self.db.db.commit()
return self.makeResponse(content="success")
else:
return self.makeResponse(is_error=True, error_message="Livre introuvable")
else:
return self.makeResponse(is_error=True, error_message="Mot de passe incorrect")
else:
return self.makeResponse(is_error=True, error_message="Utilisateur introuvable")
except Exception as e:
print("\033[31mErreur lors de la réservation : ",e, e.__traceback__.tb_lineno, "\033[0m")
return self.makeResponse(is_error=True, error_message="Oups, une erreur est survenue, veuillez réessayer ultérieurement")

def jsonify_error(status, message, traceback, version):
try :
Expand Down
26 changes: 26 additions & 0 deletions www/css/config.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
body {
background-image: url("../img/background.svg");
background-size: cover;
background-position: center;
background-repeat: repeat;
padding: 0;
margin : 0;
}
h1,h2, label{
color : #ffffff;
}

#mascotte404{
width: 50%;
height: auto;
margin-top: 10vh;
}

a{
color:white;
text-decoration: none;
}
#logo{
color: #ffffff;
text-decoration: none;
}
36 changes: 36 additions & 0 deletions www/html/config.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<!DOCTYPE html>
<html>
<head>
<title>BookWorm : Espace Administrateur</title>
<meta charset="utf-8", lang="fr">
<link rel="stylesheet" href="../frameworks/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="../css/config.css">
</head>
<body>
<h1 class="logo" style="padding-top: 5vh; padding-left: 5vh;"><a id="logo" href="./">BookWorm</a></h3>
<div class="container">
<div class="row">
<div class="col-md-8">
<h1 class="logo" style="padding-top: 10vh;">Espace Administrateur</h1>
<div class="d-flex justify-content-start" style="padding-left: 5vh; padding-top: 5vh;">
<div class="dropdown" style="padding-right: 5vh;">
<button id="selectTypeButton" class="btn btn-secondary dropdown-toggle" type="button" style="background-color: #FF8C42;" data-bs-toggle="dropdown" aria-expanded="false">
Parcourir
</button>
<ul class="dropdown-menu">
<li><a class="dropdown-item" id="selectLivre">Livres</a></li>
<li><a class="dropdown-item" id="selectAuteur">Auteurs</a></li>
<li><a class="dropdown-item" id="selectPointDeVente">Points de ventes</a></li>
<li><a class="dropdown-item" id="selectEditeur">Editeurs</a></li>
<li><a class="dropdown-item" id="selectUtilisateur">Utilisateurs</a></li>
<li><a class="dropdown-item" id="selectUtilisateur">Emprunts</a></li>
</ul>
</div>
</div>
</div>
</div>
<script src="../js/config.js"></script>
<script src="../frameworks/popper.min.js"></script>
<script src="../frameworks/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
3 changes: 2 additions & 1 deletion www/html/livre.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ <h1 class="logo" style="padding-top: 10vh;"><a id="logo" href="./">BookWorm</a><
</div>
<div class="col-md-4" style="padding-left: 5vw; padding-top: 5vh;">
<img src="" id= "imgLivre" class="img-fluid w-110" alt="livre" style="padding-top: 13vh;">
<img src="../img/reserver.svg" alt="reserver" class="img-fluid mx-auto" style="width: 50%; padding-top: 5vh;" id="reserver">
<div id="status"></div>
<div id="reserver" style=" padding-top : 2vh"></div>
</div>
</div>
</div>
Expand Down
12 changes: 12 additions & 0 deletions www/js/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const API_URL = 'http://192.168.1.20:8080'

fetch(`${API_URL}/isAdmin?email=${encodeURIComponent(email)}&password=${encodeURIComponent(password)}`)
.then(response => response.json())
.then(data => {
console.log(data);
if (data.content === "success") {
console.log("Admin")
} else {
window.location.href = "/login";
}
})
139 changes: 101 additions & 38 deletions www/js/livre.js
Original file line number Diff line number Diff line change
@@ -1,54 +1,117 @@
const API_URL = 'http://192.168.1.20:8080'

var _template = " <div class='row justify-content-center'> \
<div class='col-md-10' style='padding-top: 3vh'>\
<div class='card mb-3'>\
<h2 class='card-header'></strong>{{ titre }}</h2>\
<div class='card-body'>\
<ul class='list-group list-group-flush'>\
<li class='list-group-item'><strong><a href='/search?search={{ auteur }}&type=Auteur'><h3>{{ auteur }}<h3></a></strong></li>\
<li class='list-group-item'><img class='img-fluid align-middle' style='width: 22%;' src='/img/stars/star{{ note }}.svg'><span class='align-middle'> ({{ NoteEx }})</span></li>\
<li class='list-group-item'>Date de parution : {{ dateDeParution }}</li>\
<li class='list-group-item'><italic>{{ genre }}</italic></li>\
<li class='list-group-item'>{{ description }}</li>\
<li class='list-group-item'>Format : {{ format }}</li>\
<li class='list-group-item'>En vente chez {{ pointDeVenteName }} ({{ pointDeVente }}) à {{ prix }} €</li>\
<li class='list-group-item'> Editeur : {{ editeur }}</li>\
</ul>\
</div>\
</div>\
</div>";
const API_URL = 'http://192.168.1.20:8080';

var _template = `
<div class='row justify-content-center'>
<div class='col-md-10' style='padding-top: 3vh'>
<div class='card mb-3'>
<h2 class='card-header'>{{ titre }}</h2>
<div class='card-body'>
<ul class='list-group list-group-flush'>
<li class='list-group-item'>
<strong>
<a href='/search?search={{ auteur }}&type=Auteur'>
<h3>{{ auteur }}</h3>
</a>
</strong>
</li>
<li class='list-group-item'>
<img class='img-fluid align-middle' style='width: 22%;' src='/img/stars/star{{ note }}.svg'>
<span class='align-middle'> ({{ NoteEx }})</span>
</li>
<li class='list-group-item'>Date de parution : {{ dateDeParution }}</li>
<li class='list-group-item'><i>{{ genre }}</i></li>
<li class='list-group-item'>{{ description }}</li>
<li class='list-group-item'>Format : {{ format }}</li>
<li class='list-group-item'>En vente chez {{ pointDeVenteName }} ({{ pointDeVente }}) à {{ prix }} €</li>
<li class='list-group-item'>Editeur : {{ editeur }}</li>
</ul>
</div>
</div>
</div>
</div>
`;

async function loadLivre(isbn) {
console.log("livre: ", isbn);
let response = await fetch(`${API_URL}/getLivre?isbn=${isbn}`);
let response = await fetch(`${API_URL}/getLivre?isbn=${isbn}`);
let livreData = await response.json();
livreData = JSON.parse(livreData["content"]);
console.log("livre: ", livreData);
return livreData[isbn];
}

const urlParams = new URLSearchParams(window.location.search);
const isbn = urlParams.get('isbn');

loadLivre(isbn).then(livreData => {
if (typeof livreData === 'object' && livreData !== null) {
console.log("livreData: ", livreData);
let template = _template.replace("{{ titre }}", livreData["titre"]).replace("{{ auteur }}", livreData["auteur"]).replace("{{ note }}", Math.round(livreData["note"])).replace("{{ isbn }}", livreData["isbn"]).replace("{{ dateDeParution }}", livreData["dateDeParution"]).replace("{{ genre }}", livreData["genre"]).replace("{{ description }}", livreData["description"]).replace("{{ format }}", livreData["format"]).replace("{{ pointDeVente }}", livreData["pointDeVente"]).replace("{{ prix }}", livreData["prix"]).replace("{{ editeur }}", livreData["editeur"]).replace("{{ pointDeVenteName }}", livreData["pointDeVenteName"]).replace("{{ auteur }}", livreData["auteur"]).replace("{{ NoteEx }}", livreData["note"]);
if (livreData["status"] == "emprunté") {
document.getElementById("reservation").innerHTML = "<img class='img-fluid mx-left d-block' style='width: 70%; padding-top: 2vh' src='img/{{ status }}.svg'>".replace("{{ status }}", "borrowed");
} else if (livreData["status"] == "disponible") {
document.getElementById("reservation").innerHTML = "<img class='img-fluid mx-left d-block' style='width: 70%; padding-top: 2vh' src='img/{{ status }}.svg'>".replace("{{ status }}", "available");
} else if (livreData["status"] == "hors stock") {
document.getElementById("reservation").innerHTML = "<img class='img-fluid mx-left d-block' style='width: 70%; padding-top: 2vh' src='img/{{ status }}.svg'>".replace("{{ status }}", "outOfStock");
}
template = template.replace("{{ isbn }}", livreData[isbn]);
document.getElementById("LivreInfo").innerHTML += template;
console.log('img/livres/'+isbn+'.jpg')
document.getElementById("imgLivre").src = `img/livres/${isbn}.jpg`;
console.log("livreData: ", livreData);

let template = _template
.replace("{{ titre }}", livreData.titre)
.replace("{{ auteur }}", livreData.auteur)
.replace("{{ auteur }}", livreData.auteur)
.replace("{{ note }}", Math.round(livreData.note))
.replace("{{ dateDeParution }}", livreData.dateDeParution)
.replace("{{ genre }}", livreData.genre)
.replace("{{ description }}", livreData.description)
.replace("{{ format }}", livreData.format)
.replace("{{ pointDeVente }}", livreData.pointDeVente)
.replace("{{ prix }}", livreData.prix)
.replace("{{ editeur }}", livreData.editeur)
.replace("{{ pointDeVenteName }}", livreData.pointDeVenteName)
.replace("{{ NoteEx }}", livreData.note);

document.getElementById("LivreInfo").innerHTML += template;
document.getElementById("imgLivre").src = `img/livres/${isbn}.jpg`;

let status = '';
if (livreData.status === "emprunté") {
status = "borrowed";
} else if (livreData.status === "disponible") {
status = "available";
} else if (livreData.status === "hors stock") {
status = "outOfStock";
}
if (status) {
document.getElementById("status").innerHTML = `<img class='img-fluid mx-left d-block' style='width: 70%; padding-top: 2vh' src='img/${status}.svg'>`;
}

if (livreData.status === "disponible") {
document.getElementById("reserver").innerHTML = `<button class='btn btn-primary' style="background-color:#FF8C42;">Réserver</button>`;
document.getElementById("reserver").addEventListener("click", function () {
let decodedCookie = decodeURIComponent(document.cookie).split(';');
let email = '', password = '';
decodedCookie.forEach(c => {
let cookie = c.trim();
if (cookie.startsWith('email=')) {
email = cookie.substring('email='.length);
}
if (cookie.startsWith('password=')) {
password = cookie.substring('password='.length);
}
});

fetch(`${API_URL}/checkLogin?email=${encodeURIComponent(email)}&password=${encodeURIComponent(password)}`)
.then(response => response.json())
.then(data => {
if (data.content === "success") {
if (confirm("Êtes-vous sûr de vouloir réserver ce livre ?")) {
fetch(`${API_URL}/reserveLivre?email=${encodeURIComponent(email)}&password=${encodeURIComponent(password)}&isbn=${isbn}`)
.then(response => response.json())
.then(data => {
if (data.content === "success") {
window.location.href = "/login";
} else {
alert("Erreur lors de la réservation");
}
});
}
} else {
window.location.href = "/login";
}
})
});
}
else {
document.getElementById("LivreInfo").innerHTML = "<br><h2 class='text-center' style='color:white'>Oups, aucun résultat n'a été trouvé.<h2><br><img id='mascotte404' class='img-fluid mx-auto d-block w-25' src='../img/error404.svg' alt='404'>";
}

});
})

0 comments on commit ae06eb5

Please sign in to comment.