Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision

Target

Select target project
  • m23cheri/jobmgmnt
1 result
Select Git revision
Show changes
Commits on Source (8)
Showing
with 943 additions and 642 deletions
# JobMngmnt
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.imt-atlantique.fr/m23cheri/jobmngmnt.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.imt-atlantique.fr/m23cheri/jobmngmnt/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
......@@ -30,6 +30,7 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
......
package fr.atlantique.imt.inf211.jobmngt.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import fr.atlantique.imt.inf211.jobmngt.converter.QualificationLevelConverter;
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final QualificationLevelConverter qualificationLevelConverter;
public WebConfig(QualificationLevelConverter qualificationLevelConverter) {
this.qualificationLevelConverter = qualificationLevelConverter;
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(qualificationLevelConverter);
}
}
package fr.atlantique.imt.inf211.jobmngt.controller;
import fr.atlantique.imt.inf211.jobmngt.entity.Application;
import fr.atlantique.imt.inf211.jobmngt.service.ApplicationService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.List;
import fr.atlantique.imt.inf211.jobmngt.entity.Application;
import fr.atlantique.imt.inf211.jobmngt.entity.Candidate;
import fr.atlantique.imt.inf211.jobmngt.entity.QualificationLevel;
import fr.atlantique.imt.inf211.jobmngt.entity.Sector;
import fr.atlantique.imt.inf211.jobmngt.service.ApplicationService;
import fr.atlantique.imt.inf211.jobmngt.service.CandidateService;
import fr.atlantique.imt.inf211.jobmngt.service.QualificationLevelService;
import fr.atlantique.imt.inf211.jobmngt.service.SectorService;
import jakarta.servlet.http.HttpSession;
@Controller
@RequestMapping("/applications")
public class ApplicationController {
private static final Logger logger = Logger.getLogger(ApplicationController.class.getName());
@Autowired
private ApplicationService applicationService;
@GetMapping
public String redirectToApplicationList() {
return "redirect:/applications/list";
@Autowired
private CandidateService candidateService;
@Autowired
private QualificationLevelService qualificationLevelService;
@Autowired
private SectorService sectorService;
/**
* Affiche le formulaire de candidature.
*/
@GetMapping("/apply")
public String showApplicationForm(HttpSession session, Model model) {
Integer userId = (Integer) session.getAttribute("uid");
if (userId == null) {
model.addAttribute("error", "Vous devez être connecté pour postuler.");
return "redirect:/login";
}
Optional<Candidate> candidateOpt = candidateService.findById(userId);
if (candidateOpt.isEmpty()) {
model.addAttribute("error", "Utilisateur non trouvé.");
return "error";
}
Candidate candidate = candidateOpt.get();
List<QualificationLevel> qualifications = qualificationLevelService.getAllQualificationLevels();
List<Sector> sectors = sectorService.getAllSectors();
model.addAttribute("application", new Application());
model.addAttribute("candidate", candidate);
model.addAttribute("qualifications", qualifications);
model.addAttribute("sectors", sectors);
return "application/apply";
}
/**
* Enregistre une candidature et redirige vers la page de confirmation.
*/
@PostMapping("/apply")
public String submitApplication(
@RequestParam("cv") String cv,
@RequestParam("qualificationLevel") int qualificationLevelId,
@RequestParam("sectors") List<Integer> sectorIds,
HttpSession session,
RedirectAttributes redirectAttributes) {
Integer userId = (Integer) session.getAttribute("uid");
if (userId == null) {
return "redirect:/login?error=Vous devez être connecté pour postuler.";
}
Optional<Candidate> candidateOpt = candidateService.findById(userId);
if (candidateOpt.isEmpty()) {
redirectAttributes.addFlashAttribute("error", "Utilisateur non trouvé.");
return "redirect:/error";
}
Candidate candidate = candidateOpt.get();
Optional<QualificationLevel> qualificationLevelOpt = qualificationLevelService.findById(qualificationLevelId);
if (qualificationLevelOpt.isEmpty()) {
redirectAttributes.addFlashAttribute("error", "Niveau de qualification non trouvé.");
return "redirect:/error";
}
QualificationLevel qualificationLevel = qualificationLevelOpt.get();
List<Sector> sectors = sectorService.getSectorsByIds(sectorIds);
if (sectors.isEmpty()) {
redirectAttributes.addFlashAttribute("error", "Vous devez sélectionner au moins un secteur.");
return "redirect:/error";
}
Application application = new Application();
application.setCandidate(candidate);
application.setCv(cv);
application.setQualificationlevel(qualificationLevel);
application.setSectors(sectors);
application.setAppdate(LocalDateTime.now());
Application savedApplication = applicationService.save(application);
// Stocke uniquement l'ID en session
session.setAttribute("lastApplicationId", savedApplication.getId());
return "redirect:/applications/confirmation";
}
/**
* Affiche la page de confirmation avec les détails de la candidature.
*/
@GetMapping("/confirmation")
public String showConfirmationPage(Model model, HttpSession session) {
Integer lastApplicationId = (Integer) session.getAttribute("lastApplicationId");
if (lastApplicationId == null) {
System.out.println(" Aucun ID de candidature enregistré.");
return "redirect:/error";
}
Optional<Application> applicationOpt = applicationService.findById(lastApplicationId);
if (applicationOpt.isEmpty()) {
System.out.println(" Aucune candidature trouvée en base de données !");
return "redirect:/error";
}
Application application = applicationOpt.get();
// Vérifier si l'objet a bien été récupéré
System.out.println(" Candidature trouvée : " + application.getId());
System.out.println(" CV : " + application.getCv());
System.out.println(" Qualification : " + (application.getQualificationlevel() != null ? application.getQualificationlevel().getLabel() : "NULL"));
System.out.println(" Secteurs : " + (application.getSectors() != null ? application.getSectors().size() : "NULL"));
System.out.println(" Date : " + application.getAppdate());
model.addAttribute("application", application);
return "application/application-confirmation";
}
// Affichage de la liste des candidatures
@GetMapping("/list")
public String listApplications(Model model) {
List<Application> applications = applicationService.getAllApplications();
model.addAttribute("applications", applications);
if (applications.isEmpty()) {
model.addAttribute("error", "Aucune candidature trouvée.");
}
model.addAttribute("applicationsList", applications); // Renommage de la variable
return "application/application-list";
}
/**
* Affiche les détails de la candidature.
*/
@GetMapping("/details/{id}")
public String showApplicationDetails(@PathVariable int id, Model model) {
Optional<Application> applicationOpt = applicationService.findById(id);
if (applicationOpt.isEmpty()) {
model.addAttribute("error", "Candidature non trouvée.");
return "error"; // Page d'erreur si l'application n'est pas trouvée
}
Application application = applicationOpt.get();
model.addAttribute("application", application);
return "application/application-details";
}
// suprimer et update candidature
@GetMapping("/edit/{id}")
public String showEditForm(@PathVariable int id, Model model, HttpSession session) {
Integer userId = (Integer) session.getAttribute("uid");
if (userId == null) {
return "redirect:/login"; // Rediriger vers login si non connecté
}
Optional<Application> applicationOpt = applicationService.findById(id);
if (applicationOpt.isEmpty()) {
model.addAttribute("error", "Candidature non trouvée.");
return "error";
}
Application application = applicationOpt.get();
// Vérification si l'utilisateur est bien le propriétaire
if (application.getCandidate().getId() != userId) {
model.addAttribute("error", "Vous ne pouvez modifier que vos propres candidatures.");
return "error";
}
List<QualificationLevel> qualifications = qualificationLevelService.getAllQualificationLevels();
List<Sector> sectors = sectorService.getAllSectors();
model.addAttribute("application", application);
model.addAttribute("qualifications", qualifications);
model.addAttribute("sectors", sectors);
return "application/application-edit";
}
/**
* Traite la modification d'une candidature
*/
@PostMapping("/update")
public String updateApplication(
@RequestParam("id") int id,
@RequestParam("cv") String cv,
@RequestParam("qualificationLevel") int qualificationLevelId,
@RequestParam("sectors") List<Integer> sectorIds,
RedirectAttributes redirectAttributes) {
Optional<Application> applicationOpt = applicationService.findById(id);
if (applicationOpt.isEmpty()) {
redirectAttributes.addFlashAttribute("error", "Candidature non trouvée.");
return "redirect:/applications/list";
}
Application application = applicationOpt.get();
application.setCv(cv);
Optional<QualificationLevel> qualificationLevelOpt = qualificationLevelService.findById(qualificationLevelId);
if (qualificationLevelOpt.isPresent()) {
application.setQualificationlevel(qualificationLevelOpt.get());
}
List<Sector> sectors = sectorService.getSectorsByIds(sectorIds);
application.setSectors(sectors);
applicationService.save(application);
redirectAttributes.addFlashAttribute("success", "Candidature mise à jour avec succès.");
return "redirect:/applications/list";
}
/**
* Suppression d'une candidature
*/
@GetMapping("/delete/{id}")
public String deleteApplication(@PathVariable int id, RedirectAttributes redirectAttributes, HttpSession session) {
Integer userId = (Integer) session.getAttribute("uid");
if (userId == null) {
return "redirect:/login";
}
Optional<Application> applicationOpt = applicationService.findById(id);
if (applicationOpt.isEmpty()) {
redirectAttributes.addFlashAttribute("error", "Candidature non trouvée.");
return "redirect:/applications/list";
}
Application application = applicationOpt.get();
// Vérification que le candidat est bien le propriétaire
if (application.getCandidate().getId() != userId) {
redirectAttributes.addFlashAttribute("error", "Vous n'avez pas l'autorisation de supprimer cette candidature.");
return "redirect:/applications/list";
}
applicationService.delete(id);
redirectAttributes.addFlashAttribute("success", "Candidature supprimée avec succès.");
return "redirect:/applications/list";
}
}
\ No newline at end of file
package fr.atlantique.imt.inf211.jobmngt.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
//import org.hibernate.mapping.List;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
......@@ -24,7 +23,8 @@ public class CandidateController {
private CandidateService candidateService;
@GetMapping("/signup")
public String showSignupForm() {
public String showSignupForm(Model model) {
model.addAttribute("candidate", new Candidate());
return "candidate/signupCandidate";
}
......@@ -34,100 +34,95 @@ public class CandidateController {
@RequestParam String lastname,
@RequestParam String firstname,
@RequestParam String city) {
// Vérifier si l'email existe déjà
Optional<Candidate> existingCandidate = candidateService.findByMail(mail);
if (existingCandidate.isPresent()) {
ModelAndView mav = new ModelAndView("candidate/signup");
mav.addObject("error", "Email already exists. Please use another email.");
return mav;
}
// Vérifier si le mot de passe est assez long
if (password.length() < 4) {
ModelAndView mav = new ModelAndView("candidate/signup");
mav.addObject("error", "Password must be at least 4 characters long.");
boolean isRegistered = candidateService.registerCandidate(new Candidate(mail, password, city, lastname, firstname));
if (!isRegistered) {
ModelAndView mav = new ModelAndView("candidate/signupCandidate");
mav.addObject("error", "This email is already registered. Please use another one.");
return mav;
}
// Création du candidat et enregistrement
Candidate candidate = new Candidate(mail, password, city, lastname, firstname);
candidateService.registerCandidate(candidate);
// Redirection vers la page de confirmation
// Redirection vers confirmation avec un message spécifique
ModelAndView mav = new ModelAndView("candidate/confirmation");
mav.addObject("message", "Your account has been successfully created!");
return mav;
}
@GetMapping("/list")
public String listCandidates(Model model) {
List<Candidate> candidates = candidateService.getAllCandidates();
model.addAttribute("candidates", candidates);
return "candidate/candidates-list";
}
@GetMapping
@GetMapping
public String redirectToList() {
return "redirect:/candidates/list";
}
@GetMapping("/details/{id}")
public String getCandidateDetails(@PathVariable int id, Model model) {
Candidate candidate = candidateService.getCandidateById(id);
if (candidate == null) {
model.addAttribute("error", "Le candidat n'existe pas.");
return "error";
}
model.addAttribute("candidate", candidate);
return "candidate/details";
}
@GetMapping("/edit/{id}")
public String showEditForm(@PathVariable int id, Model model) {
Candidate candidate = candidateService.getCandidateById(id);
if (candidate == null) {
model.addAttribute("error", "Le candidat n'existe pas.");
return "error";
public String getCandidateDetails(@PathVariable int id, Model model) {
Candidate candidate = candidateService.getCandidateById(id);
if (candidate == null) {
model.addAttribute("error", "Le candidat n'existe pas.");
return "error";
}
model.addAttribute("candidate", candidate);
return "candidate/details";
}
model.addAttribute("candidate", candidate);
return "candidate/editCandidate";
}
@PostMapping("/edit")
public String updateCandidate(@RequestParam int id,
@RequestParam String mail,
@RequestParam String password,
@RequestParam String lastname,
@RequestParam String firstname,
@RequestParam String city,
Model model) {
Candidate candidate = candidateService.getCandidateById(id);
if (candidate == null) {
model.addAttribute("error", "Le candidat n'existe pas.");
return "error";
@GetMapping("/edit/{id}")
public String showEditForm(@PathVariable int id, Model model) {
Candidate candidate = candidateService.getCandidateById(id);
if (candidate == null) {
model.addAttribute("error", "Le candidat n'existe pas.");
return "error";
}
model.addAttribute("candidate", candidate);
return "candidate/editCandidate";
}
candidate.setMail(mail);
candidate.setPassword(password);
candidate.setLastname(lastname);
candidate.setFirstname(firstname);
candidate.setCity(city);
candidateService.updateCandidate(candidate);
model.addAttribute("message", "Candidat mis à jour avec succès !");
return "candidate/confirmation";
}
@GetMapping("/delete/{id}")
public String deleteCandidate(@PathVariable int id, Model model) {
Candidate candidate = candidateService.getCandidateById(id);
if (candidate == null) {
model.addAttribute("error", "Le candidat n'existe pas.");
return "error";
@PostMapping("/edit")
public String updateCandidate(@RequestParam int id,
@RequestParam String password,
@RequestParam String lastname,
@RequestParam String firstname,
@RequestParam String city,
Model model) {
Candidate candidate = candidateService.getCandidateById(id);
if (candidate == null) {
model.addAttribute("error", "Le candidat n'existe pas.");
return "error";
}
candidate.setPassword(password);
candidate.setLastname(lastname);
candidate.setFirstname(firstname);
candidate.setCity(city);
candidateService.updateCandidate(candidate);
// Envoie l’objet candidat pour l’afficher après modification
model.addAttribute("message", "Candidat mis à jour avec succès !");
model.addAttribute("candidate", candidate);
return "candidate/confirmation";
}
@GetMapping("/delete/{id}")
public String deleteCandidate(@PathVariable int id, Model model) {
Candidate candidate = candidateService.getCandidateById(id);
if (candidate == null) {
model.addAttribute("error", "Le candidat avec l'ID " + id + " n'existe pas.");
return "error"; // Affiche une page d'erreur si le candidat n'existe pas
}
candidateService.deleteCandidate(id);
// Rediriger vers la liste avec un message de confirmation
model.addAttribute("message", "Le candidat " + candidate.getFirstname() + " " + candidate.getLastname() + " a été supprimé avec succès !");
return "candidate/confirmationSupp"; // Affichage de la confirmation après suppression
}
candidateService.deleteCandidate(id);
model.addAttribute("message", "Le candidat a été supprimé avec succès !");
return "candidate/confirmation";
}
}
\ No newline at end of file
package fr.atlantique.imt.inf211.jobmngt.controller;
import java.util.HashSet;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import fr.atlantique.imt.inf211.jobmngt.entity.Company;
import fr.atlantique.imt.inf211.jobmngt.service.CompanyService;
@Controller
public class CompanyController {
@Autowired
private CompanyService companyService;
public CompanyController(CompanyService companyService) {
this.companyService = companyService;
}
// Affiche le formulaire d'inscription
@GetMapping("/companies/create")
public String showCreateForm(Model model) {
Company company = new Company();
company.setJobOffers(new HashSet<>());
model.addAttribute("company", company);
return "company/companyForm";
}
// Affiche la liste des entreprises
@GetMapping("/companies")
public String listCompanies(Model model) {
model.addAttribute("companies", companyService.getAllCompanies());
return "company/companyList";
}
// Affiche les détails d'une entreprise
@GetMapping("/companies/view/{id}")
public String viewCompany(@PathVariable("id") int id, Model model, RedirectAttributes redirectAttributes) {
Optional<Company> companyOpt = companyService.findById(id);
if (companyOpt.isPresent()) {
model.addAttribute("company", companyOpt.get());
return "company/companyView";
} else {
redirectAttributes.addFlashAttribute("errorMessage", "❌ L'entreprise avec ID " + id + " n'existe pas !");
return "redirect:/companies";
}
}
// Enregistre une entreprise avec vérification des doublons et message de succès
@PostMapping("/companies/create")
public String registerCompany(Company company, RedirectAttributes redirectAttributes, Model model) {
Optional<Company> existingCompany = companyService.findByMail(company.getMail());
if (existingCompany.isPresent()) {
model.addAttribute("errorMessage", "❌ Une entreprise avec cet e-mail existe déjà !");
model.addAttribute("company", company);
return "company/companyForm"; // 🔹 Rester sur le formulaire en cas d'erreur
}
try {
companyService.saveCompany(company);
redirectAttributes.addFlashAttribute("successMessage", "✅ L'entreprise a été ajoutée avec succès !");
return "redirect:/companies";
} catch (Exception e) {
model.addAttribute("errorMessage", "❌ Erreur lors de l'inscription !");
model.addAttribute("company", company);
return "company/companyForm"; // 🔹 Rester sur le formulaire en cas d'erreur
}
}
// Affiche le formulaire de modification d'une entreprise
@GetMapping("/companies/{id}/edit")
public String showEditForm(@PathVariable("id") int id, Model model, RedirectAttributes redirectAttributes) {
Optional<Company> companyOpt = companyService.findById(id);
if (companyOpt.isPresent()) {
model.addAttribute("company", companyOpt.get());
return "company/companyEdit";
} else {
redirectAttributes.addFlashAttribute("errorMessage", "❌ L'entreprise avec ID " + id + " n'existe pas !");
return "redirect:/companies";
}
}
// Met à jour les informations d'une entreprise avec message de succès
@PostMapping("/companies/update")
public String updateCompany(Company company, RedirectAttributes redirectAttributes) {
try {
companyService.updateCompany(company);
redirectAttributes.addFlashAttribute("successMessage", "✅ L'entreprise a été mise à jour avec succès !");
return "redirect:/companies/view/" + company.getId();
} catch (Exception e) {
redirectAttributes.addFlashAttribute("errorMessage", "❌ Erreur lors de la mise à jour !");
return "redirect:/companies/" + company.getId() + "/edit";
}
}
// Supprime une entreprise
@GetMapping("/companies/delete/{id}")
public String deleteCompany(@PathVariable("id") int id, RedirectAttributes redirectAttributes) {
try {
companyService.deleteCompany(id);
redirectAttributes.addFlashAttribute("successMessage", "✅ Entreprise supprimée avec succès !");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("errorMessage", "❌ Erreur lors de la suppression !");
}
return "redirect:/companies";
}
}
package fr.atlantique.imt.inf211.jobmngt.controller;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import fr.atlantique.imt.inf211.jobmngt.entity.JobOffer;
import fr.atlantique.imt.inf211.jobmngt.entity.Sector;
import fr.atlantique.imt.inf211.jobmngt.service.CompanyService;
import fr.atlantique.imt.inf211.jobmngt.service.JobOfferService;
import fr.atlantique.imt.inf211.jobmngt.service.QualificationLevelService;
import fr.atlantique.imt.inf211.jobmngt.service.SectorService;
@Controller
@RequestMapping("/jobs")
public class JobOfferController {
private final JobOfferService jobOfferService;
private final CompanyService companyService;
private final QualificationLevelService qualificationLevelService;
private final SectorService sectorService;
@Autowired
public JobOfferController(JobOfferService jobOfferService,
CompanyService companyService,
QualificationLevelService qualificationLevelService,
SectorService sectorService) {
this.jobOfferService = jobOfferService;
this.companyService = companyService;
this.qualificationLevelService = qualificationLevelService;
this.sectorService = sectorService;
}
// Affiche la liste des offres d'emploi avec log
@GetMapping
public String listJobOffers(Model model) {
List<JobOffer> jobOffers = jobOfferService.getAllJobOffers();
System.out.println("🔎 Nombre d'offres récupérées: " + jobOffers.size());
model.addAttribute("jobOffers", jobOffers);
return "jobOffer/jobOfferList";
}
// Affiche les détails d'une offre
@GetMapping("/view/{id}")
public String viewJobOffer(@PathVariable("id") int id, Model model, RedirectAttributes redirectAttributes) {
Optional<JobOffer> jobOfferOpt = jobOfferService.findById(id);
if (jobOfferOpt.isPresent()) {
model.addAttribute("jobOffer", jobOfferOpt.get());
return "jobOffer/jobOfferView";
} else {
redirectAttributes.addFlashAttribute("errorMessage", "L'offre d'emploi avec ID " + id + " n'existe pas !");
return "redirect:/jobs";
}
}
// Affiche le formulaire de création avec sélection des secteurs
@GetMapping("/create")
public String showCreateForm(Model model) {
JobOffer jobOffer = new JobOffer();
jobOffer.setPublicationDate(new Date());
model.addAttribute("jobOffer", jobOffer);
model.addAttribute("companies", companyService.getAllCompanies());
model.addAttribute("qualificationLevels", qualificationLevelService.getAllQualificationLevels());
model.addAttribute("sectors", sectorService.listOfSectors());
return "jobOffer/jobOfferForm";
}
// Enregistre une offre avec gestion des secteurs et des erreurs
@PostMapping("/save")
public String saveJobOffer(@ModelAttribute JobOffer jobOffer,
@RequestParam(value = "sectorIds", required = false) List<Integer> sectorIds,
RedirectAttributes redirectAttributes) {
try {
System.out.println("🔹 Tentative d'enregistrement: " + jobOffer);
// Associer les secteurs sélectionnés à l'offre d'emploi
if (sectorIds != null && !sectorIds.isEmpty()) {
Set<Sector> selectedSectors = sectorIds.stream()
.map(id -> sectorService.findById(id.longValue()))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet()); // Convertir la liste en Set
jobOffer.setSectors(selectedSectors); // Affectation corrigée
}
jobOfferService.saveJobOffer(jobOffer);
System.out.println(" Enregistrement réussi !");
redirectAttributes.addFlashAttribute("successMessage", " Offre d'emploi créée avec succès !");
return "redirect:/jobs";
} catch (Exception e) {
System.err.println(" Erreur lors de l'enregistrement: " + e.getMessage());
redirectAttributes.addFlashAttribute("errorMessage", " Erreur lors de la création de l'offre !");
return "redirect:/jobs/create";
}
}
// Supprime une offre d'emploi
@GetMapping("/delete/{id}")
public String deleteJobOffer(@PathVariable("id") int id, RedirectAttributes redirectAttributes) {
Optional<JobOffer> jobOfferOpt = jobOfferService.findById(id);
if (jobOfferOpt.isPresent()) {
try {
jobOfferService.deleteJobOffer(id);
redirectAttributes.addFlashAttribute("successMessage", " Offre d'emploi supprimée avec succès !");
} catch (Exception e) {
redirectAttributes.addFlashAttribute("errorMessage", " Erreur lors de la suppression de l'offre !");
}
} else {
redirectAttributes.addFlashAttribute("errorMessage", " L'offre d'emploi avec ID " + id + " n'existe pas !");
}
return "redirect:/jobs";
}
// Affiche le formulaire de modification
@GetMapping("/{id}/edit")
public String showEditForm(@PathVariable("id") int id, Model model, RedirectAttributes redirectAttributes) {
Optional<JobOffer> jobOfferOpt = jobOfferService.findById(id);
if (jobOfferOpt.isPresent()) {
model.addAttribute("jobOffer", jobOfferOpt.get());
model.addAttribute("companies", companyService.getAllCompanies());
model.addAttribute("qualificationLevels", qualificationLevelService.getAllQualificationLevels());
model.addAttribute("sectors", sectorService.listOfSectors());
return "jobOffer/jobOfferForm";
} else {
redirectAttributes.addFlashAttribute("errorMessage", "L'offre d'emploi avec ID " + id + " n'existe pas !");
return "redirect:/jobs";
}
}
}
package fr.atlantique.imt.inf211.jobmngt.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.beans.factory.annotation.Autowired;
import fr.atlantique.imt.inf211.jobmngt.service.QualificationLevelService;
......@@ -18,7 +18,7 @@ public class QualificationLevelController {
public ModelAndView listOfQualificationLevels() {
ModelAndView modelAndView = new ModelAndView("qualificationLevel/qualificationLevelList");
modelAndView.addObject("qualificationlevellist", qualificationLevelService.listOfQualificationLevels());
modelAndView.addObject("qualificationlevellist", qualificationLevelService.getAllQualificationLevels());
return modelAndView;
}
......
package fr.atlantique.imt.inf211.jobmngt.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.beans.factory.annotation.Autowired;
import fr.atlantique.imt.inf211.jobmngt.service.SectorService;
......
package fr.atlantique.imt.inf211.jobmngt.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import fr.atlantique.imt.inf211.jobmngt.dao.ApplicationDao;
import fr.atlantique.imt.inf211.jobmngt.dao.CandidateDao;
import fr.atlantique.imt.inf211.jobmngt.dao.QualificationLevelDao;
import fr.atlantique.imt.inf211.jobmngt.dao.SectorDao;
import fr.atlantique.imt.inf211.jobmngt.entity.Application;
import fr.atlantique.imt.inf211.jobmngt.entity.Candidate;
import fr.atlantique.imt.inf211.jobmngt.entity.QualificationLevel;
import fr.atlantique.imt.inf211.jobmngt.entity.Sector;
@RestController
@RequestMapping("/api/applications")
public class TestApplicationDaoController {
@Autowired
private ApplicationDao applicationDao;
@Autowired
private CandidateDao candidateDao;
@Autowired
private QualificationLevelDao qualificationLevelDao;
@Autowired
private SectorDao sectorDao;
/**
* Récupérer toutes les candidatures existantes.
*/
@GetMapping("")
public List<Application> getAllApplications() {
return applicationDao.findAll("appdate", "ASC"); // Exemple de tri par date en ordre croissant
}
/**
* Créer une nouvelle candidature.
*/
@PostMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
public Application newApplication(@RequestBody Map<String, Object> payload) {
// Vérifier la présence du candidat
int candidateId = (int) payload.get("candidateId");
Candidate candidate = candidateDao.findById(candidateId);
if (candidate == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Candidat introuvable !");
}
// Vérifier le niveau de qualification
int qualificationLevelId = (int) payload.get("qualificationLevelId");
QualificationLevel qualificationLevel = qualificationLevelDao.findById(qualificationLevelId);
if (qualificationLevel == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Niveau de qualification introuvable !");
}
// Création de l'application
Application application = new Application();
application.setCv((String) payload.get("cv"));
application.setAppdate(new Date());
application.setCandidate(candidate);
application.setQualificationlevel(qualificationLevel);
// Gestion des secteurs (ajout de vérification)
Set<Sector> sectors = new HashSet<>();
if (payload.containsKey("sectors")) {
for (Map<String, Object> sectorData : (List<Map<String, Object>>) payload.get("sectors")) {
int sectorId = (int) sectorData.get("id");
Sector sector = sectorDao.findById(sectorId);
if (sector != null) {
sectors.add(sector);
}
}
}
application.setSectors(new ArrayList<>(sectors));
// Persistance de la candidature
applicationDao.persist(application);
return application;
}
/**
* Récupérer les candidatures par secteur et niveau de qualification.
*/
@GetMapping("/sector/{sector}/qualification/{qualification}")
public List<Application> findBySectorAndQualification(@PathVariable String sector, @PathVariable String qualification) {
return applicationDao.findBySectorAndQualification(sector, qualification);
}
}
package fr.atlantique.imt.inf211.jobmngt.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import fr.atlantique.imt.inf211.jobmngt.dao.CandidateDao;
import fr.atlantique.imt.inf211.jobmngt.entity.Candidate;
@RestController
@RequestMapping("/api/candidates")
public class TestCandidateDaoController {
@Autowired
private CandidateDao candidateDao;
/**
* Lister tous les candidats existants
*/
@GetMapping("")
public List<Candidate> all() {
return candidateDao.findAll();
}
/**
* Créer un nouveau candidat
*/
@PostMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
public Candidate newCandidate(@RequestBody Candidate candidate) {
candidateDao.persist(candidate);
return candidate;
}
/**
* Récupérer les informations d'un candidat par son ID
*/
@GetMapping("/{id}")
public Candidate one(@PathVariable int id) {
return candidateDao.findById(id);
}
/**
* Modifier les informations d'un candidat
*/
@PutMapping("/{id}")
public Candidate replaceCandidate(@RequestBody Candidate newCandidate, @PathVariable int id) {
Candidate candidate = candidateDao.findById(id);
if (candidate != null) {
candidate.setFirstname(newCandidate.getFirstname());
candidate.setLastname(newCandidate.getLastname());
candidate.setMail(newCandidate.getMail()); // Hérité de AppUser
candidate.setPassword(newCandidate.getPassword()); // Hérité de AppUser
candidate.setCity(newCandidate.getCity()); // Hérité de AppUser
return candidateDao.merge(candidate);
}
return null;
}
/**
* Supprimer un candidat par ID
*/
@DeleteMapping("/{id}")
public void deleteCandidate(@PathVariable int id) {
Candidate candidate = candidateDao.findById(id);
if (candidate != null) {
candidateDao.remove(candidate);
}
}
}
package fr.atlantique.imt.inf211.jobmngt.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import fr.atlantique.imt.inf211.jobmngt.dao.CompanyDao;
import fr.atlantique.imt.inf211.jobmngt.entity.Company;
@RestController
@RequestMapping("/api/companies")
public class TestCompanyDaoController {
@Autowired
private CompanyDao companyDao;
/**
* Lister toutes les entreprises existantes
*/
@GetMapping("")
public List<Company> all() {
return companyDao.findAll();
}
/**
* Créer une nouvelle entreprise
*/
@PostMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
public Company newCompany(@RequestBody Company company) {
if (company.getMail() == null || company.getPassword() == null || company.getCity() == null) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Les champs 'mail', 'password' et 'city' sont obligatoires !");
}
companyDao.persist(company);
return company;
}
/**
* Récupérer les informations d'une entreprise par ID
*/
@GetMapping("/{id}")
public Company one(@PathVariable int id) {
Company company = companyDao.findById(id);
if (company == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Entreprise non trouvée");
}
return company;
}
/**
* Modifier les informations d'une entreprise
*/
@PutMapping("/{id}")
public Company replaceCompany(@RequestBody Company newCompany, @PathVariable int id) {
Company company = companyDao.findById(id);
if (company != null) {
company.setDenomination(newCompany.getDenomination());
company.setDescription(newCompany.getDescription());
// Hérité de AppUser
company.setMail(newCompany.getMail());
company.setPassword(newCompany.getPassword());
company.setCity(newCompany.getCity());
return companyDao.merge(company);
}
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Entreprise non trouvée");
}
/**
* Supprimer une entreprise par ID
*/
@DeleteMapping("/{id}")
public void deleteCompany(@PathVariable int id) {
Company company = companyDao.findById(id);
if (company != null) {
companyDao.remove(company);
} else {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Entreprise non trouvée");
}
}
}
package fr.atlantique.imt.inf211.jobmngt.controller;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import fr.atlantique.imt.inf211.jobmngt.dao.CompanyDao;
import fr.atlantique.imt.inf211.jobmngt.dao.JobOfferDao;
import fr.atlantique.imt.inf211.jobmngt.dao.QualificationLevelDao;
import fr.atlantique.imt.inf211.jobmngt.dao.SectorDao;
import fr.atlantique.imt.inf211.jobmngt.entity.Company;
import fr.atlantique.imt.inf211.jobmngt.entity.JobOffer;
import fr.atlantique.imt.inf211.jobmngt.entity.QualificationLevel;
import fr.atlantique.imt.inf211.jobmngt.entity.Sector;
@RestController
@RequestMapping("/api/joboffers")
public class TestJobOfferDaoController {
@Autowired
private JobOfferDao jobOfferDao;
@Autowired
private CompanyDao companyDao;
@Autowired
private QualificationLevelDao qualificationLevelDao;
@Autowired
private SectorDao sectorDao;
/**
* 🔍 Récupérer toutes les offres d'emploi.
*/
@GetMapping("")
public List<JobOffer> getAllJobOffers() {
return jobOfferDao.findAll();
}
/**
* Récupérer les offres d'emploi en fonction d'un secteur et d'un niveau de qualification.
// */
@GetMapping("/sector/{sector}/qualification/{qualification}")
public List<JobOffer> findBySectorAndQualification(@PathVariable String sector, @PathVariable String qualification) {
return jobOfferDao.findBySectorAndQualification(sector, qualification);
}
/**
* 🔍 Récupérer une offre d'emploi par ID.
*/
@GetMapping("/{id}")
public JobOffer getJobOfferById(@PathVariable int id) {
JobOffer jobOffer = jobOfferDao.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Offre d'emploi introuvable !"));
if (jobOffer == null) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Offre d'emploi introuvable !");
}
return jobOffer;
}
/**
* ✨ Créer une nouvelle offre d'emploi.
*/
@PostMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
public JobOffer newJobOffer(@RequestBody Map<String, Object> payload) {
// Vérification et récupération des données
int companyId = (int) payload.get("companyId");
Company company = companyDao.findById(companyId);
if (company == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Entreprise introuvable !");
int qualificationLevelId = (int) payload.get("qualificationLevelId");
QualificationLevel qualificationLevel = qualificationLevelDao.findById(qualificationLevelId);
if (qualificationLevel == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Niveau de qualification introuvable !");
JobOffer jobOffer = new JobOffer();
jobOffer.setCompany(company);
jobOffer.setQualificationLevel(qualificationLevel);
jobOffer.setTitle((String) payload.get("title"));
jobOffer.setTaskDescription((String) payload.get("taskDescription"));
jobOffer.setPublicationDate(new Date());
// Gestion des secteurs
Set<Sector> sectors = new HashSet<>();
for (Map<String, Object> sectorData : (List<Map<String, Object>>) payload.get("sectors")) {
int sectorId = (int) sectorData.get("id");
Sector sector = sectorDao.findById(sectorId);
if (sector == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Secteur introuvable avec ID: " + sectorId);
sectors.add(sector);
}
jobOffer.setSectors(sectors);
return jobOfferDao.save(jobOffer);
}
@DeleteMapping("/{id}")
public void deleteJobOffer(@PathVariable int id) {
if (!jobOfferDao.existsById(id)) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Offre d'emploi introuvable !");
}
jobOfferDao.deleteById(id);
}
}
package fr.atlantique.imt.inf211.jobmngt.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import fr.atlantique.imt.inf211.jobmngt.entity.Company;
import fr.atlantique.imt.inf211.jobmngt.service.CompanyService;
@Component // Indique que c'est un bean Spring
public class CompanyConverter implements Converter<String, Company> {
private final CompanyService companyService;
public CompanyConverter(CompanyService companyService) {
this.companyService = companyService;
}
@Override
public Company convert(String source) {
if (source == null || source.isEmpty()) {
return null;
}
return companyService.findById(Integer.parseInt(source)).orElse(null);
}
}
package fr.atlantique.imt.inf211.jobmngt.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import fr.atlantique.imt.inf211.jobmngt.entity.QualificationLevel;
import fr.atlantique.imt.inf211.jobmngt.service.QualificationLevelService;
import java.util.Optional;
@Component
public class QualificationLevelConverter implements Converter<String, QualificationLevel> {
private final QualificationLevelService qualificationLevelService;
public QualificationLevelConverter(QualificationLevelService qualificationLevelService) {
this.qualificationLevelService = qualificationLevelService;
}
@Override
public QualificationLevel convert(String id) {
try {
int parsedId = Integer.parseInt(id);
Optional<QualificationLevel> qualificationLevelOpt = qualificationLevelService.findById(parsedId);
return qualificationLevelOpt.orElse(null); // Renvoie `null` si introuvable (géré en amont)
} catch (NumberFormatException e) {
return null; // Gestion d'une conversion invalide
}
}
}
package fr.atlantique.imt.inf211.jobmngt.dao;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
......@@ -12,9 +13,6 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.TypedQuery;
/**
* DAO pour l'entité Application.
*/
@Repository
public class ApplicationDao {
......@@ -29,11 +27,13 @@ public class ApplicationDao {
entityManager.persist(transientInstance);
}
@Transactional
public void remove(Application persistentInstance) {
logger.log(Level.INFO, "Removing Application instance");
entityManager.remove(persistentInstance);
}
@Transactional
public void remove(Application application) {
logger.log(Level.INFO, "Removing Application instance");
if (application != null) {
entityManager.remove(entityManager.contains(application) ? application : entityManager.merge(application));
}
}
@Transactional
public Application merge(Application detachedInstance) {
......@@ -42,49 +42,16 @@ public class ApplicationDao {
}
@Transactional(readOnly = true)
public Application findById(int id) {
return entityManager.find(Application.class, id);
}
/*
* Retourne toutes les applications triées par un champ et un ordre spécifié.
*/
@Transactional(readOnly = true)
public List<Application> findAll(String sort, String order) {
logger.log(Level.INFO, "Fetching all applications sorted by " + sort + " in " + order + " order");
String jpql = "SELECT a FROM Application a ORDER BY a." + sort + " " +
(order.equalsIgnoreCase("asc") ? "ASC" : "DESC");
TypedQuery<Application> query = entityManager.createQuery(jpql, Application.class);
return query.getResultList();
}
public Optional<Application> findById(int id) {
return Optional.ofNullable(entityManager.find(Application.class, id));
}
/**
* Récupère les candidatures en fonction d'un secteur d'activité et d'un niveau de qualification donné.
*/
@Transactional(readOnly = true)
public List<Application> findBySectorAndQualification(String sectorLabel, String qualificationLevel) {
logger.log(Level.INFO, "Fetching applications for sector: " + sectorLabel + " and qualification level: " + qualificationLevel);
String jpql = "SELECT a FROM Application a " +
"JOIN a.sectors s " +
"WHERE s.label = :sectorLabel " +
"AND a.qualificationlevel.label = :qualificationLevel"; // 🛠 Correction ici
TypedQuery<Application> query = entityManager.createQuery(jpql, Application.class);
query.setParameter("sectorLabel", sectorLabel);
query.setParameter("qualificationLevel", qualificationLevel);
public List<Application> findAll() {
logger.log(Level.INFO, "Fetching all applications");
TypedQuery<Application> query = entityManager.createQuery("SELECT a FROM Application a ORDER BY a.appdate DESC", Application.class);
return query.getResultList();
}
@Transactional(readOnly = true)
public List<Application> findAll() {
logger.log(Level.INFO, "Fetching all applications");
String jpql = "SELECT a FROM Application a ORDER BY a.appdate DESC";
TypedQuery<Application> query = entityManager.createQuery(jpql, Application.class);
return query.getResultList();
}
}
......@@ -94,3 +61,4 @@ public List<Application> findAll() {
package fr.atlantique.imt.inf211.jobmngt.dao;
// Generated 3 mars 2025, 13:07:58 by Hibernate Tools 5.6.15.Final
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import fr.atlantique.imt.inf211.jobmngt.entity.Candidate;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
/**
* Home object for domain model class Candidate.
* @see .Candidate
* @author Hibernate Tools
*/
@Repository
public class CandidateDao {
private static final Logger logger = Logger.getLogger(CandidateDao.class.getName());
@PersistenceContext
private EntityManager entityManager;
@PersistenceContext private EntityManager entityManager;
@Transactional
public void persist(Candidate transientInstance) {
logger.log(Level.INFO, "persisting Candidate instance");
try {
entityManager.persist(transientInstance);
logger.log(Level.INFO, "persist successful");
}
catch (RuntimeException re) {
logger.log(Level.SEVERE, "persist failed", re);
throw re;
}
public void persist(Candidate candidate) {
entityManager.persist(candidate);
}
@Transactional
public void remove(Candidate persistentInstance) {
logger.log(Level.INFO, "removing Candidate instance");
try {
entityManager.remove(persistentInstance);
logger.log(Level.INFO, "remove successful");
}
catch (RuntimeException re) {
logger.log(Level.SEVERE, "remove failed", re);
throw re;
}
public void remove(Candidate candidate) {
entityManager.remove(candidate);
}
@Transactional
public Candidate merge(Candidate detachedInstance) {
logger.log(Level.INFO, "merging Candidate instance");
try {
Candidate result = entityManager.merge(detachedInstance);
logger.log(Level.INFO, "merge successful");
return result;
}
catch (RuntimeException re) {
logger.log(Level.SEVERE, "merge failed", re);
throw re;
}
public Candidate merge(Candidate candidate) {
return entityManager.merge(candidate);
}
@Transactional(readOnly = true)
public List<Candidate> findAll() {
return entityManager.createQuery("SELECT c FROM Candidate c", Candidate.class).getResultList();
}
@Transactional
public Candidate findById( int id) {
logger.log(Level.INFO, "getting Candidate instance with id: " + id);
try {
Candidate instance = entityManager.find(Candidate.class, id);
logger.log(Level.INFO, "get successful");
return instance;
}
catch (RuntimeException re) {
logger.log(Level.SEVERE, "get failed", re);
throw re;
}
public Candidate findById(int id) {
return entityManager.find(Candidate.class, id);
}
@Transactional(readOnly = true)
@Transactional(readOnly = true)
public Optional<Candidate> findByMail(String mail) {
TypedQuery<Candidate> query = entityManager.createQuery(
"SELECT c FROM Candidate c WHERE c.mail = :mail", Candidate.class);
query.setParameter("mail", mail);
List<Candidate> result = query.getResultList();
return result.isEmpty() ? Optional.empty() : Optional.of(result.get(0));
return query.getResultStream().findFirst();
}
@Transactional
public void deleteById(int id) {
Candidate candidate = findById(id);
if (candidate != null) {
entityManager.remove(candidate);
}
@Transactional
public void deleteById(int id) {
Candidate candidate = findById(id);
if (candidate != null) {
entityManager.remove(candidate);
}
}
}
@Transactional(readOnly = true)
public List<Candidate> findAll() {
return entityManager.createQuery("SELECT c FROM Candidate c", Candidate.class).getResultList();
}
}
package fr.atlantique.imt.inf211.jobmngt.dao;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
......@@ -45,12 +46,86 @@ public class CompanyDao {
return entityManager.createQuery("SELECT c FROM Company c", Company.class).getResultList();
}
@Transactional(readOnly = true)
public Optional<Company> findById(int id) {
return Optional.ofNullable(entityManager.find(Company.class, id));
}
@Transactional
public void remove(int id) {
Company company = findById(id).orElseThrow(() ->
new RuntimeException("Impossible de supprimer : l'entreprise avec ID " + id + " n'existe pas."));
entityManager.remove(company);
}
public Company findById(int id) {
logger.log(Level.INFO, "Getting Company instance with id: " + id);
return entityManager.find(Company.class, id);
@Transactional(readOnly = true)
public Optional<Company> findByMail(String mail) {
List<Company> result = entityManager.createQuery(
"SELECT c FROM Company c WHERE c.mail = :mail", Company.class)
.setParameter("mail", mail)
.getResultList();
return result.isEmpty() ? Optional.empty() : Optional.of(result.get(0));
}
public void save(Company company) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'save'");
}
}
// package fr.atlantique.imt.inf211.jobmngt.dao;
// import java.util.List;
// import java.util.Optional;
// import org.springframework.stereotype.Repository;
// import org.springframework.transaction.annotation.Transactional;
// import fr.atlantique.imt.inf211.jobmngt.entity.Company;
// import jakarta.persistence.EntityManager;
// import jakarta.persistence.PersistenceContext;
// @Repository
// public class CompanyDao {
// @PersistenceContext
// private EntityManager entityManager;
// @Transactional
// public Company save(Company company) {
// if (company.getId() == 0) {
// entityManager.persist(company);
// return company;
// } else {
// return entityManager.merge(company);
// }
// }
// @Transactional
// public void remove(int id) {
// Company company = findById(id).orElseThrow(() ->
// new RuntimeException("Impossible de supprimer l'entreprise avec ID " + id));
// entityManager.remove(company);
// }
// @Transactional(readOnly = true)
// public List<Company> findAll() {
// return entityManager.createQuery("SELECT c FROM Company c", Company.class).getResultList();
// }
// @Transactional(readOnly = true)
// public Optional<Company> findById(int id) {
// return Optional.ofNullable(entityManager.find(Company.class, id));
// }
// }
......@@ -3,7 +3,7 @@ package fr.atlantique.imt.inf211.jobmngt.dao;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
......
......@@ -39,9 +39,9 @@ public class SectorDao {
}
@Transactional(readOnly = true)
public Sector findById(int id) {
logger.log(Level.INFO, "Fetching Sector instance with ID: " + id);
return entityManager.find(Sector.class, id);
public Sector findById(Object id) {
logger.log(Level.INFO, "Fetching Sector instance with ID: " + id);
return entityManager.find(Sector.class, id);
}
@Transactional(readOnly = true)
......@@ -51,13 +51,18 @@ public class SectorDao {
return entityManager.createQuery(query, Long.class).getSingleResult();
}
@Transactional(readOnly = true)
public List<Sector> findAll(String sort, String order) {
logger.log(Level.INFO, "Fetching all sectors sorted by " + sort + " in " + order + " order");
String query = "SELECT s FROM Sector s ORDER BY s." + sort + " " + (order.equalsIgnoreCase("asc") ? "ASC" : "DESC");
return entityManager.createQuery(query, Sector.class).getResultList();
if (order == null || (!order.equalsIgnoreCase("ASC") && !order.equalsIgnoreCase("DESC"))) {
order = "ASC"; // Définit une valeur par défaut si `order` est null
}
// Ici, utilisez `sort` pour définir la colonne par défaut si nécessaire
String sortColumn = (sort != null) ? sort : "id";
return entityManager.createQuery("SELECT s FROM Sector s ORDER BY s." + sortColumn + " " + order, Sector.class)
.getResultList();
}
/**
* Nouvelle méthode : Récupérer les secteurs ayant un label donné.
*/
......@@ -72,4 +77,18 @@ public class SectorDao {
return query.getResultList();
}
@Transactional(readOnly = true)
public List<Sector> findAllByIds(List<Integer> ids) {
logger.log(Level.INFO, "Fetching sectors with IDs: " + ids);
String jpql = "SELECT s FROM Sector s WHERE s.id IN :ids";
TypedQuery<Sector> query = entityManager.createQuery(jpql, Sector.class);
query.setParameter("ids", ids);
return query.getResultList();
}
}