Skip to content

Commit

Permalink
added support for user note
Browse files Browse the repository at this point in the history
  • Loading branch information
dedaleDev committed May 25, 2024
1 parent 0d83408 commit e24fa93
Show file tree
Hide file tree
Showing 11 changed files with 151 additions and 25 deletions.
48 changes: 27 additions & 21 deletions backup.sql

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions database.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ class db():
"selectAllISBN" : "SELECT ISBN FROM `Livre`;",
"selectAllUser" : "SELECT * FROM `Utilisateur`;",
"selectAllEmprunt" : "SELECT * FROM `Emprunt`;",
"addNote" : "INSERT INTO `Note` (`Note`, `Utilisateur`, `Livre`) VALUES (%s,%s,%s);",
"selectNoteByISBN" : "SELECT * FROM `Note` WHERE `Livre` = %s;",
"selectNoteByUserAndLivre" : "SELECT * FROM `Note` WHERE `Utilisateur` = %s AND `Livre` = %s;",
}

def __init__(self, host:str ="localhost", user:str="root", passwd:str="1234", port:int=3306, debug:bool=False) -> None:
Expand Down
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
db_PASSWD = "1234"
db_PORT = 3306

debug = False #Ne pas utiliser en usage normal, cela supprime l'ensemble des données au démarrage. En cas de problème, essayez d'activer ce mode.
debug = False #Rénitialise l'ensemble des données au démarrage. En cas de problème, essayez d'activer ce mode.

www_dir = os.path.abspath('./www')
print(os.path.join(www_dir, 'css'))
Expand Down
26 changes: 25 additions & 1 deletion operationOnDataBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -856,4 +856,28 @@ def convertPointDeVenteToAcceptablePointDeVente(pointDeVente:str,db:database.db)
print("point de vente trouvé", pointsDeVentes[i][0])
return pointsDeVentes[i][0]
else :
print("point de vente non trouvé", originPointDeVente +'!='+ pointDeVente)
print("point de vente non trouvé", originPointDeVente +'!='+ pointDeVente)

def getRealNote(isbn:str,db:database.db) -> float :
""" This function returns the real note of a book.
Args : isbn (str): The ISBN of the book.
Returns : float : The real note of the book."""
try :
db.mkRequest("selectNoteByISBN", False, isbn)
notes = db.cursor.fetchall()
moy = 0
nbNotes = 0
for note in notes :
print(note[3], isbn)
if note[3] ==isbn:
moy += note[1]
nbNotes+=1
if nbNotes != 0:
return moy/nbNotes
else :
db.mkRequest("selectLivreByISBN", True, isbn)
result = db.cursor.fetchall()
return result[0][4]
except Exception as e:
print(f"Une erreur est survenue lors de la recherche de la note réelle du livre :{e}, ligne : {e.__traceback__.tb_lineno}")
return 0
35 changes: 35 additions & 0 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,41 @@ def newUser(self, **params):
print(f"Erreur : {e}")
return self.makeResponse(is_error=True, error_message=str(e))

#Note = ID, Note (0-10), Utilisateur (email), Livre (isbn)
@cherrypy.expose
@cherrypy.tools.json_out()
def addNote(self, email:str, password:str, isbn:str, note:str) -> str:
try :
print("REQUEST RECEIVED", email, password, isbn, note)
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:
if isbn.isdigit() and float(note) >= 0 and float(note) <= 10:
self.db.mkRequest("selectLivreByISBN", False, isbn)
livre = self.db.cursor.fetchall()
if livre is not None and livre != () and livre != []:
self.db.mkRequest("selectNoteByUserAndLivre", False, email, isbn)
tmp = self.db.cursor.fetchall()
print("TMP",tmp)
if tmp == ():
self.db.mkRequest("addNote", False, note, email, isbn)
self.db.db.commit()
return self.makeResponse(content="success")
else :
return self.makeResponse(is_error=True, error_message="Vous avez déjà noté ce livre !")
else:
return self.makeResponse(is_error=True, error_message="Livre introuvable")
else :
return self.makeResponse(is_error=True, error_message="Les données envoyées sont incorrectes")
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 l'ajout de la note : ",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 :
response = cherrypy.response
Expand Down
8 changes: 7 additions & 1 deletion template.sql
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ CREATE TABLE `Livre` (

CREATE TABLE `Note` (
`ID` int(11) NOT NULL,
`Note` int(10) NOT NULL,
`Note` float(10) NOT NULL,
`Utilisateur` varchar(50) NOT NULL,
`Livre` varchar(13) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Expand Down Expand Up @@ -194,6 +194,12 @@ ALTER TABLE `Auteur`
ALTER TABLE `Emprunt`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

--
-- AUTO_INCREMENT pour la table `Note`
--
ALTER TABLE `Note`
MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT;

--
-- Contraintes pour les tables déchargées
--
Expand Down
2 changes: 2 additions & 0 deletions utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ def formatLivreToJsonOrdered(data:list[tuple], db:database.db)->json:
if len(item) != 12:
item = item[:12]
ISBN, titre, auteur, description, note, dateDeParution, status, genre, format, prix, pointDeVente, editeur = item
note = operationOnDataBase.getRealNote(ISBN, db)
result.append({
'ISBN': ISBN,
'titre': titre,
Expand Down Expand Up @@ -124,6 +125,7 @@ def formatLivreToJson(data:list[tuple], db:database.db)->json:
if len(item) != 12:
item = item[:12]
ISBN, titre, auteur, description, note, dateDeParution, status, genre, format, prix, pointDeVente, editeur = item
note = operationOnDataBase.getRealNote(ISBN, db)
result[ISBN] = {
'titre':titre,
'auteur':searchEngine.getAuteurNameByID(db, auteur),
Expand Down
1 change: 0 additions & 1 deletion www/css/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ body {

h1, h2, h3, p {
color : #ffffff;
width: ;
}

.logo {
Expand Down
13 changes: 13 additions & 0 deletions www/html/livre.html
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,19 @@ <h1 class="logo" style="padding-top: 10vh;"><a id="logo" href="./">BookWorm</a><
<img src="" id= "imgLivre" class="img-fluid w-110" alt="livre" style="padding-top: 13vh;">
<div id="status"></div>
<div id="reserver" style=" padding-top : 2vh"></div>
<div id="noter" style=" padding-top : 2vh">
<form id="noteForm">
<h6 style="color: white;">Vous avez aimé ce livre ? Notez-le !</h6>
<div class="form-group row">
<label style="color: white" for="note" class="col-sm-2 col-form-label">Note</label>
<div class="col-sm-10">
<div class="d-flex align-items-center">
<input id="inputNote" type="number" pattern="[0-9*]" value="5" class="form-control" id="note" name="note" min="0" max="10" step="0.5">
<button type="button" id="buttonNote" class="btn btn-primary ml-2" style="background-color:#FF8C42;">Noter</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Expand Down
1 change: 1 addition & 0 deletions www/img/stars/star0.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
37 changes: 37 additions & 0 deletions www/js/livre.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,5 +113,42 @@ loadLivre(isbn).then(livreData => {
})
});
}
const noteInput = document.getElementById("inputNote");
const noteButton = document.getElementById("buttonNote");
noteButton.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") {
console.log("note: ", noteInput.value, isbn);
fetch(`${API_URL}/addNote?email=${encodeURIComponent(email)}&password=${encodeURIComponent(password)}&isbn=${isbn}&note=${noteInput.value}`)
.then(response => response.json())
.then(data => {
console.log("data: ", data)
if (data.message === "Vous avez déjà noté ce livre !"){
alert("Vous avez déjà noté ce livre !");
} else if (data.content === "success") {
alert("Note ajoutée avec succès");
window.location.reload();
} else {
alert("Erreur lors de l'ajout de la note");
}
});
} else {
window.location.href = "/login";
}
})
});
}
})

0 comments on commit e24fa93

Please sign in to comment.