This commit is contained in:
Parpaillax
2024-04-30 13:21:46 +02:00
16 changed files with 282 additions and 24 deletions

View File

@@ -13,7 +13,7 @@ public interface ArticleService {
Article findArticleById(int id);
int saveArticle(Article article);
void deleteArticle(int id);
void updateArticle(int id);
int updateArticle(Article article);
List<Article> findArticleByTitle(String title);
Page<Article> searchArticlePageable(SearchArticleCritere critere, Pageable pageable);
}

View File

@@ -38,8 +38,8 @@ public class ArticleServiceImpl implements ArticleService{
}
@Override
public void updateArticle(int id) {
public int updateArticle(Article article) {
return articleRepository.updateArticle(article);
}
@Override

View File

@@ -3,6 +3,7 @@ package fr.eni.enchere.bll;
import fr.eni.enchere.bo.Retrait;
public interface RetraitService {
Retrait retraitByNumarticle(int id);
Retrait findByNumArticle(int id);
void setRetrait(Retrait retrait);
void updateRetrait(Retrait retrait);
}

View File

@@ -14,12 +14,17 @@ public class RetraitServiceImpl implements RetraitService {
}
@Override
public Retrait retraitByNumarticle(int id) {
return null;
public Retrait findByNumArticle(int idArticle) {
return retraitRepository.findByNumArticle(idArticle);
}
@Override
public void setRetrait(Retrait retrait) {
retraitRepository.save(retrait);
}
@Override
public void updateRetrait(Retrait retrait) {
retraitRepository.update(retrait);
}
}

View File

@@ -17,11 +17,12 @@ public class Article {
int Utilisateur;
String pseudoUtilisateur;
int numCategorie;
boolean isDelete;
public Article() {
}
public Article(int id, String nom, String desc, MultipartFile photo, Date dateDebutEnch, Date dateFinEnch, float prixInitial, float prixVente, int Utilisateur, String pseudoUtilisateur, int numCategorie) {
public Article(int id, String nom, String desc, MultipartFile photo, Date dateDebutEnch, Date dateFinEnch, float prixInitial, float prixVente, int Utilisateur, String pseudoUtilisateur, int numCategorie, boolean isDelete) {
setId(id);
setNom(nom);
setDesc(desc);
@@ -32,6 +33,7 @@ public class Article {
setPrixVente(prixVente);
setNoUtilisateur(Utilisateur);
setNumCategorie(numCategorie);
setIsDelete(isDelete);
}
public int getId() {
@@ -121,4 +123,12 @@ public class Article {
public void setNumCategorie(int numCategorie) {
this.numCategorie = numCategorie;
}
public boolean getIsDelete() {
return isDelete;
}
public void setIsDelete(boolean delete) {
isDelete = delete;
}
}

View File

@@ -6,6 +6,7 @@ import fr.eni.enchere.bo.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
@@ -60,7 +61,7 @@ public class ArticleController {
Article article = articleService.findArticleById(id);
UserProfil user = userService.utilisateurById(article.getUtilisateur());
Categorie cate = categorieService.findCategorieById(article.getNumCategorie());
Retrait retrait = retraitService.retraitByNumarticle(article.getId());
Retrait retrait = retraitService.findByNumArticle(article.getId());
article.setPseudoUtilisateur(user.getPseudo());
List<Enchere> lastEnchere = this.enchereService.enchereByArticle(article.getId());
@@ -86,6 +87,11 @@ public class ArticleController {
if (maxMontantEnchere.isPresent()) {
model.addAttribute("maxEnchere", maxMontantEnchere.get());
}
if (article.getId() != 0) {
model.addAttribute("imagePath", "/images/articles/" + article.getId() + ".jpg");
} else {
model.addAttribute("imagePath", "/images/articles/no-data.jpg");
}
List<ObjectError> errors = (List<ObjectError>) session.getAttribute("errors");
if (errors != null) {
model.addAttribute("errors", errors);
@@ -241,8 +247,7 @@ public class ArticleController {
@GetMapping("/edit")
public String edit(Model model, @RequestParam()int id) {
Article article = this.articleService.findArticleById(id);
Retrait retrait = this.retraitService.retraitByNumarticle(id);
System.out.println(article.getNom());
Retrait retrait = this.retraitService.findByNumArticle(id);
model.addAttribute("article", article);
model.addAttribute("retrait", retrait);
@@ -250,4 +255,126 @@ public class ArticleController {
return "editArticle";
}
@PostMapping("/edit")
public String edit(@ModelAttribute("article") Article article,
@ModelAttribute("retrait") Retrait retrait,
@RequestParam("dateDebut") String dateDebut,
@RequestParam("dateFin") String dateFin,
RedirectAttributes redirectAttributes) {
//Récupérer l'utilisateur pour set l'article
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
UserProfil userProfile = userService.utilisateurByName(username);
article.setNoUtilisateur(userProfile.getId());
//Reste de l'article
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date dDateDebut = null;
Date dDateFin = null;
try {
dDateDebut = format.parse(dateDebut);
dDateFin = format.parse(dateFin);
} catch (ParseException e) {
redirectAttributes.addAttribute("erreur", "La date de début n'est pas valide.");
redirectAttributes.addAttribute("erreur", "La date de fin n'est pas valide.");
}
article.setDateDebutEnch(dDateDebut);
article.setDateFinEnch(dDateFin);
//Vérification du formulaire
//Vérification du nom de l'article
String regex = "^[a-zA-Z0-9 ]*$";
if (article.getNom().length() < 3){
redirectAttributes.addAttribute("erreur", "Le nom de l'article doit contenir au moin 3 caractères.");
return "redirect:/article/edit?id="+article.getId();
}
if (!Pattern.matches(regex, article.getNom())){
redirectAttributes.addAttribute("erreur", "Le nom de l'article ne doit pas contenir de caractère speciaux.");
return "redirect:/article/edit?id="+article.getId();
}
//Vérification description de l'article
if (article.getDesc().length() < 20){
redirectAttributes.addAttribute("erreur", "La description de l'article doit contenir au moin 20 caractères.");
return "redirect:/article/edit?id="+article.getId();
}
//Vérification de la photo
if (article.getPhoto() != null && !article.getPhoto().isEmpty()) {
if (article.getPhoto().getSize() > 5 * 1024 * 1024) {
redirectAttributes.addAttribute("erreur", "La photo ne doit pas faire plus de 5 Mo.");
return "redirect:/article/edit?id="+article.getId();
}
if (!article.getPhoto().getOriginalFilename().toLowerCase().endsWith(".jpg")) {
redirectAttributes.addAttribute("erreur", "L'image doit avoir une extension .jpg.");
return "redirect:/article/edit?id="+article.getId();
}
}
//Vérification du prix initial
if (article.getPrixInitial() > 2000000000 && article.getPrixInitial() < 0){
redirectAttributes.addAttribute("erreur", "Le prix doit être compris entre 0 et 2 000 000 000 crédits.");
return "redirect:/article/edit?id="+article.getId();
}
//Vérifier les dates
LocalDate dateDebutEnch = LocalDate.parse(dateDebut);
LocalDate dateActuelle = LocalDate.now();
if (dateDebutEnch.isBefore(dateActuelle)) {
redirectAttributes.addAttribute("erreur", "La date de début d'enchère ne peux pas être infèrieur à la date du jour.");
return "redirect:/article/edit?id="+article.getId();
}
LocalDate dateFinEnch = LocalDate.parse(dateFin);
LocalDate datePlusUnJour = LocalDate.now().plusDays(1);
if (dateFinEnch.isBefore(datePlusUnJour)) {
redirectAttributes.addAttribute("erreur", "La date de début d'enchère ne peux pas être infàrieur à la date du jour + 1.");
return "redirect:/article/edit?id="+article.getId();
}
//Vérification rue
if (!Pattern.matches("^[a-zA-Z0-9 ]+$", retrait.getRue())){
redirectAttributes.addAttribute("erreur", "Le rue n'est pas valide.");
return "redirect:/article/edit?id="+article.getId();
}
if (retrait.getRue().isEmpty()){
redirectAttributes.addAttribute("erreur", "Entrer une rue.");
return "redirect:/article/edit?id="+article.getId();
}
//Vérifier code postal et ville
if(Pattern.matches("^\\d{5}$", retrait.getCode_postale())){
//Récupérer les villes en fonction du code postal
RestTemplate restTemplate = new RestTemplate();
List<String> villeCodePostal = new ArrayList<>(); // Initialisez la liste pour éviter les NullPointerException
String apiUrl = API_URL + retrait.getCode_postale();
ResponseEntity<JsonNode> response = restTemplate.getForEntity(apiUrl, JsonNode.class); // Désérialiser en JsonNode
if (response.getStatusCode().is2xxSuccessful()) {
JsonNode responseBody = response.getBody();
if (responseBody.isArray()) { // Vérifiez si le corps de la réponse est un tableau JSON
for (JsonNode node : responseBody) {
String cityName = node.get("nomCommune").asText();
villeCodePostal.add(cityName);
}
} else {
redirectAttributes.addAttribute("erreur", "Une erreur est survenue !");
return "redirect:/article/edit?id="+article.getId();
}
if (!villeCodePostal.contains(userProfile.getVille())) {
String showCity = String.join(", ", villeCodePostal);
redirectAttributes.addAttribute("erreur", "Essayer : " + showCity);
return "redirect:/article/edit?id="+article.getId();
}
} else {
redirectAttributes.addAttribute("erreur", "La ville n'est pas valide.");
return "redirect:/article/edit?id="+article.getId();
}
} else {
redirectAttributes.addAttribute("erreur", "Le code postal n'est pas valide.");
return "redirect:/article/edit?id="+article.getId();
}
//Validation du formulaire
retrait.setNumArticle(articleService.updateArticle(article));
retraitService.updateRetrait(retrait);
return "redirect:/accueil";
}
@PostMapping("/delete")
public String delte(@ModelAttribute("article") Article article) {
article.setIsDelete(true);
return "";
}
}

View File

@@ -14,5 +14,5 @@ public interface ArticleRepository {
List<Article> findArticleByTitle(String title);
int saveArticle(Article article);
void deleteArticle(int id);
void updateArticle(int id);
int updateArticle(Article article);
}

View File

@@ -54,6 +54,7 @@ public class ArticleRepositoryImpl implements ArticleRepository {
article.setPrixVente(rs.getFloat("a.prix_vente"));
article.setNoUtilisateur(rs.getInt("a.no_utilisateur"));
article.setNumCategorie(rs.getInt("a.no_categorie"));
article.setIsDelete(rs.getBoolean("a.isDelete"));
return article;
}
}
@@ -84,7 +85,7 @@ public class ArticleRepositoryImpl implements ArticleRepository {
@Override
public List<Article> findAllArticle() {
String sql = "SELECT * FROM ARTICLES_VENDUS a";
String sql = "SELECT * FROM ARTICLES_VENDUS a WHERE a.isDelete = 0";
List<Article> articles = jdbcTemplate.query(sql, new ArticleRowMapper());
return articles;
}
@@ -168,7 +169,6 @@ public class ArticleRepositoryImpl implements ArticleRepository {
sql.append(")");
}
System.out.println();
// Compte le nombre total d'articles
int totalCount = countArticlePageable(critere);
@@ -278,7 +278,7 @@ public class ArticleRepositoryImpl implements ArticleRepository {
@Override
public List<Article> findArticleByTitle(String title) {
String sql = "SELECT * FROM ARTICLES_VENDUS a WHERE nom_article LIKE ?";
String sql = "SELECT * FROM ARTICLES_VENDUS a WHERE nom_article LIKE ? AND a.isDelete = 0";
List<Article> articles = jdbcTemplate.query(sql, new ArticleRowMapper(), "%" + title + "%");
return articles;
}
@@ -334,7 +334,16 @@ public class ArticleRepositoryImpl implements ArticleRepository {
}
@Override
public void updateArticle(int id) {
public int updateArticle(Article article) {
String sql = "UPDATE ARTICLES_VENDUS " +
"SET nom_article = ?, " +
"description = ?," +
"date_debut_encheres = ?," +
"date_fin_encheres = ?," +
"prix_initial = ?," +
"no_categorie = ? " +
"WHERE no_article = ?";
jdbcTemplate.update(sql, article.getNom(), article.getDesc(), article.getDateDebutEnch(), article.getDateFinEnch(), article.getPrixInitial(), article.getNumCategorie(), article.getId());
return article.getId();
}
}

View File

@@ -4,5 +4,7 @@ import fr.eni.enchere.bo.Retrait;
public interface RetraitRepository {
Retrait findById(int id);
Retrait findByNumArticle(int idArticle);
void save(Retrait retrait);
void update(Retrait retrait);
}

View File

@@ -3,12 +3,16 @@ package fr.eni.enchere.dal;
import fr.eni.enchere.bo.Retrait;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
@Repository
@Primary
public class RetraitRepositoryImpl implements RetraitRepository {
@@ -21,18 +25,41 @@ public class RetraitRepositoryImpl implements RetraitRepository {
this.namedJdbcTemplate = namedJdbcTemplate;
}
public class RetraitRowMapper implements RowMapper<Retrait> {
@Override
public Retrait mapRow(ResultSet rs, int rowNum) throws SQLException {
Retrait retrait = new Retrait();
retrait.setRue(rs.getString("rue"));
retrait.setVille(rs.getString("ville"));
retrait.setCode_postale(rs.getString("code_postal"));
retrait.setNumArticle(rs.getInt("no_article"));
return retrait;
}
}
@Override
public Retrait findById(int id) {
return null;
}
@Override
public Retrait findByNumArticle(int numArticle) {
String sql = "select * from RETRAITS where no_article = ?";
Retrait retrait = jdbcTemplate.queryForObject(sql, new RetraitRowMapper(), numArticle);
if (retrait == null) {
return null;
} else {
return retrait;
}
}
@Override
public void save(Retrait retrait) {
String sqlIsUpdate = "SELECT COUNT(*) FROM RETRAITS WHERE no_article = :numArticle";
MapSqlParameterSource parametersIsUpdate = new MapSqlParameterSource();
parametersIsUpdate.addValue("numArticle", retrait.getNumArticle());
int count = namedJdbcTemplate.queryForObject(sqlIsUpdate, parametersIsUpdate, Integer.class);
System.out.println(count);
if (count > 0) {
//Mettre à jour les informations
@@ -47,4 +74,14 @@ public class RetraitRepositoryImpl implements RetraitRepository {
namedJdbcTemplate.update(sql, parameters);
}
}
@Override
public void update(Retrait retrait) {
String sql = "UPDATE RETRAITS " +
"SET rue = ?, " +
"code_postal = ?, " +
"ville = ? " +
"WHERE no_article = ?";
jdbcTemplate.update(sql, retrait.getRue(), retrait.getCode_postale(), retrait.getVille(), retrait.getNumArticle());
}
}

View File

@@ -117,3 +117,8 @@ article.details.label.amount = Amount
article.details.button.bid = Bid
article.details.address.unknown = Unknown address
article.details.validation.amount.required = Bid amount is required.
edit.article.title = Edit my article
edit.article.update = Edit
edit.article.back = Back
edit.article.delete = Cancel my article

View File

@@ -122,4 +122,6 @@ article.details.validation.amount.required = Le montant de l'ench\u00E8re est re
edit.article.title = Modifier mon article
edit.article.update = Modifier
edit.article.back = Retour
edit.article.delete = Annuler vente

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -122,7 +122,7 @@
<div class="card shadow-sm h-100 card-article">
<div class="row g-0">
<div class="col-md-4 d-flex align-items-center justify-content-center p-3">
<img th:src="${'images/articles/' + article.id + '.jpg'}" alt="Image de l'article" class="img-fluid rounded">
<img th:src="${'images/articles/' + article.id + '.jpg'} ? ${'images/articles/' + article.id + '.jpg'} : ${'images/articles/no-data.jpg'}" alt="Image de l'article" class="img-fluid rounded">
</div>
<div class="col-md-8">
<div class="card-body d-flex flex-column ">

View File

@@ -39,6 +39,12 @@
<span th:text="${article.prixInitial}"></span>
</div>
<div class="mt-2 d-flex flex-row align-items-center justify-content-between">
<div class="mt-2 d-flex flex-row align-items-end justify-content-between">
<strong><label class="col-form-label">Dernière offre</label></strong>
<span th:text="${maxEnchere} ? ${maxEnchere} : 'Aucune offre en cours'"></span>
</div>
<div class="mt-2 d-flex flex-row align-items-end justify-content-between">
<strong><label class="col-form-label" th:text="#{article.details.label.end_date}"></label></strong>
<span th:text="${article.dateFinEnch}"></span>
</div>
@@ -57,7 +63,10 @@
</span>
<button type="submit" class="btn btn-primary" th:text="#{article.details.button.bid}"></button>
</form>
<button th:if="${isArticleCurrentUser}" type="button" class="btn btn-success"> Modifier</button>
<div class="mt-5 d-flex justify-content-end align-items-center">
<a class="btn btn-secondary mr-2" href="/accueil" th:text="#{edit.article.back}"></a>
<a th:if="${#strings.equals(user.getPseudo(), article.pseudoUtilisateur)} and ${#dates.format(article.dateDebutEnch, 'yyyy-MM-dd')} > ${#dates.format(#dates.createNow(), 'yyyy-MM-dd')}" class="btn btn-primary" th:href="@{/article/edit(id=${article.id})}" th:text="#{edit.article.update}"></a>
</div>
</div>
</div>
<hr>

View File

@@ -7,17 +7,68 @@
<body>
<div id="container-main" class="container mt-5">
<h1 th:text="#{edit.article.title}"></h1>
<form th:action="@{/article/new}" th:object="${article}">
<form th:action="@{/article/edit}" method="post" th:object="${article}">
<!-- Titre article-->
<div class="mb-3">
<label for="nom" class="form-label">Titre</label>
<input type="hidden" id="id" name="id" th:field="*{id}">
<strong><label for="nom" class="form-label">Titre</label></strong>
<input type="text" class="form-control" th:field="*{nom}" id="nom">
</div>
<!-- Description article-->
<div class="mb-3">
<label for="categorie" class="form-label">Catégorie:</label>
<strong><label for="desc" class="form-label">Description</label></strong>
<input type="text" class="form-control" th:field="*{desc}" id="desc">
</div>
<!-- Catégorie article-->
<div class="mb-3">
<strong><label for="categorie" class="form-label">Catégorie:</label></strong>
<select class="form-control" th:field="*{numCategorie}" id="categorie" required>
<option th:each="categorie : ${categories}" th:value="${categorie.id}" th:text="${categorie.libelle}"></option>
</select>
<div class="invalid-feedback">Veuillez sélectionner une catégorie.</div>
</div>
<!-- Photo article-->
<div class="mb-3">
<label for="photo" class="form-label" th:text="#{article.add.form.label.photo}">Photo de l'article:</label>
<input type="file" class="form-control" id="photo" accept="image/jpeg">
</div>
<!-- Prix de l'article-->
<div class="mb-3">
<strong><label for="price" class="form-label">Prix initial</label></strong>
<input type="text" class="form-control" th:field="*{prixInitial}" id="price">
</div>
<!-- Date début enchère-->
<div class="mb-3">
<strong><label for="dateDebut" class="form-label">Date début d'enchère</label></strong>
<input type="date" class="form-control" th:value="*{dateDebutEnch}" id="dateDebut" name="dateDebut">
</div>
<!-- Date fin enchère-->
<div class="mb-3">
<strong><label for="dateFin" class="form-label">Date fin d'enchère</label></strong>
<input type="date" class="form-control" th:value="*{dateFinEnch}" id="dateFin" name="dateFin">
</div>
<!-- Retrait-->
<h4 th:text="#{article.add.form.label.removal}">Retrait</h4>
<div th:object="${retrait}">
<!-- Rue-->
<div class="mb-3">
<strong><label for="street" class="form-label">Rue</label></strong>
<input type="text" class="form-control" th:field="*{rue}" id="street">
</div>
<!-- Code postal-->
<div class="mb-3">
<strong><label for="cp" class="form-label">Code postal</label></strong>
<input type="text" class="form-control" th:field="*{code_postale}" id="cp">
</div>
<!-- Ville-->
<div class="mb-3">
<strong><label for="city" class="form-label">Ville</label></strong>
<input type="text" class="form-control" th:field="*{ville}" id="city">
</div>
</div>
<div class="d-flex align-items-center">
<a class="btn btn-danger justify-content-start" th:href="@{/article/delete(id=*{id})}" th:text="#{edit.article.delete}"></a>
<a class="btn btn-secondary justify-content-end" th:href="@{/article/show(id=*{id})}" th:text="#{edit.profil.button.cancel}"></a>
<button type="submit" class="btn btn-primary border-right ml-2 justify-content-end" th:text="#{edit.profil.button.edit}"></button>
</div>
</form>
</div>