diff --git a/.env.example b/.env.example
index f9a270e0..4c0043eb 100644
--- a/.env.example
+++ b/.env.example
@@ -13,3 +13,6 @@ CLOUDINARY_API_SECRET=valor-cloudinary
PERSPECTIVE_API_KEY=valor-perspective
RECAPTCHA_SITE_KEY=valor-recaptcha
+#chaves API Mercado Pago
+MP_PUBLIC_KEY=chave
+MP_ACCESS_TOKEN=chave
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 99cf0888..c7dccaa0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -139,6 +139,86 @@
jackson-databind
2.13.0
+
+ org.projectlombok
+ lombok
+ 1.18.24
+
+
+
+
+ com.mercadopago
+ sdk-java
+ 2.0.1
+
+
+ com.google.code.gson
+ gson
+ 2.8.9
+
+
+
+ com.itextpdf
+ itext7-core
+ 7.2.0
+
+
+
+ com.sun.mail
+ javax.mail
+ 1.6.2
+
+
+
+
+ org.apache.xmlgraphics
+ batik-transcoder
+ 1.14
+
+
+ xalan
+ xalan
+
+
+
+
+
+
+ com.google.zxing
+ core
+ 3.4.1
+
+
+
+ com.google.zxing
+ javase
+ 3.4.1
+
+
+
+
+ org.apache.xmlgraphics
+ fop
+ 2.6
+
+
+ xalan
+ xalan
+
+
+
+
+
+ com.google.api-client
+ google-api-client
+ 1.32.1
+
+
+
+ org.postgresql
+ postgresql
+ runtime
+
diff --git a/src/main/java/br/edu/utfpr/servicebook/config/WebSecurityConfig.java b/src/main/java/br/edu/utfpr/servicebook/config/WebSecurityConfig.java
index 6f15e02d..3bd3b0dd 100644
--- a/src/main/java/br/edu/utfpr/servicebook/config/WebSecurityConfig.java
+++ b/src/main/java/br/edu/utfpr/servicebook/config/WebSecurityConfig.java
@@ -12,6 +12,7 @@
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
+import org.springframework.web.client.RestTemplate;
@Configuration
@EnableWebSecurity
@@ -21,7 +22,6 @@ public class WebSecurityConfig {
@Autowired
CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
-
private static final String[] PUBLIC_URLS = {
"/",
"/**",
@@ -75,6 +75,9 @@ public AuthenticationManager authenticationManager(AuthenticationConfiguration a
return authenticationConfiguration.getAuthenticationManager();
}
-
+ @Bean
+ public RestTemplate restTemplate() {
+ return new RestTemplate();
+ }
}
diff --git a/src/main/java/br/edu/utfpr/servicebook/controller/ClientController.java b/src/main/java/br/edu/utfpr/servicebook/controller/ClientController.java
index e4966ad3..52b0f7bb 100644
--- a/src/main/java/br/edu/utfpr/servicebook/controller/ClientController.java
+++ b/src/main/java/br/edu/utfpr/servicebook/controller/ClientController.java
@@ -12,13 +12,23 @@
import br.edu.utfpr.servicebook.sse.EventSSEDTO;
import br.edu.utfpr.servicebook.sse.EventSseMapper;
import br.edu.utfpr.servicebook.sse.SSEService;
+import br.edu.utfpr.servicebook.util.DateUtil;
import br.edu.utfpr.servicebook.util.pagination.PaginationDTO;
import br.edu.utfpr.servicebook.util.pagination.PaginationUtil;
import br.edu.utfpr.servicebook.util.UserTemplateInfo;
import br.edu.utfpr.servicebook.util.TemplateUtil;
+import com.cloudinary.Cloudinary;
+import com.cloudinary.utils.ObjectUtils;
+import com.mercadopago.client.common.AddressRequest;
+import com.mercadopago.client.common.IdentificationRequest;
+import com.mercadopago.client.common.PhoneRequest;
+import com.mercadopago.client.preference.*;
+import com.mercadopago.resources.preference.Preference;
+import org.apache.batik.transcoder.TranscoderException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
@@ -31,12 +41,39 @@
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityNotFoundException;
import javax.servlet.http.HttpServletRequest;
+import javax.xml.transform.TransformerException;
+import java.io.File;
import java.io.IOException;
+import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
import java.time.LocalDate;
-import java.util.List;
-import java.util.Optional;
+import java.util.*;
import java.util.stream.Collectors;
+import org.springframework.http.ResponseEntity;
+import org.springframework.validation.BindingResult;
+import com.google.zxing.WriterException;
+import org.apache.batik.transcoder.TranscoderException;
+import org.apache.fop.configuration.ConfigurationException;
+import com.mercadopago.MercadoPagoConfig;
+import org.springframework.validation.BindingResult;
+import org.springframework.web.multipart.MultipartFile;
+import java.io.File;
+import java.nio.file.Files;
+import java.text.ParseException;
+import java.time.format.DateTimeFormatter;
+import java.util.Arrays;
+import java.util.Map;
+import com.cloudinary.Cloudinary;
+import com.cloudinary.utils.ObjectUtils;
+import javax.validation.Valid;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+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;
@RequestMapping("/minha-conta/cliente")
@Controller
public class ClientController {
@@ -104,6 +141,54 @@ public class ClientController {
@Autowired
private ProfessionalMapper professionalMapper;
+ @Autowired
+ private PaymentService paymentService;
+
+ @Autowired
+ private PaymentMapper paymentMapper;
+
+ @Autowired
+ private PaymentVoucherService paymentVoucherService;
+
+ @Autowired
+ private PaymentVoucherMapper paymentVoucherMapper;
+
+ @Autowired
+ private PaymentJobService paymentJobService;
+
+ @Autowired
+ private PaymentJobMapper paymentJobMapper;
+
+ @Autowired
+ private Cloudinary cloudinary;
+
+ @Autowired
+ private ProfessionalServiceOfferingService professionalServiceOfferingService;
+
+ @Autowired
+ private AssessmentProfessionalService assessmentProfessionalService;
+
+ @Autowired
+ private AssessmentProfessionalFileService assessmentProfessionalFileService;
+
+ @Autowired
+ private CategoryService categoryService;
+
+ @Autowired
+ private AssessmentProfessionalFileMapper assessmentProfessionalFileMapper;
+
+ @Autowired
+ private ModerateService moderateService;
+
+ @Autowired
+ private AssessmentResponseService assessmentResponseService;
+
+ @Autowired
+ private PerspectiveAPIService perspectiveAPIService;
+
+ @Value("${svg.certificate.template}")
+ private String svgCertificateTemplate;
+
/**
* Método que apresenta a tela inicial do cliente
@@ -192,11 +277,14 @@ public String delete (@PathVariable Long id, RedirectAttributes redirectAttribut
*/
@GetMapping("/meus-pedidos/{id}")
@RolesAllowed({RoleType.USER, RoleType.COMPANY})
- public ModelAndView showDetailsRequest(@PathVariable Optional id) throws Exception {
+ public ModelAndView showDetailsRequest(@PathVariable Optional id,
+ @RequestParam(value = "pag", defaultValue = "1") int page,
+ @RequestParam(value = "siz", defaultValue = "4") int size) throws Exception {
ModelAndView mv = new ModelAndView("client/details-request");
Optional jobRequest = jobRequestService.findById(id.get());
+ Optional oJobContracted = jobContractedService.findByJobRequest(jobRequest.get());
if (!jobRequest.isPresent()) {
throw new EntityNotFoundException("Solicitação de serviço não encontrado. Por favor, tente novamente.");
@@ -214,7 +302,31 @@ public ModelAndView showDetailsRequest(@PathVariable Optional id) throws E
ExpertiseMinDTO expertiseDTO = expertiseMapper.toMinDto(expertise.get());
- List jobCandidates = jobCandidateService.findByJobRequestOrderByChosenByBudgetDesc(jobRequest.get());
+ Optional client = (userService.findByEmail(authentication.getEmail()));
+
+ if (!client.isPresent()) {
+ throw new Exception("Usuário não autenticado! Por favor, realize sua autenticação no sistema.");
+ }
+
+ PageRequest pageRequest = PageRequest.of(1 - 1, 4, Sort.by("dateTarget").ascending());
+ Page jobRequestPage = null;
+ List jobRequestFullDTOs = null;
+
+ List jobCandidates = jobCandidateService.findByJobRequestAndChosenByBudget(jobRequest.get(), true);
+
+ jobRequestPage = jobRequestService.findByStatusAndClient(JobRequest.Status.DOING, client.get(), pageRequest);
+
+ jobRequestFullDTOs = jobRequestPage.stream()
+ .map(jobRequest1 -> {
+ Optional totalCandidates = jobContractedService.findByJobRequest(jobRequest1);
+
+ if (totalCandidates.isPresent()) {
+ return jobRequestMapper.toFullDto(jobRequest1);
+ }
+
+ return jobRequestMapper.toFullDto(jobRequest1, Optional.ofNullable(0L));
+ }).collect(Collectors.toList());
+
List jobCandidatesDTOs = jobCandidates.stream()
.map(candidate -> {
@@ -222,9 +334,18 @@ public ModelAndView showDetailsRequest(@PathVariable Optional id) throws E
})
.collect(Collectors.toList());
+ if (jobRequest.get().getServiceOffering() != null) {
+ Optional pso = professionalServiceOfferingService.findById(jobRequest.get().getServiceOffering().getId());
+ mv.addObject("service_professional", pso.get());
+ }
+
+
mv.addObject("candidates", jobCandidatesDTOs);
+ mv.addObject("jobCandidates12", jobRequestFullDTOs);
mv.addObject("expertise", expertiseDTO);
mv.addObject("jobRequest", jobDTO);
+ mv.addObject("jobContracted", oJobContracted.get());
+
return mv;
}
@@ -237,15 +358,33 @@ public ModelAndView showDetailsRequest(@PathVariable Optional id) throws E
*/
@GetMapping("/meus-pedidos/{jobId}/detalhes/{candidateId}")
@RolesAllowed({RoleType.USER, RoleType.COMPANY})
- public ModelAndView showDetailsRequestCandidate(@PathVariable Optional jobId, @PathVariable Optional candidateId) throws Exception {
+ public ModelAndView showDetailsRequestCandidate(@PathVariable Long jobId, @PathVariable Long candidateId) throws Exception {
ModelAndView mv = new ModelAndView("client/details-request-candidate");
- Optional oCandidate = userService.findById(candidateId.get());
+ System.out.println("DADOSSS");
+ System.out.println(jobId);
+ System.out.println(candidateId);
+
+ Optional oCandidate = userService.findById(candidateId);
+ Optional oIndividual = individualService.findById(candidateId);
+
+ System.out.println(oCandidate);
+ System.out.println(oIndividual.get());
+
if (!oCandidate.isPresent()) {
throw new EntityNotFoundException("O candidato não foi encontrado!");
}
- Optional jobCandidate = jobCandidateService.findById(jobId.get(), oCandidate.get().getId());
+ Optional oJobRequest = jobRequestService.findById(jobId);
+ System.out.println("oJobRequest");
+ System.out.println(oJobRequest);
+
+ if (!oJobRequest.isPresent()) {
+ throw new EntityNotFoundException("O candidato não foi encontrado!");
+ }
+
+ Optional jobCandidate = jobCandidateService.findById(oJobRequest.get().getId(), oIndividual.get().getId());
+
if (!jobCandidate.isPresent()) {
throw new EntityNotFoundException("Candidato não encontrado. Por favor, tente novamente.");
}
@@ -273,7 +412,7 @@ public ModelAndView showDetailsRequestCandidate(@PathVariable Optional job
public ModelAndView showAvailableJobs(
HttpServletRequest request,
@RequestParam(value = "pag", defaultValue = "1") int page,
- @RequestParam(value = "siz", defaultValue = "3") int size,
+ @RequestParam(value = "siz", defaultValue = "4") int size,
@RequestParam(value = "ord", defaultValue = "id") String order,
@RequestParam(value = "dir", defaultValue = "ASC") String direction
) throws Exception {
@@ -739,7 +878,7 @@ public String markAsClose(
* Altera o estado de um serviço para TO_HIRED, ou seja, o cliente contratou um serviço mas
* fica no estado de espera da confirmação do profissional.
* @param jobId
- * @param individualId
+ * @param userId
* @param redirectAttributes
* @return
* @throws IOException
@@ -764,16 +903,418 @@ public String markAsHided(@PathVariable Long jobId, @PathVariable Long userId, R
jobRequest.setStatus(JobRequest.Status.TO_HIRED);
jobRequestService.save(jobRequest);
+ System.out.println("JOBBBBBBBBB" + oJobRequest.get());
+
//guarda a data de contratação
- Optional oJobContracted = jobContractedService.findByJobRequest(jobRequest);
- if(!oJobContracted.isPresent()) {
- throw new EntityNotFoundException("O profissional não pode ser contratado!");
- }
+ Optional oJobContracted = jobContractedService.findByJobRequest(oJobRequest.get());
+// if(!oJobContracted.isPresent()) {
+// throw new EntityNotFoundException("O profissional não pode ser contratado!");
+// }
+ Optional oUser = userService.findById(userId);
- JobContracted jobContracted = oJobContracted.get();
+ JobContracted jobContracted = new JobContracted();
jobContracted.setHiredDate(LocalDate.now());
+ jobContracted.setJobRequest(oJobRequest.get());
+ jobContracted.setUser(oUser.get());
jobContractedService.save(jobContracted);
return "redirect:/minha-conta/cliente/meus-pedidos/"+jobId;
}
+
+ @Autowired
+ public ClientController(PaymentService paymentService) {
+ this.paymentService = paymentService;
+ }
+
+ /**
+ * Responsável por realizar o pagamento via API Mercado Pago.
+ */
+ @PostMapping("/pagamento")
+ @RolesAllowed({RoleType.USER})
+ public ResponseEntity createPayment(@RequestBody CardPaymentDTO cardPaymentDTO) {
+ log.info("Received payment request: {}", cardPaymentDTO);
+
+ Optional oUser = (userService.findByEmail(authentication.getEmail()));
+
+//
+//// if(!paymentResponse.getStatusCode().is2xxSuccessful()){
+//// response.setMessage("Erro ao processar pagamento. Tente novamente");
+//// return ResponseEntity.status(paymentResponse.getStatusCode()).body(response);
+//// }
+//
+// Map, ?> responseMap = (Map, ?>) responseBody;
+
+// Integer paymentId = (Integer) responseMap.get("id");
+// String status = (String) responseMap.get("status");
+////
+// PaymentDTO paymentDTO = new PaymentDTO(paymentId, status);
+// Payment payment = paymentMapper.toEntity(paymentDTO);
+////
+// paymentService.save(payment);
+//
+// response.setData(paymentResponse.getBody());
+//
+// System.out.println("SATTSUS PAGAMENTO.....");
+//// System.out.println(status);
+//
+//
+// return ResponseEntity.ok(response);
+//
+//
+// } catch (Exception e) {
+// response.setMessage("Erro ao fazer pagamento. Por favor, tente novamente.");
+// return ResponseEntity.status(400).body(response);
+// }
+
+
+ PaymentResponseDTO payment = paymentService.pay(cardPaymentDTO);
+
+ System.out.println("paymentResponse");
+ System.out.println(payment.getStatus());
+ System.out.println(payment.getId());
+
+ if(Objects.equals(payment.getStatus(), "approved")){
+ Payment payment1 = new Payment();
+ payment1.setStatus(payment.getStatus());
+ payment1.setPaymentId(payment.getId());
+ paymentService.save(payment1);
+ }
+
+ return ResponseEntity.status(HttpStatus.CREATED).body(payment);
+ }
+
+ /**
+ * Apos processar o pagamento, ele é inserido na tabela payments_jobRequests
+ * contendo o id do pagamento e do serviço que foi realizado o pagamento.
+ * Finalizado este processo é preciso gerar um comprovante do pagamento
+ * tanto para cliente quanto profissional, que sera enviado por email
+ * **/
+ @PostMapping("/pagamento/jobRequest")
+ @RolesAllowed({RoleType.USER})
+ public ModelAndView savePaymentJob(@RequestBody PaymentJobDTO dto, BindingResult errors, RedirectAttributes redirectAttributes) throws ConfigurationException, TranscoderException, IOException, TransformerException, WriterException {
+ ModelAndView modelAndView = new ModelAndView();
+ final Date now = new Date();
+
+ Optional oPayment = paymentService.findByPaymentId(dto.getPaymentId());
+ Optional oJobRequest = jobRequestService.findById(dto.getJobRequestId());
+
+ PaymentJobRequest paymentJob = new PaymentJobRequest();
+ paymentJob.setJobRequestId(dto.getJobRequestId());
+ paymentJob.setPayment(oPayment.get());
+ paymentJob.setJobRequest(oJobRequest.get());
+ paymentJob.setDateCreated(now);
+
+ paymentJobService.save(paymentJob);
+
+ createVoucherPayment(paymentJob); // GERA O COMPROVANTE DE PAGAMENTO
+
+ modelAndView.addObject("mensagem", "Pagamento processado com sucesso!");
+
+ return modelAndView;
+ }
+
+ public String createVoucherPayment(PaymentJobRequest paymentJob) throws IOException, TranscoderException, ConfigurationException, TransformerException, WriterException, TransformerException {
+ /*Busca o job request - cliente*/
+ Optional oJobRequest = jobRequestService.findById(paymentJob.getJobRequestId());
+
+ /*Traz o profissional*/
+ Optional oJobContracted = jobContractedService.findByJobRequest(oJobRequest.get());
+
+ /*Traz o servico*/
+ Optional oExpertise = expertiseService.findById(oJobRequest.get().getExpertise().getId());
+
+ PaymentVoucher paymentVoucher = new PaymentVoucher();
+ paymentVoucher.setClient(oJobRequest.get().getUser());
+ paymentVoucher.setProfessional(oJobContracted.get().getUser());
+ paymentVoucher.setCode(gerarCodigoAlfanumerico());
+ paymentVoucher.setJobRequest(oJobRequest.get());
+
+ String emailProfissional = oJobContracted.get().getUser().getEmail();
+ String emailClient = oJobRequest.get().getUser().getEmail();
+
+ paymentVoucherService.save(paymentVoucher);
+ Date dataAtual = new Date();
+
+ // Converter LocalDate para Date
+ SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
+
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(dataAtual);
+
+ // Incrementando 15 dias
+ calendar.add(Calendar.DATE, 15);
+
+ // Obtendo a nova data após o incremento
+ Date dataFinal = calendar.getTime();
+ SimpleDateFormat sdfNovo = new SimpleDateFormat("dd/MM/yyyy");
+
+ String client_name = paymentVoucher.getClient().getName(); // NOME DO CLIENTE
+ String client_fone = paymentVoucher.getClient().getPhoneNumber(); // TELEFONE DO CLIENTE
+ String client_email = paymentVoucher.getClient().getEmail(); // EMAIL DO CLIENTE
+ String client_address_name = paymentVoucher.getClient().getAddress().getNeighborhood(); // ENDEREÇO DO CLIENTE
+ String client_address_number = paymentVoucher.getClient().getAddress().getNumber(); // NUMERO ENDEREÇO DO CLIENTE
+ String client_address = client_address_name + " - " + client_address_number; // ENDEREÇO DO CLIENTE
+
+ String profes_name = paymentVoucher.getProfessional().getName(); // NOME DO PROFISSIONAL
+ String profes_fone = paymentVoucher.getProfessional().getPhoneNumber(); // TELEFONE DO PROFISSIONAL
+ String profes_email = paymentVoucher.getProfessional().getEmail(); // EMAIL DO PROFISSIONAL
+ String profes_address_name = paymentVoucher.getProfessional().getAddress().getNeighborhood(); // ENDEREÇO DO PROFISSIONAL
+ String profes_address_number = paymentVoucher.getProfessional().getAddress().getNumber(); // NUMERO ENDEREÇO DO PROFISSIONAL
+ String profes_address = profes_address_name + " - " + profes_address_number; // ENDEREÇO DO PROFISSIONAL
+
+ String service_name = oJobRequest.get().getExpertise().getName();
+
+// Optional optionalProfessionalServiceOffering = professionalServiceOfferingService.findProfessionalServiceOfferingByExpertiseAAndUser(paymentVoucher.getProfessional().getId(), oJobRequest.get().getExpertise().getId());
+ Optional optionalProfessionalServiceOffering = professionalServiceOfferingService.findProfessionalServiceOfferingByIdAndUser(oJobRequest.get().getServiceOffering().getId(), paymentVoucher.getProfessional().getId());
+
+ String value_service = "0,00";
+ if (optionalProfessionalServiceOffering.isPresent()){
+ value_service = String.valueOf(optionalProfessionalServiceOffering.get().getPrice());
+ }
+
+ File pdfFile = paymentVoucherService.generateCertificate(svgCertificateTemplate, paymentVoucher.getCode(),service_name, sdfNovo.format(dataAtual), sdfNovo.format(dataFinal),
+ client_name, "111111111", client_fone, client_email, profes_name, "10444444440",
+ profes_email, profes_fone, profes_address, "PIX", value_service, "QRDCOD", sdfNovo.format(dataAtual));
+ Map uploadResult = cloudinary.uploader().upload(pdfFile, ObjectUtils.asMap("folder", "certificates"));
+
+ String uploadURL = (String)uploadResult.get("url");
+
+ //envia um email com a URL do certificado
+ /*Envio de email para o profissional*/
+ quartzService.sendEmailPaymentVoucher(paymentVoucher.getCode(),
+ oJobRequest.get().getUser().getId(), oJobContracted.get().getUser().getId(), oExpertise.get().getName(), sdf.format(dataFinal), (String)uploadResult.get("url"));
+ pdfFile.delete();
+
+// (url.openStream(), voucher, service,date, date_due,name_client,document_client,fone_client,mail_client,name_professional, document_professional,
+// mail_professional, fone_professional, endereco_pro, payment_type, payment_value, qrCode);
+
+ return "redirect:/minha-conta/cliente#executados";
+ }
+
+ /* Gera código aleatorico e unico para gravação de comprovante */
+ private String gerarCodigoAlfanumerico() {
+ UUID uuid = UUID.randomUUID();
+ String codigo = uuid.toString().replace("-", "").substring(0, 10);
+ return codigo.toUpperCase();
+ }
+
+ /**
+ * Avalia o serviço depois de finalizado
+ * @param jobId
+ * @param redirectAttributes
+ * @return
+ * @throws IOException
+ */
+ @GetMapping("/avaliar/servico/{jobId}/profissional/{profissionalId}")
+ @RolesAllowed({RoleType.USER, RoleType.COMPANY})
+ public ModelAndView evaluateService(@PathVariable Long jobId, @PathVariable Long profissionalId, RedirectAttributes redirectAttributes) throws IOException {
+ Optional oClientAuthenticated = (userService.findByEmail(authentication.getEmail()));
+ ModelAndView mv = new ModelAndView("client/evaluate-jobs");
+
+ if(!oClientAuthenticated.isPresent()){
+ return mv.addObject("visitor/login");
+ }
+
+ Optional oJobRequest = jobRequestService.findById(jobId);
+
+ Optional oIndividual = userService.findById(profissionalId);
+
+ System.out.println("INDIVIDUAL");
+ System.out.println(oIndividual.get().getName());
+
+ Optional oJobContracted = jobContractedService.findByJobRequest(oJobRequest.get());
+ DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
+
+
+ mv.addObject("job", oJobRequest.get());
+ mv.addObject("professional", oIndividual.get());
+ mv.addObject("jobContracted", oJobContracted.get());
+ mv.addObject("hiredDate", dateTimeFormatter.format(oJobContracted.get().getHiredDate()));
+ mv.addObject("finishDate", dateTimeFormatter.format(oJobContracted.get().getFinishDate()));
+
+ return mv;
+ }
+
+ /**
+ * @param jobId
+ * @param profissionalId
+ * @param dto
+ * @param redirectAttributes
+ * @return
+ * @throws IOException
+ * @throws ParseException
+ */
+ @PostMapping("/avaliar/servico/{jobId}/profissional/{profissionalId}")
+ @RolesAllowed({RoleType.USER})
+ public ModelAndView saveAssessmentProfessional(
+ @PathVariable Long profissionalId,
+ @PathVariable Long jobId,
+ AssessmentProfessionalDTO dto,
+ AssessmentProfessionalFileDTO assessmentProfessionalFileDTO,
+ @RequestParam("pathImage") MultipartFile file,
+ RedirectAttributes redirectAttributes,
+ BindingResult errors
+ ) throws IOException, ParseException {
+ String currentUserEmail = authentication.getEmail();
+
+ Optional oindividual = individualService.findById(profissionalId);
+ Optional oClliente = individualService.findByEmail(currentUserEmail);
+
+ if(!oindividual.isPresent()){
+ throw new EntityNotFoundException("O usuário não foi encontrado!");
+ }
+
+ Optional oJobRequest = jobRequestService.findById(jobId);
+
+ AssessmentProfessional assessmentProfessional = new AssessmentProfessional();
+ String comment = dto.getComment();
+
+ if (!comment.isEmpty()){
+ String analyzedComment = analyzeComment(comment);
+ if ("Comentário Ofensivo".equals(analyzedComment)) {
+ errors.rejectValue("comment", "error.dto", "Proibido comentários ofensivos!.");
+ return errorFowarding(dto, assessmentProfessionalFileDTO, errors);
+ }
+ }
+
+ assessmentProfessional.setComment(dto.getComment());
+ assessmentProfessional.setProfessional(oindividual.get());
+ assessmentProfessional.setQuality(dto.getQuality());
+ assessmentProfessional.setDate(DateUtil.getToday());
+
+ assessmentProfessional.setClient(oClliente.get());
+ assessmentProfessional.setJobRequest(oJobRequest.get());
+ assessmentProfessionalService.save(assessmentProfessional);
+
+ if (!assessmentProfessionalFileDTO.getPathImage().isEmpty() ) {
+ Map, ?> uploadResult = cloudinary.uploader().upload(file.getBytes(), ObjectUtils.emptyMap());
+
+ String imageUrl = (String) uploadResult.get("url");
+
+ if(moderateService.isNsfwImage(imageUrl)){
+ String publicId = (String) uploadResult.get("public_id");
+ cloudinary.uploader().destroy(publicId, ObjectUtils.emptyMap());
+ redirectAttributes.addFlashAttribute("msgError", "A imagem enviada contém conteúdo impróprio. Por favor, envie outra foto.");
+ return new ModelAndView("redirect:/minha-conta/cliente/avaliar/servico/"+jobId+"/profissional/"+profissionalId);
+ }
+
+// AssessmentProfessionalFiles assessmentProfessionalFiles = assessmentProfessionalFileMapper.toEntity(assessmentProfessionalFileDTO);
+// assessmentProfessionalFiles.setAssessmentProfessional(assessmentProfessional);
+ AssessmentProfessionalFiles assessmentProfessionalFiles1 = new AssessmentProfessionalFiles();
+ assessmentProfessionalFiles1.setPathImage(imageUrl);
+ assessmentProfessionalFiles1.setAssessmentProfessional(assessmentProfessional);
+ assessmentProfessionalFileService.save(assessmentProfessionalFiles1);
+ }
+
+ redirectAttributes.addFlashAttribute("msg", "Avaliação realizada com sucesso!");
+
+ return new ModelAndView("redirect:/minha-conta/cliente#executados");
+ }
+
+ public boolean isValidateImage(MultipartFile image){
+ List contentTypes = Arrays.asList("image/png", "image/jpg", "image/jpeg");
+
+ for(int i = 0; i < contentTypes.size(); i++){
+ if(image.getContentType().toLowerCase().startsWith(contentTypes.get(i))){
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /*Método responsavel em chamar a api e então validar comentários*/
+ @GetMapping("/analyze-comment")
+ public String analyzeComment(String coment){
+ return perspectiveAPIService.analyzeComment(coment);
+ }
+
+ private ModelAndView errorFowarding(AssessmentProfessionalDTO dto, AssessmentProfessionalFileDTO dtoFiles,BindingResult errors) {
+ ModelAndView mv = new ModelAndView("client/evaluate-jobs");
+ mv.addObject("dto", dto);
+ mv.addObject("errors", errors.getAllErrors());
+ return mv;
+ }
+
+ private ModelAndView errorFowardingResponse(AssessmentResponseDTO dto,BindingResult errors) {
+ ModelAndView mv = new ModelAndView("professional/detail-service");
+ mv.addObject("dto", dto);
+ mv.addObject("errors", errors.getAllErrors());
+ return mv;
+ }
+
+ /**
+ * @param profissionalId
+ * @param dto
+ * @param redirectAttributes
+ * @return
+ * @throws IOException
+ * @throws ParseException
+ */
+ @PostMapping("/contratar-servico/profissional/{profissionalId}")
+ @RolesAllowed({RoleType.USER})
+ public ModelAndView saveContratedServiceProfessional(
+ JobRequestDTO dto,
+ RedirectAttributes redirectAttributes,
+ @PathVariable Long profissionalId,
+ BindingResult errors
+ ) throws IOException, ParseException {
+ String currentUserEmail = authentication.getEmail();
+
+ System.out.println(dto);
+
+ Optional oCliente = individualService.findByEmail(currentUserEmail);
+
+ if(!oCliente.isPresent()){
+ throw new EntityNotFoundException("O usuário não foi encontrado!");
+ }
+
+ Optional oExpertise = expertiseService.findById(dto.getExpertiseId());
+
+ if(!oExpertise.isPresent()){
+ throw new EntityNotFoundException("Especialidade não foi encontrada!");
+ }
+
+ JobRequest jobRequest = new JobRequest();
+ jobRequest.setExpertise(oExpertise.get());
+ jobRequest.setUser(oCliente.get());
+ jobRequest.setClientConfirmation(true);
+ jobRequest.setQuantityCandidatorsMax(1);
+ jobRequest.setDateCreated(LocalDate.now());
+ jobRequest.setDateTarget(DateUtil.getThisMonth()); // para este mês
+ jobRequest.setDescription(oExpertise.get().getDescription());
+ jobRequest.setProfessionalConfirmation(true);
+ jobRequest.setStatus(JobRequest.Status.TO_DO);
+
+ Optional oUser = userService.findById(profissionalId);
+
+ Optional oProfessionalServiceOffering = professionalServiceOfferingService.findById(dto.getProfessionalServiceOfferingId());
+ if(!oProfessionalServiceOffering.isPresent()){
+ throw new EntityNotFoundException("Serviço do profissional não foi encontrada!");
+ }
+ jobRequest.setServiceOffering(oProfessionalServiceOffering.get());
+
+ jobRequestService.save(jobRequest);
+
+ JobCandidate jobCandidate = new JobCandidate(jobRequest, oUser.get());
+ jobCandidateService.save(jobCandidate);
+
+ if(!oUser.isPresent()){
+ throw new EntityNotFoundException("Profissional não foi encontrado!");
+ }
+
+ JobContracted jobContracted = new JobContracted();
+ jobContracted.setJobRequest(jobRequest);
+ jobContracted.setUser(oUser.get());
+ jobContracted.setHiredDate(LocalDate.now());
+
+ jobContractedService.save(jobContracted);
+
+ jobRequest.setStatus(JobRequest.Status.TO_DO);
+ jobRequestService.save(jobRequest);
+
+ redirectAttributes.addFlashAttribute("msg", "Pedido foi enviado, o profissional receberá uma notificação!!");
+
+ return new ModelAndView("redirect:/minha-conta/cliente#paraFazer");
+ }
}
\ No newline at end of file
diff --git a/src/main/java/br/edu/utfpr/servicebook/controller/CompanyProfessionalController.java b/src/main/java/br/edu/utfpr/servicebook/controller/CompanyProfessionalController.java
new file mode 100644
index 00000000..ca0c3b45
--- /dev/null
+++ b/src/main/java/br/edu/utfpr/servicebook/controller/CompanyProfessionalController.java
@@ -0,0 +1,264 @@
+package br.edu.utfpr.servicebook.controller;
+
+import br.edu.utfpr.servicebook.model.dto.*;
+import br.edu.utfpr.servicebook.model.entity.*;
+import br.edu.utfpr.servicebook.model.mapper.*;
+import br.edu.utfpr.servicebook.model.repository.UserRepository;
+import br.edu.utfpr.servicebook.security.IAuthentication;
+import br.edu.utfpr.servicebook.security.RoleType;
+import br.edu.utfpr.servicebook.service.*;
+import br.edu.utfpr.servicebook.sse.EventSSE;
+import br.edu.utfpr.servicebook.sse.EventSSEDTO;
+import br.edu.utfpr.servicebook.sse.EventSseMapper;
+import br.edu.utfpr.servicebook.sse.SSEService;
+import br.edu.utfpr.servicebook.util.TemplateUtil;
+import br.edu.utfpr.servicebook.util.UserTemplateInfo;
+import br.edu.utfpr.servicebook.util.UserTemplateStatisticInfo;
+import com.cloudinary.utils.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
+import org.springframework.stereotype.Controller;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.ui.Model;
+import org.springframework.validation.BindingResult;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.servlet.ModelAndView;
+import org.springframework.web.servlet.mvc.support.RedirectAttributes;
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
+
+import javax.annotation.security.RolesAllowed;
+import javax.persistence.EntityNotFoundException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.validation.Valid;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import java.util.stream.Collectors;
+@RequestMapping("/minha-conta/empresa/profissionais")
+@Controller
+public class CompanyProfessionalController {
+ public static final Logger log = LoggerFactory.getLogger(CompanyProfessionalController.class);
+ @Autowired
+ private UserService userService;
+
+ @Autowired
+ private CompanyProfessionalService companyProfessionalService;
+
+ @Autowired
+ private IAuthentication authentication;
+
+ @Autowired
+ private UserMapper userMapper;
+
+ @Autowired
+ private CompanyProfessionalMapper companyProfessionalMapper;
+
+ @Autowired
+ private TemplateUtil templateUtil;
+
+ @Autowired
+ private UserRepository userRepository;
+
+ @Autowired
+ private QuartzService quartzService;
+
+ @Autowired
+ private UserCodeMapper userCodeMapper;
+
+ @Autowired
+ private UserCodeService userCodeService;
+
+ @Autowired
+ private UserTokenMapper userTokenMapper;
+
+ @Autowired
+ private UserTokenService userTokenService;
+
+ @Autowired
+ private StateService stateService;
+
+ @Autowired
+ private SSEService sseService;
+
+ @Autowired
+ private EventSseMapper eventSseMapper;
+ @Autowired
+ private ProfessionalExpertiseService professionalExpertiseService;
+ @Autowired
+ private ExpertiseService expertiseService;
+
+ @Autowired
+ private ExpertiseMapper expertiseMapper;
+
+ /**
+ * Apresenta a tela para a empresa adicionar profissionais.
+ * @param expertiseId
+ * @return
+ * @throws Exception
+ */
+ @GetMapping()
+ @RolesAllowed({RoleType.COMPANY})
+ public ModelAndView showProfessionals(@RequestParam(required = false, defaultValue = "0") Optional expertiseId) throws Exception {
+
+ User company = this.getCompany();
+ UserDTO professionalMinDTO = userMapper.toDto(company);
+
+ ModelAndView mv = new ModelAndView("company/new-professional");
+
+ UserTemplateInfo userTemplateInfo = templateUtil.getUserInfo(professionalMinDTO);
+ UserTemplateStatisticInfo sidePanelStatisticDTO = templateUtil.getCompanyStatisticInfo(company, expertiseId.get());
+
+ mv.addObject("statisticInfo", sidePanelStatisticDTO);
+
+ mv.addObject("id", expertiseId.orElse(0L));
+
+ List professionals = userService.findProfessionalsNotExist();
+
+ List companyProfessionals = companyProfessionalService.findByCompany(company.getId());
+
+ List companyProfessionalDTO2s = companyProfessionals.stream()
+ .map(s -> companyProfessionalMapper.toResponseDTO(s))
+ .collect(Collectors.toList());
+
+ Optional oProfessional = (userService.findByEmail(authentication.getEmail()));
+
+ UserTemplateInfo individualInfo = templateUtil.getUserInfo(professionalMinDTO);
+
+ //envia a notificação ao usuário
+ List eventSsesList = sseService.findPendingEventsByEmail(authentication.getEmail());
+ List eventSSEDTOs = eventSsesList.stream()
+ .map(eventSse -> {
+ return eventSseMapper.toFullDto(eventSse);
+ })
+ .collect(Collectors.toList());
+ List professionalExpertises = professionalExpertiseService.findByProfessional(oProfessional.get());
+
+ List expertiseDTOs = professionalExpertises.stream()
+ .map(professionalExpertise -> professionalExpertise.getExpertise())
+ .map(expertise -> expertiseMapper.toDto(expertise))
+ .collect(Collectors.toList());
+
+
+ mv.addObject("professionals", professionals);
+ mv.addObject("professionalCompanies", companyProfessionalDTO2s);
+ mv.addObject("statisticInfo", sidePanelStatisticDTO);
+ mv.addObject("eventsse", eventSSEDTOs);
+ mv.addObject("expertises", expertiseDTOs);
+ mv.addObject("company", true);
+
+ return mv;
+ }
+
+ @PostMapping()
+ @RolesAllowed({RoleType.COMPANY})
+ public ModelAndView saveProfessionals(@Valid CompanyProfessionalDTO dto, BindingResult errors, RedirectAttributes redirectAttributes) throws Exception {
+
+ ModelAndView mv = new ModelAndView("redirect:profissionais");
+ String ids = dto.getIds();
+ User company = this.getCompany();
+ Optional company_name = userService.findById(company.getId());
+ Optional oCompany = (userService.findByEmail(authentication.getEmail()));
+
+ Optional oProfessional = userService.findByEmail(ids);
+ if(!oProfessional.isPresent()){
+ Random random = new Random();
+ int numberRandom = random.nextInt(100 - 1) + 1;
+
+ String token = "RP0"+company.getId()+numberRandom;
+ UserTokenDTO userTokenDTO = new UserTokenDTO();
+ userTokenDTO.setUser(company);
+ userTokenDTO.setEmail(ids);
+ userTokenDTO.setToken(token);
+ UserToken userToken = userTokenMapper.toEntity(userTokenDTO);
+
+ userTokenService.save(userToken);
+
+ String tokenLink = ServletUriComponentsBuilder.fromCurrentContextPath().build().toString()
+ + "/cadastrar-se?passo-1&code="+token;
+
+ quartzService.sendEmailToRegisterUser(dto.getIds(), company.getName(), tokenLink);
+
+ CompanyProfessional p = companyProfessionalService.save(new CompanyProfessional(company, dto.getIds()));
+
+ redirectAttributes.addFlashAttribute("msg", "Convite enviado para usuário, aguardando confirmação!");
+
+ } else {
+ String tokenLink = ServletUriComponentsBuilder.fromCurrentContextPath().build().toString() + "/minha-conta/empresa/profissionais/confirmar/" + company_name.get().getId() +"/" + dto.getIds();
+ quartzService.sendEmailWithConfirmationUser(dto.getIds(), company.getName(), tokenLink);
+
+ Optional optionalCompanyProfessional = companyProfessionalService.findByCompanyAndProfessional(company, oProfessional.get());
+
+
+ if(!optionalCompanyProfessional.isPresent()){
+
+ CompanyProfessional p = companyProfessionalService.save(new CompanyProfessional(company, dto.getIds(), oProfessional.get()));
+
+ redirectAttributes.addFlashAttribute("msg", "Convite enviado para usuário, aguardando confirmação!");
+ } else {
+ redirectAttributes.addFlashAttribute("msg", "Usuário ja está na empresa!");
+ }
+ }
+ return mv;
+ }
+
+ @DeleteMapping("/{id}")
+ @RolesAllowed({RoleType.COMPANY})
+ @Transactional
+ public String delete(@PathVariable User id, RedirectAttributes redirectAttributes) throws Exception {
+ User company = this.getCompany();
+ Optional oProfessional = userService.findById(id.getId());
+
+ Optional optionalCompanyProfessional = companyProfessionalService.findByCompanyAndProfessional(company, oProfessional.get());
+
+ if (optionalCompanyProfessional.get().getProfessional().getId().equals(id.getId())) {
+ this.companyProfessionalService.delete(optionalCompanyProfessional.get().getId());
+ }
+ return "redirect:/minha-conta/empresa/profissionais";
+ }
+
+ /**
+ * Retorna a empresa logado.
+ * @return
+ * @throws Exception
+ */
+ private User getCompany() throws Exception {
+ Optional oCompany = (userService.findByEmail(authentication.getEmail()));
+
+ if (!oCompany.isPresent()) {
+ throw new Exception("Opss! Não foi possivel encontrar seus dados, tente fazer login novamente");
+ }
+
+ return oCompany.get();
+ }
+
+ @GetMapping("/confirmar/{companyId}/{email}")
+ @RolesAllowed({RoleType.COMPANY, RoleType.USER})
+ public String includeProfessionals(@PathVariable Long companyId, @PathVariable String email, HttpServletRequest request, RedirectAttributes redirectAttributes) throws
+ IOException {
+
+ Optional oProfessional = userService.findByEmail(email);
+ Optional oCompany = userService.findById(companyId);
+ if(!oProfessional.isPresent()){
+ throw new EntityNotFoundException("Profissional não encontrado pelo id informado.");
+ }
+
+ if(!oCompany.isPresent()){
+ throw new EntityNotFoundException("Empresa não encontrada pelo id informado.");
+ }
+ Optional oCompanyProfessional = companyProfessionalService.findByCompanyAndProfessional(oCompany.get(), oProfessional.get());
+
+ if(!oCompanyProfessional.isPresent()){
+ throw new EntityNotFoundException("Profissional não encontrado na empresa.");
+ }
+
+ CompanyProfessional companyProfessional = oCompanyProfessional.get();
+
+ companyProfessional.setConfirmed(true);
+ companyProfessionalService.save(companyProfessional);
+
+ return "redirect:/login";
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/br/edu/utfpr/servicebook/controller/IndexController.java b/src/main/java/br/edu/utfpr/servicebook/controller/IndexController.java
index e1c2b3bd..49b3bd06 100644
--- a/src/main/java/br/edu/utfpr/servicebook/controller/IndexController.java
+++ b/src/main/java/br/edu/utfpr/servicebook/controller/IndexController.java
@@ -1,7 +1,13 @@
package br.edu.utfpr.servicebook.controller;
+import br.edu.utfpr.servicebook.model.dto.CategoryDTO;
+import br.edu.utfpr.servicebook.model.dto.ExpertiseDTO;
import br.edu.utfpr.servicebook.model.dto.JobRequestFullDTO;
+import br.edu.utfpr.servicebook.model.dto.ServiceDTO;
import br.edu.utfpr.servicebook.model.entity.*;
+import br.edu.utfpr.servicebook.model.mapper.CategoryMapper;
+import br.edu.utfpr.servicebook.model.mapper.ExpertiseMapper;
+import br.edu.utfpr.servicebook.model.mapper.ServiceMapper;
import br.edu.utfpr.servicebook.security.IAuthentication;
import br.edu.utfpr.servicebook.security.RoleType;
import br.edu.utfpr.servicebook.service.*;
@@ -15,20 +21,20 @@
import org.springframework.data.domain.Page;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
+import javax.persistence.EntityNotFoundException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;
+import java.util.stream.Collectors;
@RequestMapping("/")
@Controller
@@ -61,6 +67,20 @@ public class IndexController {
@Autowired
private HttpSession httpSession;
+ @Autowired
+ private CategoryService categoryService;
+
+ @Autowired
+ private CategoryMapper categoryMapper;
+
+ @Autowired
+ private ExpertiseMapper expertiseMapper;
+
+ @Autowired
+ private ServiceService serviceService;
+
+ @Autowired
+ private ServiceMapper serviceMapper;
@GetMapping
@PermitAll
public ModelAndView showIndexPage(HttpServletResponse response) {
@@ -81,6 +101,11 @@ public ModelAndView showIndexPage(HttpServletResponse response) {
return new ModelAndView("redirect:/minha-conta/empresa/disponiveis");
}
}
+ //lista de categorias
+ List categories = categoryService.findAll();
+ List categoryDTOs = categories.stream()
+ .map(s -> categoryMapper.toDto(s))
+ .collect(Collectors.toList());
List cities = cityService.findAll();
mv.addObject("cities", cities);
@@ -90,6 +115,7 @@ public ModelAndView showIndexPage(HttpServletResponse response) {
mv.addObject("totalJobContracted", jobContractedService.countAll());
mv.addObject("totalProfessionals", userService.countProfessionals());
mv.addObject("totalClients", userService.countUsersWithoutExpertise());
+ mv.addObject("categories", categoryDTOs);
return mv;
}
@@ -101,8 +127,6 @@ public String showClientPage(HttpSession httpSession, RedirectAttributes redirec
return "redirect:/";
}
-
-
@GetMapping("/bem-vindo")
@PermitAll
public ModelAndView showWelcomePage() {
@@ -122,4 +146,53 @@ public String notAuthorized() {
return "error/not-authorized";
}
+ @GetMapping("/especialidades/categoria/{categoryId}")
+ @PermitAll
+ @ResponseBody
+ public List showExpertisesByCategory(@PathVariable Long categoryId) throws Exception {
+ if(categoryId != null){
+ List expertises = expertiseService.findByCategoryId(categoryId);
+
+ List expertiseDTOS = expertises.stream()
+ .map(s -> expertiseMapper.toDto(s))
+ .collect(Collectors.toList());
+
+ return expertiseDTOS;
+ } else {
+ List expertises = expertiseService.findAll();
+
+ List expertiseDTOS = expertises.stream()
+ .map(s -> expertiseMapper.toDto(s))
+ .collect(Collectors.toList());
+
+ return expertiseDTOS;
+ }
+
+ }
+
+ @GetMapping("/servicos/especialidade/{expertiseId}")
+ @PermitAll
+ @ResponseBody
+ public List showServicesByExpertise(@PathVariable Long expertiseId) throws Exception {
+ if(expertiseId != null){
+ Expertise expertise = expertiseService.findById(expertiseId).orElseThrow(() -> new EntityNotFoundException("Especialidade não encontrada"));
+
+ List services = serviceService.findByExpertise(expertise);
+
+ List servicesDTO = services.stream()
+ .map(s -> serviceMapper.toDto(s))
+ .collect(Collectors.toList());
+ return servicesDTO;
+
+ } else {
+ List services = serviceService.findAll();
+
+ List servicesDTO = services.stream()
+ .map(s -> serviceMapper.toDto(s))
+ .collect(Collectors.toList());
+
+ return servicesDTO;
+ }
+
+ }
}
\ No newline at end of file
diff --git a/src/main/java/br/edu/utfpr/servicebook/controller/JobContractedController.java b/src/main/java/br/edu/utfpr/servicebook/controller/JobContractedController.java
index 4ff0414e..021be80a 100644
--- a/src/main/java/br/edu/utfpr/servicebook/controller/JobContractedController.java
+++ b/src/main/java/br/edu/utfpr/servicebook/controller/JobContractedController.java
@@ -104,13 +104,13 @@ public String markAsToDo(
JobContracted jobContracted = oJobContracted.get();
if (dto.isConfirm()) {
- DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
JobRequest jobRequest = jobContracted.getJobRequest();
jobRequest.setStatus(JobRequest.Status.TO_DO);
jobRequestService.save(jobRequest);
- jobContracted.setTodoDate(LocalDate.parse(dto.getTodoDate(), dateTimeFormatter));
+// jobContracted.setTodoDate(LocalDate.parse(dto.getTodoDate(), dateTimeFormatter));
+ jobContracted.setTodoDate(LocalDate.parse(dto.getTodoDate()));
jobContractedService.save(jobContracted);
} else {
JobRequest jobRequest = jobContracted.getJobRequest();
diff --git a/src/main/java/br/edu/utfpr/servicebook/controller/JobRequestController.java b/src/main/java/br/edu/utfpr/servicebook/controller/JobRequestController.java
index 00f8f6b7..fb0fa337 100644
--- a/src/main/java/br/edu/utfpr/servicebook/controller/JobRequestController.java
+++ b/src/main/java/br/edu/utfpr/servicebook/controller/JobRequestController.java
@@ -22,6 +22,7 @@
import com.cloudinary.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
@@ -97,16 +98,16 @@ public class JobRequestController {
private TemplateUtil templateUtil;
- public enum RequestDateSelect{
- today(0), tomorrow(1) , thisweek(2), nextweek(3), thismonth(4), nextmonth(5);
+ public enum RequestDateSelect {
+ today(0), tomorrow(1), thisweek(2), nextweek(3), thismonth(4), nextmonth(5);
private int value;
- RequestDateSelect(int value){
+ RequestDateSelect(int value) {
this.value = value;
}
- public int getValue(){
+ public int getValue() {
return value;
}
@@ -115,16 +116,30 @@ public int getValue(){
@GetMapping
@PermitAll
public String showWizard(@RequestParam(value = "passo", required = false, defaultValue = "1") Long step,
+ @RequestParam(value = "especialidade", required = false, defaultValue = "0") Long expertiseId,
HttpSession httpSession,
Model model) throws Exception {
log.debug("Mostrando o passo {}", step);
- if(step < 1 || step > 8){
+ if (step < 1 || step > 5) {
step = 1L;
}
+
+ String currentUserEmail = authentication.getEmail();
+
+ Optional oUser = userService.findByEmail(currentUserEmail);
+// if (!oUser.isPresent()) {
+// return "redirect:/login";
+// }
+
JobRequestDTO dto = wizardSessionUtil.getWizardState(httpSession, JobRequestDTO.class, WizardSessionUtil.KEY_WIZARD_JOB_REQUEST);
model.addAttribute("dto", dto);
- if(step == 1L){
+ if (expertiseId != 0) {
+ JobRequestDTO sessionDTO = wizardSessionUtil.getWizardState(httpSession, JobRequestDTO.class, WizardSessionUtil.KEY_WIZARD_JOB_REQUEST);
+ sessionDTO.setExpertiseId(expertiseId);
+ }
+
+ if (step == 1L) {
List expertise = expertiseService.findAll();
List expertiseDTOs = expertise.stream()
.map(u -> expertiseMapper.toDto(u))
@@ -140,14 +155,14 @@ public String showWizard(@RequestParam(value = "passo", required = false, defaul
public String saveFormRequestedJob(HttpSession httpSession, @Validated(JobRequestDTO.RequestExpertiseGroupValidation.class) JobRequestDTO dto, BindingResult errors, RedirectAttributes redirectAttributes, Model model) throws Exception {
Optional oExpertise = null;
- if(dto.getExpertiseId() != null) {
+ if (dto.getExpertiseId() != null) {
oExpertise = expertiseService.findById(dto.getExpertiseId());
if (!oExpertise.isPresent()) {
- errors.rejectValue("expertiseId","error.dto","Especialidade não encontrada! Por favor, selecione uma especialidade profissional.");
+ errors.rejectValue("expertiseId", "error.dto", "Especialidade não encontrada! Por favor, selecione uma especialidade profissional.");
}
}
- if(errors.hasErrors()){
+ if (errors.hasErrors()) {
model.addAttribute("dto", dto);
model.addAttribute("errors", errors.getAllErrors());
@@ -173,8 +188,7 @@ public String saveFormRequestedJob(HttpSession httpSession, @Validated(JobReques
@PermitAll
public String saveFormDateJob(HttpSession httpSession, @Validated(JobRequestDTO.RequestExpirationGroupValidation.class) JobRequestDTO dto, BindingResult errors, RedirectAttributes redirectAttributes, Model model) throws Exception {
-
- if(errors.hasErrors()){
+ if (errors.hasErrors()) {
model.addAttribute("dto", dto);
model.addAttribute("errors", errors.getAllErrors());
log.debug("Passo 2 {}", dto);
@@ -184,32 +198,32 @@ public String saveFormDateJob(HttpSession httpSession, @Validated(JobRequestDTO.
}
JobRequestDTO sessionDTO = wizardSessionUtil.getWizardState(httpSession, JobRequestDTO.class, WizardSessionUtil.KEY_WIZARD_JOB_REQUEST);
System.out.println("dto.getDateProximity()" + dto.getDateProximity());
- if(dto.getDateProximity() == RequestDateSelect.today.value){
+ if (dto.getDateProximity() == RequestDateSelect.today.value) {
//Hoje
log.debug("HOJE: {}", sessionDTO);
sessionDTO.setDateTarget(DateUtil.getToday());
}
- if(dto.getDateProximity() == RequestDateSelect.tomorrow.value){
+ if (dto.getDateProximity() == RequestDateSelect.tomorrow.value) {
//Amanhã
log.debug("Amanhã: {}", sessionDTO);
sessionDTO.setDateTarget(DateUtil.getTomorrow());
}
- if(dto.getDateProximity() == RequestDateSelect.thisweek.value){
+ if (dto.getDateProximity() == RequestDateSelect.thisweek.value) {
//Esta Semana
log.debug("Esta Semana: {}", sessionDTO);
sessionDTO.setDateTarget(DateUtil.getThisWeek());
}
- if(dto.getDateProximity() == RequestDateSelect.nextweek.value){
+ if (dto.getDateProximity() == RequestDateSelect.nextweek.value) {
//Proxima Semana
log.debug("Proxima Semana: {}", sessionDTO);
sessionDTO.setDateTarget(DateUtil.getNextWeek());
}
- if(dto.getDateProximity() == RequestDateSelect.thismonth.value){
+ if (dto.getDateProximity() == RequestDateSelect.thismonth.value) {
//Este Mês
log.debug("Este Mês: {}", sessionDTO);
sessionDTO.setDateTarget(DateUtil.getThisMonth());
}
- if(dto.getDateProximity() == RequestDateSelect.nextmonth.value){
+ if (dto.getDateProximity() == RequestDateSelect.nextmonth.value) {
//Proximo Mes
log.debug("Proximo Mês: {}", sessionDTO);
sessionDTO.setDateTarget(DateUtil.getNextMonth());
@@ -219,52 +233,53 @@ public String saveFormDateJob(HttpSession httpSession, @Validated(JobRequestDTO.
return "redirect:/requisicoes?passo=3";
}
- @PostMapping("/passo-3")
- @PermitAll
- public String saveFormMaxCandidates(HttpSession httpSession, @Validated(JobRequestDTO.RequestMaxCandidatesGroupValidation.class) JobRequestDTO dto, BindingResult errors, RedirectAttributes redirectAttributes, Model model) throws Exception {
- if(errors.hasErrors()){
- model.addAttribute("dto", dto);
- model.addAttribute("errors", errors.getAllErrors());
-
- log.debug("Passo 3 {}", dto);
- log.debug("Errors 3 {}", errors);
- return "client/job-request/wizard-step-03";
-
- }
- JobRequestDTO sessionDTO = wizardSessionUtil.getWizardState(httpSession, JobRequestDTO.class, WizardSessionUtil.KEY_WIZARD_JOB_REQUEST);
- sessionDTO.setQuantityCandidatorsMax(dto.getQuantityCandidatorsMax());
-
- log.debug("Passo 3 {}", sessionDTO);
- return "redirect:/requisicoes?passo=4";
-
- }
+// @PostMapping("/passo-3")
+// @PermitAll
+// public String saveFormMaxCandidates(HttpSession httpSession, @Validated(JobRequestDTO.RequestMaxCandidatesGroupValidation.class) JobRequestDTO dto, BindingResult errors, RedirectAttributes redirectAttributes, Model model) throws Exception {
+// if(errors.hasErrors()){
+// model.addAttribute("dto", dto);
+// model.addAttribute("errors", errors.getAllErrors());
+//
+// log.debug("Passo 3 {}", dto);
+// log.debug("Errors 3 {}", errors);
+// return "client/job-request/wizard-step-03";
+//
+// }
+// JobRequestDTO sessionDTO = wizardSessionUtil.getWizardState(httpSession, JobRequestDTO.class, WizardSessionUtil.KEY_WIZARD_JOB_REQUEST);
+// sessionDTO.setQuantityCandidatorsMax(dto.getQuantityCandidatorsMax());
+//
+// log.debug("Passo 3 {}", sessionDTO);
+// return "redirect:/requisicoes?passo=4";
+//
+// }
- @PostMapping("/passo-4")
+ @PostMapping("/passo-3")
@PermitAll
public String saveFormDescription(HttpSession httpSession, @Validated(JobRequestDTO.RequestDescriptionGroupValidation.class) JobRequestDTO dto, BindingResult errors, RedirectAttributes redirectAttributes, Model model) throws Exception {
-
- if(errors.hasErrors()){
+ if (errors.hasErrors()) {
model.addAttribute("dto", dto);
model.addAttribute("errors", errors.getAllErrors());
log.debug("Passo 4 {}", dto);
log.debug("Errors 4 {}", errors);
- return "client/job-request/wizard-step-04";
+ return "client/job-request/wizard-step-03";
}
JobRequestDTO sessionDTO = wizardSessionUtil.getWizardState(httpSession, JobRequestDTO.class, WizardSessionUtil.KEY_WIZARD_JOB_REQUEST);
sessionDTO.setDescription(dto.getDescription());
+ sessionDTO.setQuantityCandidatorsMax(5); // valor padrão
log.debug("Passo 4 {}", sessionDTO);
- return "redirect:/requisicoes?passo=5";
+ return "redirect:/requisicoes?passo=4";
}
/**
* Cadastra várias imagens, mas um POST para cada imagem.
* Para cadastrar várias imagens, é necessário fazer um POST para cada imagem.
+ *
* @param httpSession
* @param redirectAttributes
* @param dto
@@ -272,28 +287,58 @@ public String saveFormDescription(HttpSession httpSession, @Validated(JobRequest
* @return
* @throws IOException
*/
- @PostMapping("/passo-5")
+ @PostMapping("/passo-4")
@PermitAll
public String saveFormImagePath(HttpSession httpSession, RedirectAttributes redirectAttributes, JobRequestDTO dto, Model model) throws IOException {
-
//persiste na sessão
JobRequestDTO sessionDTO = wizardSessionUtil.getWizardState(httpSession, JobRequestDTO.class, WizardSessionUtil.KEY_WIZARD_JOB_REQUEST);
sessionDTO.setImageFile(dto.getImageFile());
+ Optional oExpertise = expertiseService.findById(sessionDTO.getExpertiseId());
+
+ if (!oExpertise.isPresent()) {
+ throw new InvalidParamsException("A especilidade informada não foi encontrada!");
+ }
- System.out.println(sessionDTO.getExpertiseId());
+ /* Verifica se o usuário está logado, pois pode submeter um anuncio sem estar logado. */
+ User user = null;
+ Optional oUser = userService.findByEmail(authentication.getEmail());
+ if (oUser.isPresent()) {
+ user = oUser.get();
+ }
- if(isValidateImage(dto.getImageFile())){
+ if (isValidateImage(dto.getImageFile())) {
File jobImage = Files.createTempFile("temp", dto.getImageFile().getOriginalFilename()).toFile();
dto.getImageFile().transferTo(jobImage);
Map data = cloudinary.uploader().upload(jobImage, ObjectUtils.asMap("folder", "jobs"));
+ sessionDTO.setImageSession((String) data.get("url"));
+
+ Expertise exp = oExpertise.get();
+ sessionDTO.setClientConfirmation(true);
+ sessionDTO.setDateCreated(DateUtil.getToday());
+ sessionDTO.setStatus(JobRequest.Status.AVAILABLE.toString());
+
+ log.debug("Passo 7 {}", sessionDTO);
+ JobRequest jobRequest = jobRequestMapper.toEntity(sessionDTO);
+ jobRequest.setExpertise(exp);
+ jobRequest.setUser(user);
+
+ //jobRequest.setImage(sessionDTO.getImageSession());
+ jobRequestService.save(jobRequest);
+ //envia a notificação SSE
+ if (jobRequest.getUser() != null) {
+ EventSSE eventSse = new EventSSE(EventSSE.Status.JOB_CONFIRMED, jobRequest.getDescription().toString(), user.getName(), jobRequest.getUser().getName(), jobRequest.getUser().getEmail());
+ sseService.send(eventSse);
+ System.out.println("Push: " + eventSse.getMessage());
+ }
+
+ redirectAttributes.addFlashAttribute("msg", "Requisição confirmada!");
- sessionDTO.setImageSession((String)data.get("url"));
- log.debug("Passo 5 {}", sessionDTO);
+// return "redirect:/requisicoes?passo=7";
+ return "redirect:/requisicoes/passo-5";
- return "redirect:/requisicoes/passo=5";
} else {
- return "redirect:/requisicoes/passo=5";
+ return "redirect:/requisicoes/passo=4";
}
}
@@ -315,6 +360,7 @@ public String saveFormImagePath(HttpSession httpSession, RedirectAttributes redi
/**
* Salva a requisição
+ *
* @param httpSession
* @param dto
* @param redirectAttributes
@@ -323,20 +369,20 @@ public String saveFormImagePath(HttpSession httpSession, RedirectAttributes redi
*/
@PostMapping("/passo-7")
@PermitAll
- public String saveFormVerification(HttpSession httpSession, JobRequestDTO dto, RedirectAttributes redirectAttributes, Model model){
+ public String saveFormVerification(HttpSession httpSession, JobRequestDTO dto, RedirectAttributes redirectAttributes, Model model) {
JobRequestDTO sessionDTO = wizardSessionUtil.getWizardState(httpSession, JobRequestDTO.class, WizardSessionUtil.KEY_WIZARD_JOB_REQUEST);
Optional oExpertise = expertiseService.findById(sessionDTO.getExpertiseId());
- if(!oExpertise.isPresent()){
+ if (!oExpertise.isPresent()) {
throw new InvalidParamsException("A especilidade informada não foi encontrada!");
}
/* Verifica se o usuário está logado, pois pode submeter um anuncio sem estar logado. */
User user = null;
Optional oUser = userService.findByEmail(authentication.getEmail());
- if(oUser.isPresent()){
- user = oUser.get();
+ if (oUser.isPresent()) {
+ user = oUser.get();
}
Expertise exp = oExpertise.get();
@@ -357,21 +403,23 @@ public String saveFormVerification(HttpSession httpSession, JobRequestDTO dto, R
System.out.println("Push: " + eventSse.getMessage());
redirectAttributes.addFlashAttribute("msg", "Requisição confirmada!");
- return "redirect:/requisicoes/passo-8";
+ return "redirect:/requisicoes/passo-5";
}
/**
* Mostra os profissionais resultado da busca
+ *
* @param httpSession
* @return
*/
- @GetMapping("/passo-8")
+ @GetMapping("/passo-5")
@PermitAll
protected ModelAndView showProfessionals(HttpSession httpSession) {
- ModelAndView mv = new ModelAndView("client/job-request/wizard-step-08");
+ ModelAndView mv = new ModelAndView("client/job-request/wizard-step-05");
JobRequestDTO sessionDTO = wizardSessionUtil.getWizardState(httpSession, JobRequestDTO.class, WizardSessionUtil.KEY_WIZARD_JOB_REQUEST);
-
+ System.out.println("toto");
+ System.out.println(sessionDTO);
Optional expertise = expertiseService.findById(sessionDTO.getExpertiseId());
List professionals = individualService.findDistinctByTermIgnoreCase(expertise.get().getName());
@@ -380,9 +428,6 @@ protected ModelAndView showProfessionals(HttpSession httpSession) {
.map(s -> individualMapper.toSearchItemDto(s, individualService.getExpertises(s)))
.collect(Collectors.toList());
-
-
-
mv.addObject("professionals", professionalSearchItemDTOS);
mv.addObject("professionalsAmount", professionalSearchItemDTOS.size());
@@ -397,6 +442,7 @@ protected ModelAndView showProfessionals(HttpSession httpSession) {
* depois que realizao login na aplicação.
* Esta requisição de serviço é pega da sessão e então, é salva no BD e o usuário é encaminhado para este endereço.
* TODO apresentar uma mensagem de erro genérica no JSP caso error seja true
+ *
* @return
*/
// @GetMapping("pedido-recebido")
@@ -415,12 +461,11 @@ protected ModelAndView showProfessionals(HttpSession httpSession) {
//
// return mv;
// }
-
- public boolean isValidateImage(MultipartFile image){
+ public boolean isValidateImage(MultipartFile image) {
List contentTypes = Arrays.asList("image/png", "image/jpg", "image/jpeg");
- for(int i = 0; i < contentTypes.size(); i++){
- if(image.getContentType().toLowerCase().startsWith(contentTypes.get(i))){
+ for (int i = 0; i < contentTypes.size(); i++) {
+ if (image.getContentType().toLowerCase().startsWith(contentTypes.get(i))) {
return true;
}
}
@@ -431,6 +476,7 @@ public boolean isValidateImage(MultipartFile image){
/**
* O profissional solicita para não ver mais o JobRequest informado na lista de disponíveis, não tendo interesse.
* A persistência é temporária na tabela, pois ao passar de uns dias será removido por um job assíncrono.
+ *
* @param id
* @param redirectAttributes
* @return
@@ -442,12 +488,12 @@ public String rememberToHide(@PathVariable Long id, RedirectAttributes redirectA
String currentUserEmail = authentication.getEmail();
Optional oUser = userService.findByEmail(currentUserEmail);
- if(!oUser.isPresent()){
+ if (!oUser.isPresent()) {
throw new EntityNotFoundException("O usuário não foi encontrado!");
}
Optional oJobRequest = jobRequestService.findById(id);
- if(!oJobRequest.isPresent()) {
+ if (!oJobRequest.isPresent()) {
throw new EntityNotFoundException("Candidatura não encontrada!");
}
@@ -456,4 +502,4 @@ public String rememberToHide(@PathVariable Long id, RedirectAttributes redirectA
return "redirect:/minha-conta/profissional#disponiveis";
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/br/edu/utfpr/servicebook/controller/MyAccountController.java b/src/main/java/br/edu/utfpr/servicebook/controller/MyAccountController.java
index a5ad97f4..e347edd7 100644
--- a/src/main/java/br/edu/utfpr/servicebook/controller/MyAccountController.java
+++ b/src/main/java/br/edu/utfpr/servicebook/controller/MyAccountController.java
@@ -97,6 +97,8 @@ public class MyAccountController {
@Autowired
private ModerateService moderateService;
+ @Autowired
+ private StateService stateService;
private String userSmsErrorForwarding(String step, UserSmsDTO dto, Model model, BindingResult errors) {
model.addAttribute("dto", dto);
model.addAttribute("errors", errors.getAllErrors());
@@ -906,6 +908,92 @@ public String updateMyPersonalData(@PathVariable Long id,
redirectAttributes.addFlashAttribute("msg", "Informações pessoais atualizadas com sucesso!");
return "redirect:/minha-conta/informacoes-pessoais/" + id;
}
+
+ @GetMapping("/meu-endereco/{id}")
+ @RolesAllowed({RoleType.USER, RoleType.COMPANY})
+ public ModelAndView showMyAddress(@PathVariable Long id) throws IOException {
+
+ Optional oUser = this.userService.findById(id);
+
+ if (!oUser.isPresent()) {
+ throw new EntityNotFoundException("O usuário não foi encontrado.");
+ }
+
+ Optional oUserAuthenticated = this.userService.findByEmail(authentication.getEmail());
+
+ User userAuthenticated = oUserAuthenticated.get();
+
+ if (id != userAuthenticated.getId()) {
+ throw new AuthenticationCredentialsNotFoundException("Você não tem permissão para atualizar essas informações pessoais.");
+ }
+
+ UserDTO userDTO = userMapper.toDto(userAuthenticated);
+
+ List cities = cityService.findAll();
+ List states = stateService.findAll();
+
+ ModelAndView mv = new ModelAndView("professional/account/my-address");
+ mv.addObject("userDTO", userDTO);
+ mv.addObject("cities", cities);
+ mv.addObject("states", states);
+ return mv;
+ }
+
+ /**
+ * Atualiza o endereço do indivíduo e empresa
+ * @param addressDTO
+ * @param errors
+ * @param redirectAttributes
+ * @return
+ * @throws IOException
+ */
+ @PatchMapping("/salvar-endereco/{id}")
+ @RolesAllowed({RoleType.USER, RoleType.COMPANY})
+ public String updateMyAddress(@PathVariable Long id,
+ AddressDTO addressDTO,
+ BindingResult errors,
+ RedirectAttributes redirectAttributes
+ ) throws IOException {
+
+ if (errors.hasErrors()) {
+ redirectAttributes.addFlashAttribute("errors", errors.getAllErrors());
+ return "redirect:/minha-conta/meu-endereco/" + id;
+ }
+
+ Optional oUser = this.userService.findById(id);
+
+ if (!oUser.isPresent()) {
+ throw new EntityNotFoundException("O usuário não foi encontrado.");
+ }
+
+ Optional oUserAuthenticated = this.userService.findByEmail(authentication.getEmail());
+ User userAuthenticated = oUserAuthenticated.get();
+
+ if (id != userAuthenticated.getId()) {
+ throw new AuthenticationCredentialsNotFoundException("Você não tem permissão para atualizar o endereço.");
+ }
+
+ Optional oInvididual = this.individualService.findById(id);
+
+ Optional ocity = this.cityService.findByName(addressDTO.getCity());
+
+ Individual individual = oInvididual.get();
+ Address address = new Address();
+
+ address.setPostalCode(addressDTO.getPostalCode());
+ address.setNeighborhood(addressDTO.getNeighborhood());
+ address.setNumber(addressDTO.getNumber());
+ address.setStreet(addressDTO.getStreet());
+ address.setCity(ocity.get());
+
+ individual.setAddress(address);
+
+ this.individualService.save(individual);
+
+
+ redirectAttributes.addFlashAttribute("msg", "Endereço atualizado com sucesso!");
+ return "redirect:/minha-conta/meu-endereco/" + id;
+ }
}
diff --git a/src/main/java/br/edu/utfpr/servicebook/controller/MyAdsController.java b/src/main/java/br/edu/utfpr/servicebook/controller/MyAdsController.java
new file mode 100644
index 00000000..b8b3a498
--- /dev/null
+++ b/src/main/java/br/edu/utfpr/servicebook/controller/MyAdsController.java
@@ -0,0 +1,328 @@
+package br.edu.utfpr.servicebook.controller;
+
+import br.edu.utfpr.servicebook.model.dto.*;
+import br.edu.utfpr.servicebook.model.entity.*;
+import br.edu.utfpr.servicebook.model.mapper.ExpertiseMapper;
+import br.edu.utfpr.servicebook.model.mapper.ServiceMapper;
+import br.edu.utfpr.servicebook.security.IAuthentication;
+import br.edu.utfpr.servicebook.security.RoleType;
+import br.edu.utfpr.servicebook.service.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.stereotype.Controller;
+import org.springframework.validation.BindingResult;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.servlet.ModelAndView;
+import org.springframework.web.servlet.mvc.support.RedirectAttributes;
+import javax.annotation.security.PermitAll;
+import javax.annotation.security.RolesAllowed;
+import javax.persistence.EntityNotFoundException;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+@RequestMapping("/minha-conta/profissional/meus-anuncios")
+@Controller
+public class MyAdsController {
+ public static final Logger log = LoggerFactory.getLogger(ProfessionalHomeController.class);
+
+ @Autowired
+ private ServiceService serviceService;
+
+ @Autowired
+ private ServiceMapper serviceMapper;
+
+ @Autowired
+ private ExpertiseService expertiseService;
+
+ @Autowired
+ private ExpertiseMapper expertiseMapper;
+
+ @Autowired
+ private ProfessionalServiceOfferingService professionalServiceOfferingService;
+
+ @Autowired
+ private UserService userService;
+
+ @Autowired
+ private IAuthentication authentication;
+
+ @Autowired
+ private ProfessionalServicePackageOfferingService professionalServicePackageOfferingService;
+
+ @Autowired
+ private ProfessionalServiceOfferingAdItemService professionalServiceOfferingAdItemService;
+
+ @GetMapping
+ @PermitAll
+ protected ModelAndView showMyAds() throws Exception {
+ ModelAndView mv = new ModelAndView("professional/my-ads");
+ Optional oUser = (userService.findByEmail(authentication.getEmail()));
+
+ //paginação de serviços
+ PageRequest pageRequest = PageRequest.of(0, 5);
+ Page servicePage = serviceService.findAll(pageRequest);
+
+ Page expertisePage = expertiseService.findAll(pageRequest);
+
+ List expertiseDTOS = expertisePage.stream()
+ .map(s -> expertiseMapper.toDto(s))
+ .collect(Collectors.toList());
+
+ List serviceDTOS = servicePage.stream()
+ .map(s -> serviceMapper.toDto(s))
+ .collect(Collectors.toList());
+
+ List professionalServiceOfferings = professionalServiceOfferingService.findProfessionalServiceOfferingByUser(oUser.get());
+ List servicesIndividuals = professionalServiceOfferingService.findFirst3ProfessionalServiceOfferingByUserAndType(oUser.get(), ProfessionalServiceOffering.Type.INDIVIDUAL);
+
+ List servicesPackages = professionalServicePackageOfferingService.findAllByUserAndType(oUser.get(), ProfessionalServicePackageOffering.Type.SIMPLE_PACKAGE);
+ List servicesCombined = professionalServicePackageOfferingService.findByTypeAndUser(oUser.get(), ProfessionalServicePackageOffering.Type.COMBINED_PACKAGE);
+ List teste = professionalServiceOfferingAdItemService.findAllByProfessionalServicePackageOfferingUser(oUser.get());
+
+ mv.addObject("expertises", expertiseDTOS);
+ mv.addObject("professionalServiceOfferings", professionalServiceOfferings);
+ mv.addObject("servicesIndividuals", servicesIndividuals);
+ mv.addObject("servicesPackages", servicesPackages);
+ mv.addObject("servicesCombined", servicesCombined);
+ mv.addObject("teste", teste);
+ return mv;
+ }
+
+ @GetMapping("/novo")
+ @PermitAll
+ protected ModelAndView registerMyAds() throws Exception {
+ ModelAndView mv = new ModelAndView("professional/my-ads-register");
+
+ //paginação de serviços
+ PageRequest pageRequest = PageRequest.of(0, 5);
+
+ List expertises = expertiseService.findAll();
+ List expertiseDTOs = expertises.stream()
+ .map(s -> expertiseMapper.toDto(s))
+ .collect(Collectors.toList());
+ mv.addObject("expertises", expertiseDTOs);
+
+ Page servicePage = serviceService.findAll(pageRequest);
+ List serviceDTOS = servicePage.stream()
+ .map(s -> serviceMapper.toDto(s))
+ .collect(Collectors.toList());
+// mv.addObject("services", serviceDTOS);
+ return mv;
+ }
+
+ /**
+ * Adiciona um serviço individual.
+ * @param professionalServiceOfferingDTO
+ * @param errors
+ * @param redirectAttributes
+ * @return
+ * @throws Exception
+ */
+ @PostMapping("/novo/individual")
+ @PermitAll
+ public String saveAds(ProfessionalServiceOfferingDTO professionalServiceOfferingDTO, BindingResult errors, RedirectAttributes
+ redirectAttributes) throws Exception {
+ Optional oUser = (userService.findByEmail(authentication.getEmail()));
+
+ ModelAndView mv = new ModelAndView("professional/my-ads-register");
+
+ ProfessionalServiceOffering professionalServiceOffering = new ProfessionalServiceOffering();
+ Optional oService = serviceService.findById(professionalServiceOfferingDTO.getServiceId());
+ Optional oExpertise = expertiseService.findById(professionalServiceOfferingDTO.getExpertiseId());
+
+ professionalServiceOffering.setUser(oUser.get());
+ professionalServiceOffering.setPrice(professionalServiceOfferingDTO.getPrice());
+ professionalServiceOffering.setUnit(professionalServiceOfferingDTO.getUnit());
+ professionalServiceOffering.setDuration(professionalServiceOfferingDTO.getDuration());
+ professionalServiceOffering.setType(ProfessionalServiceOffering.Type.INDIVIDUAL);
+
+ professionalServiceOffering.setDescription(professionalServiceOfferingDTO.getDescription());
+ if(oService.isPresent()){
+ professionalServiceOffering.setService(oService.get());
+ }
+ if(oExpertise.isPresent()){
+ professionalServiceOffering.setExpertise(oExpertise.get());
+ }
+ //grava o nome do serviço original
+ professionalServiceOffering.setName(oService.get().getName());
+ professionalServiceOfferingService.save(professionalServiceOffering);
+
+ return("redirect:/minha-conta/profissional/meus-anuncios");
+ }
+
+ /**
+ * Adiciona um pacote de serviço.
+ * @param professionalServicePackageOfferingDTO
+ * @param professionalServiceOfferingDTO
+ * @return
+ * @throws Exception
+ */
+ @PostMapping("/novo/pacote")
+ @PermitAll
+ public String saveAdsPackage(ProfessionalServiceOfferingDTO professionalServiceOfferingDTO, ProfessionalServicePackageOfferingDTO professionalServicePackageOfferingDTO, BindingResult errors, RedirectAttributes
+ redirectAttributes) throws Exception {
+ Optional oUser = (userService.findByEmail(authentication.getEmail()));
+ ModelAndView mv = new ModelAndView("professional/my-ads-register");
+
+ Optional oService = serviceService.findById(professionalServicePackageOfferingDTO.getServiceId());
+
+ ProfessionalServicePackageOffering professionalServicePackageOffering = new ProfessionalServicePackageOffering();
+ professionalServicePackageOffering.setPrice(professionalServicePackageOfferingDTO.getPrice());
+ professionalServicePackageOffering.setType(ProfessionalServicePackageOffering.Type.SIMPLE_PACKAGE);
+ professionalServicePackageOffering.setUnit(professionalServicePackageOfferingDTO.getUnit());
+ professionalServicePackageOffering.setDuration(professionalServicePackageOfferingDTO.getDuration());
+ professionalServicePackageOffering.setDescription(professionalServicePackageOfferingDTO.getDescription());
+ //grava o nome do serviço original
+ professionalServicePackageOffering.setName(oService.get().getName());
+ professionalServicePackageOffering.setAmount(professionalServicePackageOfferingDTO.getAmount());
+ professionalServicePackageOffering.setUser(oUser.get());
+ professionalServicePackageOffering.setService(oService.get());
+
+ professionalServicePackageOfferingService.save(professionalServicePackageOffering);
+
+ return("redirect:/minha-conta/profissional/meus-anuncios");
+ }
+ /**
+ * Adiciona um serviço combinado com um ou mais serviços.
+ * @param professionalServicePackageOfferingDTO
+ * @param professionalServiceOfferingDTO
+ * @return
+ * @throws Exception
+ */
+ @PostMapping("/novo/combinado")
+ @PermitAll
+ public String saveAdsCombined(ProfessionalServiceOfferingDTO professionalServiceOfferingDTO, ProfessionalServicePackageOfferingDTO professionalServicePackageOfferingDTO, BindingResult errors, RedirectAttributes
+ redirectAttributes) throws Exception {
+ Optional oUser = (userService.findByEmail(authentication.getEmail()));
+ Optional oExpertise = expertiseService.findById(professionalServicePackageOfferingDTO.getExpertiseId());
+
+ ModelAndView mv = new ModelAndView("professional/my-ads-register");
+ ProfessionalServicePackageOffering professionalServicePackageOffering = new ProfessionalServicePackageOffering();
+ professionalServicePackageOffering.setPrice(professionalServicePackageOfferingDTO.getPrice());
+ professionalServicePackageOffering.setType(ProfessionalServicePackageOffering.Type.COMBINED_PACKAGE);
+ professionalServicePackageOffering.setUnit(professionalServicePackageOfferingDTO.getUnit());
+ professionalServicePackageOffering.setDuration(professionalServicePackageOfferingDTO.getDuration());
+ professionalServicePackageOffering.setDescription(professionalServicePackageOfferingDTO.getDescription());
+ professionalServicePackageOffering.setName(professionalServicePackageOfferingDTO.getDescription());
+ professionalServicePackageOffering.setExpertise(oExpertise.get());
+ professionalServicePackageOffering.setName(professionalServicePackageOfferingDTO.getDescription());
+
+ //grava o nome do serviço original
+ professionalServicePackageOffering.setUser(oUser.get());
+
+ professionalServicePackageOfferingService.save(professionalServicePackageOffering);
+
+ for (Long valor : professionalServiceOfferingDTO.getDescriptions()) {
+ ProfessionalServiceOffering professionalServiceOffering = new ProfessionalServiceOffering();
+ Optional oService = serviceService.findById(valor);
+
+ professionalServiceOffering.setDescription(professionalServicePackageOfferingDTO.getDescription());
+ //grava o nome do serviço original
+ professionalServiceOffering.setName(oService.get().getName());
+ professionalServiceOffering.setType(ProfessionalServiceOffering.Type.COMBINED_PACKAGE);
+ professionalServiceOffering.setUnit(professionalServiceOfferingDTO.getUnit());
+ professionalServiceOffering.setDuration(professionalServiceOfferingDTO.getDuration());
+ professionalServiceOffering.setPrice(professionalServiceOfferingDTO.getPrice());
+ professionalServiceOffering.setUser(oUser.get());
+ professionalServiceOffering.setService(oService.get());
+ professionalServiceOfferingService.save(professionalServiceOffering);
+//
+ ProfessionalServiceOfferingAdItem professionalServiceOfferingAdItem = new ProfessionalServiceOfferingAdItem(professionalServiceOffering, professionalServicePackageOffering);
+ professionalServiceOfferingAdItemService.save(professionalServiceOfferingAdItem);
+
+ }
+
+ return("redirect:/minha-conta/profissional/meus-anuncios");
+ }
+ @GetMapping("/pacotes")
+ @PermitAll
+ protected ModelAndView showMyAdsPackages() throws Exception {
+ ModelAndView mv = new ModelAndView("professional/ads/my-ads-packages");
+ Optional oUser = (userService.findByEmail(authentication.getEmail()));
+
+ //paginação de serviços
+ PageRequest pageRequest = PageRequest.of(0, 5);
+ Page servicePage = serviceService.findAll(pageRequest);
+ List serviceDTOS = servicePage.stream()
+ .map(s -> serviceMapper.toDto(s))
+ .collect(Collectors.toList());
+
+ List servicesPackages = professionalServicePackageOfferingService.findByTypeAndUser(oUser.get(), ProfessionalServicePackageOffering.Type.SIMPLE_PACKAGE);
+
+ mv.addObject("services", serviceDTOS);
+ mv.addObject("servicesPackages", servicesPackages);
+ return mv;
+ }
+
+ @GetMapping("/individuais")
+ @PermitAll
+ protected ModelAndView showMyAdsIndividuals() throws Exception {
+ ModelAndView mv = new ModelAndView("professional/ads/my-ads-individuals");
+ Optional oUser = (userService.findByEmail(authentication.getEmail()));
+
+ //paginação de serviços
+ PageRequest pageRequest = PageRequest.of(0, 5);
+ Page servicePage = serviceService.findAll(pageRequest);
+ List serviceDTOS = servicePage.stream()
+ .map(s -> serviceMapper.toDto(s))
+ .collect(Collectors.toList());
+
+ List professionalServiceOfferings = professionalServiceOfferingService.findProfessionalServiceOfferingByUserAndType(oUser.get(), ProfessionalServiceOffering.Type.INDIVIDUAL);
+
+ mv.addObject("services", serviceDTOS);
+ mv.addObject("professionalServiceOfferings", professionalServiceOfferings);
+ return mv;
+ }
+
+ @GetMapping("/combinados")
+ @PermitAll
+ protected ModelAndView showMyAdsCombineds() throws Exception {
+ ModelAndView mv = new ModelAndView("professional/ads/my-ads-combineds");
+ Optional oUser = (userService.findByEmail(authentication.getEmail()));
+
+ //paginação de serviços
+ PageRequest pageRequest = PageRequest.of(0, 5);
+ Page servicePage = serviceService.findAll(pageRequest);
+ List serviceDTOS = servicePage.stream()
+ .map(s -> serviceMapper.toDto(s))
+ .collect(Collectors.toList());
+
+ List servicesCombined = professionalServicePackageOfferingService.findByTypeAndUser(oUser.get(), ProfessionalServicePackageOffering.Type.COMBINED_PACKAGE);
+
+ mv.addObject("services", serviceDTOS);
+ mv.addObject("servicesCombined", servicesCombined);
+ return mv;
+ }
+ @GetMapping("/especialidade/{expertiseId}")
+ @RolesAllowed({RoleType.USER, RoleType.COMPANY})
+ @ResponseBody
+ public List findAdsByExpertise(@PathVariable Long expertiseId) throws Exception {
+
+ User professional = this.getAuthenticatedUser();
+
+ Expertise expertise = expertiseService.findById(expertiseId).orElseThrow(() -> new EntityNotFoundException("Especialidade não encontrada"));
+
+ //lista de serviços
+ List services = serviceService.findByExpertise(expertise);
+ List professionalServiceOfferings = professionalServiceOfferingService.findProfessionalServiceOfferingByUserAndExpertise(professional.getId(), expertiseId);
+
+ return professionalServiceOfferings;
+ }
+ /**
+ * Retorna o indivíduo logado.
+ * @return
+ * @throws Exception
+ */
+ private User getAuthenticatedUser() throws Exception {
+ Optional oProfessional = (userService.findByEmail(authentication.getEmail()));
+
+ if (!oProfessional.isPresent()) {
+ throw new EntityNotFoundException("Usuário não autenticado! Por favor, realize sua autenticação no sistema.");
+ }
+
+ return oProfessional.get();
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/br/edu/utfpr/servicebook/controller/ProfessionalController.java b/src/main/java/br/edu/utfpr/servicebook/controller/ProfessionalController.java
index e64b516c..02f2d7cf 100644
--- a/src/main/java/br/edu/utfpr/servicebook/controller/ProfessionalController.java
+++ b/src/main/java/br/edu/utfpr/servicebook/controller/ProfessionalController.java
@@ -2,10 +2,7 @@
import br.edu.utfpr.servicebook.model.dto.*;
import br.edu.utfpr.servicebook.model.entity.*;
-import br.edu.utfpr.servicebook.model.mapper.IndividualMapper;
-import br.edu.utfpr.servicebook.model.mapper.JobContractedMapper;
-import br.edu.utfpr.servicebook.model.mapper.ProfessionalServiceOfferingMapper;
-import br.edu.utfpr.servicebook.model.mapper.UserMapper;
+import br.edu.utfpr.servicebook.model.mapper.*;
import br.edu.utfpr.servicebook.security.IAuthentication;
import br.edu.utfpr.servicebook.service.*;
@@ -15,8 +12,10 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
+import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
+import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.annotation.security.PermitAll;
import javax.persistence.EntityNotFoundException;
@@ -73,6 +72,30 @@ public class ProfessionalController {
@Autowired
private PaginationUtil paginationUtil;
+ @Autowired
+ private ServiceService serviceService;
+
+ @Autowired
+ private ExpertiseService expertiseService;
+
+ @Autowired
+ private CategoryService categoryService;
+
+ @Autowired
+ private CategoryMapper categoryMapper;
+
+ @Autowired
+ private AssessmentProfessionalMapper assessmentProfessionalMapper;
+
+ @Autowired
+ private AssessmentProfessionalService assessmentProfessionalService;
+
+ @Autowired
+ private AssessmentProfessionalFileMapper assessmentProfessionalFileMapper;
+
+ @Autowired
+ private AssessmentResponseService assessmentResponseService;
+
@GetMapping
@PermitAll
protected ModelAndView showAll() throws Exception {
@@ -106,7 +129,8 @@ protected ModelAndView showAll() throws Exception {
* Retorna a lista de profissionais de acordo com o termo de busca.
* Se estiver logado, o usuário poderá ter acesso a todos os profissionais de acordo com a sua busca.
* Caso seja um visitante, terá acesso a apenas 4 profissionais.
- * @param searchTerm
+ *
+ * @param searchService
* @param page
* @return
* @throws Exception
@@ -114,8 +138,12 @@ protected ModelAndView showAll() throws Exception {
@GetMapping(value = "/busca")
@PermitAll
protected ModelAndView showSearchResults(
- @RequestParam(value = "termo-da-busca") String searchTerm,
- @RequestParam(value = "pag", defaultValue = "1") int page
+// @RequestParam(value = "termo-da-busca") String searchTerm,
+ @RequestParam(defaultValue = "0", value = "serviceId") Long searchService,
+ @RequestParam(defaultValue = "", value = "expertiseId") Long searchExpertise,
+ @RequestParam(defaultValue = "", value = "categoryId") Long searchCategory,
+ @RequestParam(value = "pag", defaultValue = "1") int page,
+ RedirectAttributes redirectAttributes
) throws Exception {
ModelAndView mv = new ModelAndView("visitor/search-results");
@@ -132,17 +160,59 @@ protected ModelAndView showSearchResults(
page = 1;
size = this.paginationSizeVisitor;
}
+ if (searchService == 0) {
+ redirectAttributes.addFlashAttribute("msg", "A atualização foi salva com sucesso!");
+ } else {
- Page professionals = individualService.findDistinctByTermIgnoreCaseWithPagination(searchTerm, page, size);
- List professionalSearchItemDTOS = professionals.stream()
- .map(s -> individualMapper.toSearchItemDto(s, individualService.getExpertises(s)))
- .collect(Collectors.toList());
+ Optional service = serviceService.findById(searchService);
+ Optional expertise = expertiseService.findById(searchExpertise);
+ Optional category = categoryService.findById(searchCategory);
+
+ Page professionals = individualService.findAllIndividualsByService(service.get(), page, size);
+ Page professionalServiceOfferings = professionalServiceOfferingService.findAllIndividualsByService(service.get(), page, size);
+
+ List professionalSearchItemDTOS = professionals.stream()
+ .map(s -> individualMapper.toSearchItemDto(s, individualService.getExpertises(s)))
+ .collect(Collectors.toList());
+
+ List professionalServiceOfferingDTOS = professionalServiceOfferings.stream()
+ .map(s -> professionalServiceOfferingMapper.toDTO(s)).collect(Collectors.toList());
+
+ //lista de categorias
+ List categories = categoryService.findAll();
+ List categoryDTOs = categories.stream()
+ .map(s -> categoryMapper.toDto(s))
+ .collect(Collectors.toList());
- PaginationDTO paginationDTO = paginationUtil.getPaginationDTO(professionals, "/profissionais/busca?termo-da-busca="+ searchTerm);
- mv.addObject("professionals", professionalSearchItemDTOS);
- mv.addObject("pagination", paginationDTO);
- mv.addObject("isParam", true);
- mv.addObject("searchTerm", searchTerm);
+ Page professionalsByExpertise = individualService.findDistinctByExpertiseAndCategoryPagination(expertise.get(), page, size);
+
+ Page listProfessionals = individualService.listByExpertiseAndCategory(expertise.get(), category.get(), page, size);
+
+ List professionalSearchItemDTOS2 = professionalsByExpertise.stream()
+ .map(s -> individualMapper.toSearchItemDto(s, individualService.getExpertises(s)))
+ .collect(Collectors.toList());
+
+ List professionals1 = individualService.findAllIndividualsAutonomosByService(expertise.get().getId(), page, size);
+
+ List professionalSearchItemDTOS1 = professionals1.stream()
+ .map(s -> individualMapper.toSearchItemDto(s, individualService.getExpertises(s)))
+ .collect(Collectors.toList());
+
+ PaginationDTO paginationDTO = paginationUtil.getPaginationDTO(professionalServiceOfferings, "/profissionais/busca?termo-da-busca=" + searchService);
+
+ mv.addObject("professionals", professionalSearchItemDTOS2);
+ mv.addObject("categoryDTOs", categoryDTOs);
+ mv.addObject("pagination", paginationDTO);
+ mv.addObject("isParam", true);
+ mv.addObject("service", service.get().getName());
+ mv.addObject("searchTerm", searchService);
+ mv.addObject("dto_expertise", expertise.get());
+ mv.addObject("dto", category.get());
+ mv.addObject("dto_service", service.get());
+
+ mv.addObject("professionalServiceOfferingDTOS", professionalServiceOfferingDTOS);
+ mv.addObject("count_results", professionalServiceOfferingDTOS.size());
+ }
return mv;
}
@@ -150,6 +220,7 @@ protected ModelAndView showSearchResults(
/**
* Retorna a página de detalhes do profissional.
* Esta página pode ser acessada de forma autenticada ou anônima.
+ *
* @param id
* @return
* @throws Exception
@@ -160,10 +231,71 @@ protected ModelAndView showProfessionalDetailsToVisitors(@PathVariable("id") Lon
Optional oProfessional = userService.findById(id);
- if(!oProfessional.isPresent()) {
+ if (!oProfessional.isPresent()) {
+ throw new EntityNotFoundException("Profissional não encontrado.");
+ }
+
+ //cliente autenticado, caso esteja logado
+ Optional oClientAuthenticated = (userService.findByEmail(authentication.getEmail()));
+
+ //profissional requisitado
+ UserDTO professionalDTO = userMapper.toDto(oProfessional.get());
+
+ //especialidades do profissional requisitado
+ List expertisesDTO = userService.getExpertiseDTOs(oProfessional.get());
+
+ List professionalExpertises = professionalExpertiseService.findByProfessional(oProfessional.get());
+
+ //serviços por especialidade
+ Map> servicesByExpertise = new HashMap<>();
+ for (ProfessionalExpertise pe : professionalExpertises) {
+ List professionalServiceOfferings = professionalServiceOfferingService.findProfessionalServiceOfferingByUserAndExpertise(oProfessional.get().getId(), pe.getExpertise().getId());
+
+ if (professionalServiceOfferings.isEmpty()) {
+ continue;
+ }
+
+ //transforma para DTO
+ List professionalServiceOfferingsDTO = professionalServiceOfferings.stream()
+ .map(service -> professionalServiceOfferingMapper.toDTO(service))
+ .collect(Collectors.toList());
+
+ servicesByExpertise.put(pe, professionalServiceOfferingsDTO);
+ }
+
+ ModelAndView mv = new ModelAndView("visitor/professional-details");
+ mv.addObject("professional", professionalDTO);
+ mv.addObject("professionalExpertises", expertisesDTO);
+ mv.addObject("logged", oClientAuthenticated.isPresent());
+ mv.addObject("servicesByExpertise", servicesByExpertise);
+
+ //se o cliente está logado, mostra se ele segue o profissional
+ if (oClientAuthenticated.isPresent()) {
+ List follows = followsService.findFollowProfessionalClient(oProfessional.get(), oClientAuthenticated.get());
+ boolean isFollow = !follows.isEmpty();
+ UserDTO clientDTO = userMapper.toDto(oClientAuthenticated.get());
+ mv.addObject("isFollow", isFollow);
+ mv.addObject("client", clientDTO);
+ }
+ return mv;
+ }
+
+ @GetMapping("/detalhes/{id}/profissional/{professional_id}/servico/{service_id}")
+ @PermitAll
+ protected ModelAndView showProfessionalDetailsAndServiceToVisitors(@PathVariable("id") Long id, @PathVariable("professional_id") Long professional_id, @PathVariable("service_id") Long service_id) throws Exception {
+
+ Optional oProfessional = userService.findById(professional_id);
+
+ if (!oProfessional.isPresent()) {
throw new EntityNotFoundException("Profissional não encontrado.");
}
+ Optional oService = serviceService.findById(service_id);
+
+ if (!oService.isPresent()) {
+ throw new EntityNotFoundException("Serviço não encontrado.");
+ }
+
//cliente autenticado, caso esteja logado
Optional oClientAuthenticated = (userService.findByEmail(authentication.getEmail()));
@@ -177,10 +309,10 @@ protected ModelAndView showProfessionalDetailsToVisitors(@PathVariable("id") Lon
//serviços por especialidade
Map> servicesByExpertise = new HashMap<>();
- for(ProfessionalExpertise pe : professionalExpertises) {
+ for (ProfessionalExpertise pe : professionalExpertises) {
List professionalServiceOfferings = professionalServiceOfferingService.findProfessionalServiceOfferingByUserAndExpertise(oProfessional.get().getId(), pe.getExpertise().getId());
- if(professionalServiceOfferings.isEmpty()){
+ if (professionalServiceOfferings.isEmpty()) {
continue;
}
@@ -192,20 +324,48 @@ protected ModelAndView showProfessionalDetailsToVisitors(@PathVariable("id") Lon
servicesByExpertise.put(pe, professionalServiceOfferingsDTO);
}
+ List professionalServiceOfferings = professionalServiceOfferingService.findProfessionalServiceOfferingByServiceAndUser(oService.get().getId(), oProfessional.get().getId());
+ List professionalServiceOfferings1 = professionalServiceOfferingService.findProfessionalServiceOfferingByUser(oProfessional.get());
+
+ /*AVALIAÇÕES*/
+// List assessmentProfessionalList =
+ List