Merge branch 'dev' of github.com:Quantum-P3/datasurvey into feature/US-45

This commit is contained in:
Eduardo Quiros 2021-08-01 21:59:16 -06:00
commit 417c5ef33e
No known key found for this signature in database
GPG Key ID: B77F36C3F12720B4
56 changed files with 3090 additions and 434 deletions

View File

@ -5,6 +5,7 @@ import java.util.Locale;
import javax.mail.MessagingException; import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage;
import org.datasurvey.domain.User; import org.datasurvey.domain.User;
import org.datasurvey.domain.UsuarioEncuesta;
import org.datasurvey.domain.UsuarioExtra; import org.datasurvey.domain.UsuarioExtra;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -111,6 +112,22 @@ public class MailService {
sendEmail(user.getEmail(), subject, content, false, true); sendEmail(user.getEmail(), subject, content, false, true);
} }
@Async
public void sendEmailFromTemplateUsuarioEncuesta(User user, UsuarioEncuesta usuarioEncuesta, String templateName, String titleKey) {
if (user.getEmail() == null) {
log.debug("Email doesn't exist for user '{}'", user.getLogin());
return;
}
Locale locale = Locale.forLanguageTag(user.getLangKey());
Context context = new Context(locale);
context.setVariable(USER, user);
context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
context.setVariable("colaborador", usuarioEncuesta);
String content = templateEngine.process(templateName, context);
String subject = messageSource.getMessage(titleKey, null, locale);
sendEmail(user.getEmail(), subject, content, false, true);
}
@Async @Async
public void sendActivationEmail(User user) { public void sendActivationEmail(User user) {
log.debug("Sending activation email to '{}'", user.getEmail()); log.debug("Sending activation email to '{}'", user.getEmail());
@ -164,4 +181,26 @@ public class MailService {
log.debug("Sending encuesta deletion notification mail to '{}'", user.getUser().getEmail()); log.debug("Sending encuesta deletion notification mail to '{}'", user.getUser().getEmail());
sendEmailFromTemplate(user.getUser(), "mail/encuestaDeletedEmail", "email.encuestaDeleted.title"); sendEmailFromTemplate(user.getUser(), "mail/encuestaDeletedEmail", "email.encuestaDeleted.title");
} }
@Async
public void sendInvitationColaborator(UsuarioEncuesta user) {
log.debug("Sending encuesta invitation collaboration notification mail to '{}'", user.getUsuarioExtra().getUser().getEmail());
sendEmailFromTemplateUsuarioEncuesta(
user.getUsuarioExtra().getUser(),
user,
"mail/invitationColaboratorEmail",
"email.invitation.title"
);
}
@Async
public void sendNotifyDeleteColaborator(UsuarioEncuesta user) {
log.debug("Sending delete collaboration notification mail to '{}'", user.getUsuarioExtra().getUser().getEmail());
sendEmailFromTemplateUsuarioEncuesta(
user.getUsuarioExtra().getUser(),
user,
"mail/deleteColaboratorEmail",
"email.deleteColaborator.title"
);
}
} }

View File

@ -2,11 +2,14 @@ package org.datasurvey.web.rest;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.datasurvey.domain.EPreguntaCerrada;
import org.datasurvey.domain.PPreguntaCerrada;
import org.datasurvey.domain.PPreguntaCerradaOpcion; import org.datasurvey.domain.PPreguntaCerradaOpcion;
import org.datasurvey.repository.PPreguntaCerradaOpcionRepository; import org.datasurvey.repository.PPreguntaCerradaOpcionRepository;
import org.datasurvey.service.PPreguntaCerradaOpcionQueryService; import org.datasurvey.service.PPreguntaCerradaOpcionQueryService;
@ -58,10 +61,15 @@ public class PPreguntaCerradaOpcionResource {
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new pPreguntaCerradaOpcion, or with status {@code 400 (Bad Request)} if the pPreguntaCerradaOpcion has already an ID. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new pPreguntaCerradaOpcion, or with status {@code 400 (Bad Request)} if the pPreguntaCerradaOpcion has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect. * @throws URISyntaxException if the Location URI syntax is incorrect.
*/ */
@PostMapping("/p-pregunta-cerrada-opcions") @PostMapping("/p-pregunta-cerrada-opcions/{id}")
public ResponseEntity<PPreguntaCerradaOpcion> createPPreguntaCerradaOpcion( public ResponseEntity<PPreguntaCerradaOpcion> createPPreguntaCerradaOpcion(
@Valid @RequestBody PPreguntaCerradaOpcion pPreguntaCerradaOpcion @Valid @RequestBody PPreguntaCerradaOpcion pPreguntaCerradaOpcion,
@PathVariable(value = "id", required = false) final Long id
) throws URISyntaxException { ) throws URISyntaxException {
PPreguntaCerrada pPreguntaCerrada = new PPreguntaCerrada();
pPreguntaCerrada.setId(id);
pPreguntaCerradaOpcion.setPPreguntaCerrada(pPreguntaCerrada);
log.debug("REST request to save PPreguntaCerradaOpcion : {}", pPreguntaCerradaOpcion); log.debug("REST request to save PPreguntaCerradaOpcion : {}", pPreguntaCerradaOpcion);
if (pPreguntaCerradaOpcion.getId() != null) { if (pPreguntaCerradaOpcion.getId() != null) {
throw new BadRequestAlertException("A new pPreguntaCerradaOpcion cannot already have an ID", ENTITY_NAME, "idexists"); throw new BadRequestAlertException("A new pPreguntaCerradaOpcion cannot already have an ID", ENTITY_NAME, "idexists");
@ -196,4 +204,15 @@ public class PPreguntaCerradaOpcionResource {
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())) .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
.build(); .build();
} }
@PostMapping("/p-pregunta-cerrada-opcions/deleteMany")
public ResponseEntity<Void> deleteManyPPreguntaCerradaOpcion(@Valid @RequestBody int[] ids) {
for (int id : ids) {
pPreguntaCerradaOpcionService.delete((long) id);
}
return ResponseEntity
.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, Arrays.toString(ids)))
.build();
}
} }

View File

@ -2,15 +2,17 @@ package org.datasurvey.web.rest;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.datasurvey.domain.Plantilla; import org.datasurvey.domain.*;
import org.datasurvey.repository.PlantillaRepository; import org.datasurvey.repository.PlantillaRepository;
import org.datasurvey.service.PlantillaQueryService; import org.datasurvey.service.*;
import org.datasurvey.service.PlantillaService;
import org.datasurvey.service.criteria.PlantillaCriteria; import org.datasurvey.service.criteria.PlantillaCriteria;
import org.datasurvey.web.rest.errors.BadRequestAlertException; import org.datasurvey.web.rest.errors.BadRequestAlertException;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -41,14 +43,26 @@ public class PlantillaResource {
private final PlantillaQueryService plantillaQueryService; private final PlantillaQueryService plantillaQueryService;
private final PPreguntaCerradaService pPreguntaCerradaService;
private final PPreguntaAbiertaService pPreguntaAbiertaService;
private final PPreguntaCerradaOpcionService pPreguntaCerradaOpcionService;
public PlantillaResource( public PlantillaResource(
PlantillaService plantillaService, PlantillaService plantillaService,
PlantillaRepository plantillaRepository, PlantillaRepository plantillaRepository,
PlantillaQueryService plantillaQueryService PlantillaQueryService plantillaQueryService,
PPreguntaCerradaService pPreguntaCerradaService,
PPreguntaAbiertaService pPreguntaAbiertaService,
PPreguntaCerradaOpcionService ePreguntaCerradaOpcionService
) { ) {
this.plantillaService = plantillaService; this.plantillaService = plantillaService;
this.plantillaRepository = plantillaRepository; this.plantillaRepository = plantillaRepository;
this.plantillaQueryService = plantillaQueryService; this.plantillaQueryService = plantillaQueryService;
this.pPreguntaCerradaService = pPreguntaCerradaService;
this.pPreguntaAbiertaService = pPreguntaAbiertaService;
this.pPreguntaCerradaOpcionService = ePreguntaCerradaOpcionService;
} }
/** /**
@ -154,6 +168,55 @@ public class PlantillaResource {
return ResponseEntity.ok().body(entityList); return ResponseEntity.ok().body(entityList);
} }
@GetMapping("/plantillas/preguntas/{id}")
public ResponseEntity<List<Object>> getPreguntasByIdPlantilla(@PathVariable Long id) {
List<PPreguntaCerrada> preguntasCerradas = pPreguntaCerradaService.findAll();
List<PPreguntaAbierta> preguntasAbiertas = pPreguntaAbiertaService.findAll();
List<Object> preguntas = Stream.concat(preguntasCerradas.stream(), preguntasAbiertas.stream()).collect(Collectors.toList());
List<Object> preguntasFiltered = new ArrayList<>();
for (Object obj : preguntas) {
if (obj.getClass() == PPreguntaCerrada.class) {
if (((PPreguntaCerrada) obj).getPlantilla() != null) {
if (((PPreguntaCerrada) obj).getPlantilla().getId().equals(id)) {
preguntasFiltered.add(obj);
}
}
} else if (obj.getClass() == PPreguntaAbierta.class) {
if (((PPreguntaAbierta) obj).getPlantilla() != null) {
if (((PPreguntaAbierta) obj).getPlantilla().getId().equals(id)) {
preguntasFiltered.add(obj);
}
}
}
}
return ResponseEntity.ok().body(preguntasFiltered);
}
@GetMapping("/plantillas/preguntas-opciones/{id}")
public ResponseEntity<List<List<PPreguntaCerradaOpcion>>> getPreguntaCerradaOpcionByIdPlantilla(@PathVariable Long id) {
List<List<PPreguntaCerradaOpcion>> res = new ArrayList<>();
List<PPreguntaCerrada> preguntasCerradas = pPreguntaCerradaService.findAll();
List<PPreguntaCerrada> preguntasCerradasFiltered = preguntasCerradas
.stream()
.filter(p -> Objects.nonNull(p.getPlantilla()))
.filter(p -> p.getPlantilla().getId().equals(id))
.collect(Collectors.toList());
List<PPreguntaCerradaOpcion> opciones = pPreguntaCerradaOpcionService.findAll();
for (PPreguntaCerrada pPreguntaCerrada : preguntasCerradasFiltered) {
long preguntaCerradaId = pPreguntaCerrada.getId();
List<PPreguntaCerradaOpcion> opcionesFiltered = opciones
.stream()
.filter(o -> Objects.nonNull(o.getPPreguntaCerrada()))
.filter(o -> o.getPPreguntaCerrada().getId().equals(preguntaCerradaId))
.collect(Collectors.toList());
res.add(opcionesFiltered);
}
return ResponseEntity.ok().body(res);
}
/** /**
* {@code GET /plantillas/count} : count all the plantillas. * {@code GET /plantillas/count} : count all the plantillas.
* *

View File

@ -9,13 +9,11 @@ import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import org.datasurvey.domain.Encuesta;
import org.datasurvey.domain.UsuarioEncuesta; import org.datasurvey.domain.UsuarioEncuesta;
import org.datasurvey.domain.UsuarioExtra; import org.datasurvey.domain.UsuarioExtra;
import org.datasurvey.repository.UsuarioEncuestaRepository; import org.datasurvey.repository.UsuarioEncuestaRepository;
import org.datasurvey.service.EncuestaService; import org.datasurvey.service.*;
import org.datasurvey.service.UsuarioEncuestaQueryService;
import org.datasurvey.service.UsuarioEncuestaService;
import org.datasurvey.service.UsuarioExtraService;
import org.datasurvey.service.criteria.UsuarioEncuestaCriteria; import org.datasurvey.service.criteria.UsuarioEncuestaCriteria;
import org.datasurvey.web.rest.errors.BadRequestAlertException; import org.datasurvey.web.rest.errors.BadRequestAlertException;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -48,18 +46,22 @@ public class UsuarioEncuestaResource {
private final UsuarioEncuestaQueryService usuarioEncuestaQueryService; private final UsuarioEncuestaQueryService usuarioEncuestaQueryService;
private final MailService mailService;
public UsuarioEncuestaResource( public UsuarioEncuestaResource(
UsuarioEncuestaService usuarioEncuestaService, UsuarioEncuestaService usuarioEncuestaService,
UsuarioEncuestaRepository usuarioEncuestaRepository, UsuarioEncuestaRepository usuarioEncuestaRepository,
UsuarioEncuestaQueryService usuarioEncuestaQueryService, UsuarioEncuestaQueryService usuarioEncuestaQueryService,
UsuarioExtraService usuarioExtraService, UsuarioExtraService usuarioExtraService,
EncuestaService encuestaService EncuestaService encuestaService,
MailService mailService
) { ) {
this.usuarioEncuestaService = usuarioEncuestaService; this.usuarioEncuestaService = usuarioEncuestaService;
this.usuarioEncuestaRepository = usuarioEncuestaRepository; this.usuarioEncuestaRepository = usuarioEncuestaRepository;
this.usuarioEncuestaQueryService = usuarioEncuestaQueryService; this.usuarioEncuestaQueryService = usuarioEncuestaQueryService;
this.usuarioExtraService = usuarioExtraService; this.usuarioExtraService = usuarioExtraService;
this.encuestaService = encuestaService; this.encuestaService = encuestaService;
this.mailService = mailService;
} }
/** /**
@ -77,6 +79,9 @@ public class UsuarioEncuestaResource {
throw new BadRequestAlertException("A new usuarioEncuesta cannot already have an ID", ENTITY_NAME, "idexists"); throw new BadRequestAlertException("A new usuarioEncuesta cannot already have an ID", ENTITY_NAME, "idexists");
} }
UsuarioEncuesta result = usuarioEncuestaService.save(usuarioEncuesta); UsuarioEncuesta result = usuarioEncuestaService.save(usuarioEncuesta);
if (result.getId() != null) {
mailService.sendInvitationColaborator(usuarioEncuesta);
}
return ResponseEntity return ResponseEntity
.created(new URI("/api/usuario-encuestas/" + result.getId())) .created(new URI("/api/usuario-encuestas/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
@ -200,7 +205,11 @@ public class UsuarioEncuestaResource {
@DeleteMapping("/usuario-encuestas/{id}") @DeleteMapping("/usuario-encuestas/{id}")
public ResponseEntity<Void> deleteUsuarioEncuesta(@PathVariable Long id) { public ResponseEntity<Void> deleteUsuarioEncuesta(@PathVariable Long id) {
log.debug("REST request to delete UsuarioEncuesta : {}", id); log.debug("REST request to delete UsuarioEncuesta : {}", id);
Optional<UsuarioEncuesta> usuarioEncuesta = usuarioEncuestaService.findOne(id);
usuarioEncuestaService.delete(id); usuarioEncuestaService.delete(id);
if (usuarioEncuesta != null) {
mailService.sendNotifyDeleteColaborator(usuarioEncuesta.get());
}
return ResponseEntity return ResponseEntity
.noContent() .noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())) .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
@ -225,4 +234,11 @@ public class UsuarioEncuestaResource {
} }
return ResponseEntity.ok().body(usuariosEncuestas); return ResponseEntity.ok().body(usuariosEncuestas);
} }
@PostMapping("/usuario-encuestas/notify/{id}")
public ResponseEntity<Void> notifyInvitationColaborator(@PathVariable Long id, @Valid @RequestBody UsuarioEncuesta usuarioEncuesta) {
log.debug("REST request to notify {} of invitation to Encuesta", usuarioEncuesta.getUsuarioExtra().getUser().getEmail());
mailService.sendInvitationColaborator(usuarioEncuesta);
return ResponseEntity.noContent().build();
}
} }

View File

@ -42,13 +42,25 @@ email.suspended.text2=Saludos,
#PublicEncuesta #PublicEncuesta
email.public.title=Su encuesta ha sido publicada email.public.title=Su encuesta ha sido publicada
email.public.greeting=¡Felicidades {0}! email.public.greeting=¡Felicidades {0}!
email.public.text1=Su encuesta ha sido publicada de manera publica email.public.text1=Su encuesta ha sido publicada de manera publica
email.public.text2=Saludos, email.public.text2=Saludos,
#PrivateEncuesta #PrivateEncuesta
email.private.title=Su encuesta ha sido publicada de manera privada email.private.title=Su encuesta ha sido publicada de manera privada
email.private.greeting=¡Felicidades {0}! email.private.greeting=¡Felicidades {0}!
email.private.text1=Su encuesta ha sdo publicada de manera privada. Su contraseña de acceso es: {0} email.private.text1=Su encuesta ha sdo publicada de manera privada. Su contraseña de acceso es: {0}
email.private.text2=Saludos, email.private.text2=Saludos,
#Invitation Colaborator
email.invitation.title=Se le ha invitado a colaborar en una encuesta
email.invitation.greeting=¡Nueva invitación, {0}!
email.invitation.text1=Fue invitado a la encuesta "{0}(#{1})". Para aceptar la solicitud de colaborador, ingrese al área de colaboraciones
email.invitation.text2=Saludos,
#Delete Colaborator
email.deleteColaborator.title=Se le ha expulsado de una encuesta como colaborador
email.deleteColaborator.greeting=¡Se le ha expulsado, {0}!
email.deleteColaborator.text1=Fue expulsado de la encuesta {0}(#{1})"
email.deleteColaborator.text2=Saludos,

View File

@ -0,0 +1,322 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:lang="${#locale.language}" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width" />
<!-- Forcing initial-scale shouldn't be necessary -->
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- Use the latest (edge) version of IE rendering engine -->
<meta name="x-apple-disable-message-reformatting" />
<!-- Disable auto-scale in iOS 10 Mail entirely -->
<title th:text="#{email.deleteColaborator.title}">JHipster activation</title>
<link rel="icon" th:href="@{|${baseUrl}/favicon.ico|}" />
<link href="https://fonts.googleapis.com/css?family=NotoSansSP:300,400,700" rel="stylesheet" />
<link rel="manifest" href="manifest.webapp" />
<style>
.bg_white {
background: #ffffff;
}
.bg_light {
background: #fafafa;
}
.bg_black {
background: #000000;
}
.bg_dark {
background: rgba(0, 0, 0, 0.8);
}
.email-section {
padding: 2.5em;
}
/*BUTTON*/
.btn {
padding: 10px 15px;
display: inline-block;
}
.btn.btn-primary {
border-radius: 5px;
background: #007bff;
color: #ffffff;
}
.btn.btn-white {
border-radius: 5px;
background: #ffffff;
color: #000000;
}
.btn.btn-white-outline {
border-radius: 5px;
background: transparent;
border: 1px solid #fff;
color: #fff;
}
.btn.btn-black-outline {
border-radius: 0px;
background: transparent;
border: 2px solid #000;
color: #000;
font-weight: 700;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'Lato', sans-serif;
color: #000000;
margin-top: 0;
font-weight: 400;
}
body {
font-family: 'Noto Sans JP', sans-serif;
font-weight: 400;
font-size: 15px;
line-height: 1.8;
color: rgba(0, 0, 0, 0.4);
}
a {
color: #30e3ca;
}
table {
}
/*LOGO*/
.logo h1 {
margin: 0;
}
.logo h1 a {
color: #30e3ca;
font-size: 24px;
font-weight: 700;
font-family: 'Lato', sans-serif;
}
/*HERO*/
.hero {
position: relative;
z-index: 0;
}
.hero .text {
color: rgba(0, 0, 0, 0.3);
}
.hero .text h2 {
color: #000;
font-size: 40px;
margin-bottom: 0;
font-weight: 400;
line-height: 1.4;
}
.hero .text h3 {
font-size: 24px;
font-weight: 300;
}
.hero .text h2 span {
font-weight: 600;
color: #30e3ca;
}
/*HEADING SECTION*/
.heading-section {
}
.heading-section h2 {
color: #000000;
font-size: 28px;
margin-top: 0;
line-height: 1.4;
font-weight: 400;
}
.heading-section .subheading {
margin-bottom: 20px !important;
display: inline-block;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 2px;
color: rgba(0, 0, 0, 0.4);
position: relative;
}
.heading-section .subheading::after {
position: absolute;
left: 0;
right: 0;
bottom: -10px;
content: '';
width: 100%;
height: 2px;
background: #30e3ca;
margin: 0 auto;
}
.heading-section-white {
color: rgba(255, 255, 255, 0.8);
}
.heading-section-white h2 {
/*font-family: ;*/
line-height: 1;
padding-bottom: 0;
}
.heading-section-white h2 {
color: #ffffff;
}
.heading-section-white .subheading {
margin-bottom: 0;
display: inline-block;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 2px;
color: rgba(255, 255, 255, 0.4);
}
ul.social {
padding: 0;
}
ul.social li {
display: inline-block;
margin-right: 10px;
}
.footer {
border-top: 1px solid rgba(0, 0, 0, 0.05);
color: rgba(0, 0, 0, 0.5);
}
.footer .heading {
color: #000;
font-size: 20px;
}
.footer ul {
margin: 0;
padding: 0;
}
.footer ul li {
list-style: none;
margin-bottom: 10px;
}
.footer ul li a {
color: rgba(0, 0, 0, 1);
}
</style>
</head>
<body width="100%" style="margin: 0; padding: 0 !important; mso-line-height-rule: exactly; background-color: #f1f1f1">
<center style="width: 100%; background-color: #f1f1f1">
<div
style="
display: none;
font-size: 1px;
max-height: 0px;
max-width: 0px;
opacity: 0;
overflow: hidden;
mso-hide: all;
font-family: sans-serif;
"
>
&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;
</div>
<div style="max-width: 600px; margin: 0 auto" class="email-container">
<!-- BEGIN BODY -->
<table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="margin: auto">
<tr>
<td valign="top" class="bg_white" style="padding: 1em 2.5em 0 2.5em">
<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td class="logo" style="text-align: center">
<h1>
<a href="#"
><img
src="https://res.cloudinary.com/marielascloud/image/upload/v1626333881/DataSurveyLogo2_smr2ok.png"
alt=""
width="300"
/></a>
</h1>
</td>
</tr>
</table>
</td>
</tr>
<!-- end tr -->
<tr>
<td valign="middle" class="hero bg_white" style="padding: 3em 0 2em 0">
<img
src="https://res.cloudinary.com/marielascloud/image/upload/v1626333882/email_v7pjtv.png"
alt=""
style="width: 250px; max-width: 600px; height: auto; margin: auto; display: block"
/>
</td>
</tr>
<!-- end tr -->
<tr>
<td valign="middle" class="hero bg_white" style="padding: 2em 0 4em 0">
<table>
<tr>
<td>
<div class="text" style="padding: 0 2.5em; text-align: center">
<h2 th:text="#{email.deleteColaborator.greeting(${user.login})}">¡Hola!</h2>
<h3 th:text="#{email.deleteColaborator.text1(${colaborador.encuesta.nombre}, ${colaborador.encuesta.id})}">
Your JHipster account has been created, please click on the URL below to activate it:
</h3>
<p>
<a th:with="url=(@{|${baseUrl}/colaboraciones|})" th:href="${url}" class="btn btn-primary">Ir a Colaboraciones</a>
</p>
</div>
<div class="text" style="padding: 1em 2.5em; text-align: center">
<p>
<span th:text="#{email.deleteColaborator.text2}">Regards, </span>
<br />
<em th:text="#{email.signature}">JHipster.</em>
</p>
</div>
</td>
</tr>
</table>
</td>
</tr>
<!-- end tr -->
<!-- 1 Column Text + Button : END -->
</table>
<table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="margin: auto">
<tr>
<td valign="middle" class="bg_light footer email-section">
<table>
<tr>
<td valign="top" width="33.333%" style="padding-top: 20px">
<table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td style="text-align: left; padding-right: 10px">
<h3 class="heading">Acerca de</h3>
<p>DataSurvey es su compañero más cercano para poder recolectar información valiosa para usted</p>
</td>
</tr>
</table>
</td>
<td valign="top" width="33.333%" style="padding-top: 20px">
<table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td style="text-align: left; padding-left: 5px; padding-right: 5px">
<h3 class="heading">Información de contacto</h3>
<ul>
<li><span href="mailto:datasurveyapp@gmail.com" class="text">datasurveyapp@gmail.com</span></li>
</ul>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<!-- end: tr -->
<tr>
<td class="bg_light" style="text-align: center">
<p><a href="https://datasurvey.org" style="color: rgba(0, 0, 0, 0.8)">DataSurvey.org</a></p>
</td>
</tr>
</table>
</div>
</center>
</body>
</html>

View File

@ -0,0 +1,322 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:lang="${#locale.language}" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width" />
<!-- Forcing initial-scale shouldn't be necessary -->
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- Use the latest (edge) version of IE rendering engine -->
<meta name="x-apple-disable-message-reformatting" />
<!-- Disable auto-scale in iOS 10 Mail entirely -->
<title th:text="#{email.invitation.title}">JHipster activation</title>
<link rel="icon" th:href="@{|${baseUrl}/favicon.ico|}" />
<link href="https://fonts.googleapis.com/css?family=NotoSansSP:300,400,700" rel="stylesheet" />
<link rel="manifest" href="manifest.webapp" />
<style>
.bg_white {
background: #ffffff;
}
.bg_light {
background: #fafafa;
}
.bg_black {
background: #000000;
}
.bg_dark {
background: rgba(0, 0, 0, 0.8);
}
.email-section {
padding: 2.5em;
}
/*BUTTON*/
.btn {
padding: 10px 15px;
display: inline-block;
}
.btn.btn-primary {
border-radius: 5px;
background: #007bff;
color: #ffffff;
}
.btn.btn-white {
border-radius: 5px;
background: #ffffff;
color: #000000;
}
.btn.btn-white-outline {
border-radius: 5px;
background: transparent;
border: 1px solid #fff;
color: #fff;
}
.btn.btn-black-outline {
border-radius: 0px;
background: transparent;
border: 2px solid #000;
color: #000;
font-weight: 700;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: 'Lato', sans-serif;
color: #000000;
margin-top: 0;
font-weight: 400;
}
body {
font-family: 'Noto Sans JP', sans-serif;
font-weight: 400;
font-size: 15px;
line-height: 1.8;
color: rgba(0, 0, 0, 0.4);
}
a {
color: #30e3ca;
}
table {
}
/*LOGO*/
.logo h1 {
margin: 0;
}
.logo h1 a {
color: #30e3ca;
font-size: 24px;
font-weight: 700;
font-family: 'Lato', sans-serif;
}
/*HERO*/
.hero {
position: relative;
z-index: 0;
}
.hero .text {
color: rgba(0, 0, 0, 0.3);
}
.hero .text h2 {
color: #000;
font-size: 40px;
margin-bottom: 0;
font-weight: 400;
line-height: 1.4;
}
.hero .text h3 {
font-size: 24px;
font-weight: 300;
}
.hero .text h2 span {
font-weight: 600;
color: #30e3ca;
}
/*HEADING SECTION*/
.heading-section {
}
.heading-section h2 {
color: #000000;
font-size: 28px;
margin-top: 0;
line-height: 1.4;
font-weight: 400;
}
.heading-section .subheading {
margin-bottom: 20px !important;
display: inline-block;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 2px;
color: rgba(0, 0, 0, 0.4);
position: relative;
}
.heading-section .subheading::after {
position: absolute;
left: 0;
right: 0;
bottom: -10px;
content: '';
width: 100%;
height: 2px;
background: #30e3ca;
margin: 0 auto;
}
.heading-section-white {
color: rgba(255, 255, 255, 0.8);
}
.heading-section-white h2 {
/*font-family: ;*/
line-height: 1;
padding-bottom: 0;
}
.heading-section-white h2 {
color: #ffffff;
}
.heading-section-white .subheading {
margin-bottom: 0;
display: inline-block;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 2px;
color: rgba(255, 255, 255, 0.4);
}
ul.social {
padding: 0;
}
ul.social li {
display: inline-block;
margin-right: 10px;
}
.footer {
border-top: 1px solid rgba(0, 0, 0, 0.05);
color: rgba(0, 0, 0, 0.5);
}
.footer .heading {
color: #000;
font-size: 20px;
}
.footer ul {
margin: 0;
padding: 0;
}
.footer ul li {
list-style: none;
margin-bottom: 10px;
}
.footer ul li a {
color: rgba(0, 0, 0, 1);
}
</style>
</head>
<body width="100%" style="margin: 0; padding: 0 !important; mso-line-height-rule: exactly; background-color: #f1f1f1">
<center style="width: 100%; background-color: #f1f1f1">
<div
style="
display: none;
font-size: 1px;
max-height: 0px;
max-width: 0px;
opacity: 0;
overflow: hidden;
mso-hide: all;
font-family: sans-serif;
"
>
&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;
</div>
<div style="max-width: 600px; margin: 0 auto" class="email-container">
<!-- BEGIN BODY -->
<table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="margin: auto">
<tr>
<td valign="top" class="bg_white" style="padding: 1em 2.5em 0 2.5em">
<table role="presentation" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td class="logo" style="text-align: center">
<h1>
<a href="#"
><img
src="https://res.cloudinary.com/marielascloud/image/upload/v1626333881/DataSurveyLogo2_smr2ok.png"
alt=""
width="300"
/></a>
</h1>
</td>
</tr>
</table>
</td>
</tr>
<!-- end tr -->
<tr>
<td valign="middle" class="hero bg_white" style="padding: 3em 0 2em 0">
<img
src="https://res.cloudinary.com/marielascloud/image/upload/v1626333882/email_v7pjtv.png"
alt=""
style="width: 250px; max-width: 600px; height: auto; margin: auto; display: block"
/>
</td>
</tr>
<!-- end tr -->
<tr>
<td valign="middle" class="hero bg_white" style="padding: 2em 0 4em 0">
<table>
<tr>
<td>
<div class="text" style="padding: 0 2.5em; text-align: center">
<h2 th:text="#{email.invitation.greeting(${user.login})}">¡Hola!</h2>
<h3 th:text="#{email.invitation.text1(${colaborador.encuesta.nombre}, ${colaborador.encuesta.id})}">
Your JHipster account has been created, please click on the URL below to activate it:
</h3>
<p>
<a th:with="url=(@{|${baseUrl}/colaboraciones|})" th:href="${url}" class="btn btn-primary">Ir a Colaboraciones</a>
</p>
</div>
<div class="text" style="padding: 1em 2.5em; text-align: center">
<p>
<span th:text="#{email.reactivation.text2}">Regards, </span>
<br />
<em th:text="#{email.signature}">JHipster.</em>
</p>
</div>
</td>
</tr>
</table>
</td>
</tr>
<!-- end tr -->
<!-- 1 Column Text + Button : END -->
</table>
<table align="center" role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%" style="margin: auto">
<tr>
<td valign="middle" class="bg_light footer email-section">
<table>
<tr>
<td valign="top" width="33.333%" style="padding-top: 20px">
<table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td style="text-align: left; padding-right: 10px">
<h3 class="heading">Acerca de</h3>
<p>DataSurvey es su compañero más cercano para poder recolectar información valiosa para usted</p>
</td>
</tr>
</table>
</td>
<td valign="top" width="33.333%" style="padding-top: 20px">
<table role="presentation" cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td style="text-align: left; padding-left: 5px; padding-right: 5px">
<h3 class="heading">Información de contacto</h3>
<ul>
<li><span href="mailto:datasurveyapp@gmail.com" class="text">datasurveyapp@gmail.com</span></li>
</ul>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
<!-- end: tr -->
<tr>
<td class="bg_light" style="text-align: center">
<p><a href="https://datasurvey.org" style="color: rgba(0, 0, 0, 0.8)">DataSurvey.org</a></p>
</td>
</tr>
</table>
</div>
</center>
</body>
</html>

View File

@ -11,7 +11,7 @@
<button type="button" class="ds-btn ds-btn--secondary" (click)="previousState()"> <button type="button" class="ds-btn ds-btn--secondary" (click)="previousState()">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span jhiTranslate="entity.action.back">Back</span> <fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span jhiTranslate="entity.action.back">Back</span>
</button> </button>
<ng-container *ngIf="encuesta!.estado === 'DRAFT'"> <ng-container *ngIf="encuesta!.estado === 'DRAFT' && (isAutor() || isEscritor())">
<button type="button" class="ds-btn ds-btn--primary" (click)="publishSurvey()">Publicar encuesta</button> <button type="button" class="ds-btn ds-btn--primary" (click)="publishSurvey()">Publicar encuesta</button>
</ng-container> </ng-container>
</div> </div>
@ -27,12 +27,13 @@
<!-- <jhi-alert></jhi-alert> --> <!-- <jhi-alert></jhi-alert> -->
<div class="alert alert-warning" id="no-result" *ngIf="ePreguntas?.length === 0"> <div class="ds-survey preview-survey" id="entities">
<span>No se encontraron preguntas</span>
</div>
<div class="ds-survey preview-survey" id="entities" *ngIf="ePreguntas && ePreguntas.length > 0">
<div class="ds-survey--all-question-wrapper col-8"> <div class="ds-survey--all-question-wrapper col-8">
<ng-container *ngIf="ePreguntas && ePreguntas.length === 0">
<p class="ds-title text-center">Encuesta vacía</p>
<p class="ds-subtitle text-center">Inicie creando preguntas y opciones para su encuesta.</p>
</ng-container>
<div class="ds-survey--question-wrapper card-encuesta lift" *ngFor="let ePregunta of ePreguntas; let i = index; trackBy: trackId"> <div class="ds-survey--question-wrapper card-encuesta lift" *ngFor="let ePregunta of ePreguntas; let i = index; trackBy: trackId">
<div <div
[attr.data-index]="ePregunta.id" [attr.data-index]="ePregunta.id"

View File

@ -14,7 +14,7 @@ import { IEncuesta, Encuesta } from '../encuesta.model';
import { EncuestaService } from '../service/encuesta.service'; import { EncuestaService } from '../service/encuesta.service';
import { ICategoria } from 'app/entities/categoria/categoria.model'; import { ICategoria } from 'app/entities/categoria/categoria.model';
import { CategoriaService } from 'app/entities/categoria/service/categoria.service'; import { CategoriaService } from 'app/entities/categoria/service/categoria.service';
import { IUsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model'; import { IUsuarioExtra, UsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model';
import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service'; import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@ -30,6 +30,10 @@ import { PreguntaCerradaTipo } from 'app/entities/enumerations/pregunta-cerrada-
import { faTimes, faPlus, faStar, faQuestion } from '@fortawesome/free-solid-svg-icons'; import { faTimes, faPlus, faStar, faQuestion } from '@fortawesome/free-solid-svg-icons';
import { EncuestaPublishDialogComponent } from '../encuesta-publish-dialog/encuesta-publish-dialog.component'; import { EncuestaPublishDialogComponent } from '../encuesta-publish-dialog/encuesta-publish-dialog.component';
import { UsuarioEncuestaService } from 'app/entities/usuario-encuesta/service/usuario-encuesta.service';
import { Account } from '../../../core/auth/account.model';
import { AccountService } from 'app/core/auth/account.service';
import { IUsuarioEncuesta } from '../../usuario-encuesta/usuario-encuesta.model';
@Component({ @Component({
selector: 'jhi-encuesta-detail', selector: 'jhi-encuesta-detail',
@ -47,6 +51,8 @@ export class EncuestaDetailComponent implements OnInit {
successPublished = false; successPublished = false;
ePreguntas?: any[]; ePreguntas?: any[];
ePreguntasOpciones?: any[]; ePreguntasOpciones?: any[];
usuarioExtra: UsuarioExtra | null = null;
usuariosColaboradores: IUsuarioEncuesta[] = [];
constructor( constructor(
protected activatedRoute: ActivatedRoute, protected activatedRoute: ActivatedRoute,
@ -57,7 +63,9 @@ export class EncuestaDetailComponent implements OnInit {
protected modalService: NgbModal, protected modalService: NgbModal,
protected ePreguntaCerradaService: EPreguntaCerradaService, protected ePreguntaCerradaService: EPreguntaCerradaService,
protected ePreguntaCerradaOpcionService: EPreguntaCerradaOpcionService, protected ePreguntaCerradaOpcionService: EPreguntaCerradaOpcionService,
protected ePreguntaAbiertaService: EPreguntaAbiertaService protected ePreguntaAbiertaService: EPreguntaAbiertaService,
protected accountService: AccountService,
protected usuarioEncuestaService: UsuarioEncuestaService
) {} ) {}
ngOnInit(): void { ngOnInit(): void {
@ -69,6 +77,15 @@ export class EncuestaDetailComponent implements OnInit {
this.previousState(); this.previousState();
} }
}); });
// Get jhi_user and usuario_extra information
this.accountService.getAuthenticationState().subscribe(account => {
if (account !== null) {
this.usuarioExtraService.find(account.id).subscribe(usuarioExtra => {
this.usuarioExtra = usuarioExtra.body;
});
}
});
} }
ngAfterViewChecked(): void { ngAfterViewChecked(): void {
@ -145,6 +162,16 @@ export class EncuestaDetailComponent implements OnInit {
this.isLoading = false; this.isLoading = false;
} }
);*/ );*/
this.usuarioEncuestaService.findCollaborators(this.encuesta?.id!).subscribe(
(res: any) => {
this.isLoading = false;
this.usuariosColaboradores = res.body ?? [];
},
() => {
this.isLoading = false;
}
);
} }
publishSurvey(): void { publishSurvey(): void {
const modalRef = this.modalService.open(EncuestaPublishDialogComponent, { size: 'lg', backdrop: 'static' }); const modalRef = this.modalService.open(EncuestaPublishDialogComponent, { size: 'lg', backdrop: 'static' });
@ -161,4 +188,20 @@ export class EncuestaDetailComponent implements OnInit {
previousState(): void { previousState(): void {
window.history.back(); window.history.back();
} }
isAutor() {
return this.usuarioExtra?.id === this.encuesta?.usuarioExtra?.id;
}
isEscritor() {
let escritor = false;
this.usuariosColaboradores.forEach(c => {
if (this.usuarioExtra?.id === c.usuarioExtra?.id) {
if (c.rol === 'WRITE') {
escritor = true;
}
}
});
return escritor;
}
} }

View File

@ -0,0 +1,23 @@
<form class="ds-form" *ngIf="colaborador" name="deleteForm" (ngSubmit)="confirmDelete(colaborador.id!)">
<div class="modal-body">
<p class="ds-title--small">Expulsar colaborador de encuesta</p>
<p
class="ds-subtitle"
id="jhi-delete-colaborador-heading"
jhiTranslate="dataSurveyApp.usuarioEncuesta.delete.question"
[translateValues]="{ id: colaborador.id }"
>
Are you sure you want to delete this Usuario Encuesta?
</p>
</div>
<div class="modal-footer">
<button type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal" (click)="cancel()">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button id="jhi-confirm-delete-usuarioEncuesta" data-cy="entityConfirmDeleteButton" type="submit" class="ds-btn ds-btn--danger">
<fa-icon icon="times"></fa-icon>&nbsp;<span jhiTranslate="dataSurveyApp.usuarioEncuesta.delete.action">Delete</span>
</button>
</div>
</form>

View File

@ -0,0 +1,26 @@
import { Component, OnInit } from '@angular/core';
import { IUsuarioEncuesta } from '../../usuario-encuesta/usuario-encuesta.model';
import { UsuarioEncuestaService } from '../../usuario-encuesta/service/usuario-encuesta.service';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'jhi-encuesta-delete-colaborator-dialog',
templateUrl: './encuesta-delete-colaborator-dialog.component.html',
styleUrls: ['./encuesta-delete-colaborator-dialog.component.scss'],
})
export class EncuestaDeleteColaboratorDialogComponent {
colaborador?: IUsuarioEncuesta;
constructor(protected usuarioEncuestaService: UsuarioEncuestaService, protected activeModal: NgbActiveModal) {}
cancel(): void {
this.activeModal.dismiss();
}
confirmDelete(id: number): void {
this.usuarioEncuestaService.delete(id).subscribe(() => {
this.activeModal.close('deleted');
});
}
}

View File

@ -0,0 +1,19 @@
<form *ngIf="encuesta" name="deleteForm" (ngSubmit)="confirmFinalizar(encuesta!)">
<div class="modal-header">
<h4 class="ds-title--small" data-cy="encuestaDeleteDialogHeading">Finalizar encuesta</h4>
</div>
<div class="modal-body">
<p class="ds-subtitle" id="jhi-delete-encuesta-heading">¿Está seguro de querer finalizar la encuesta?</p>
</div>
<div class="modal-footer">
<button type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal" (click)="cancel()">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button id="jhi-confirm-delete-encuesta" data-cy="entityConfirmDeleteButton" type="submit" class="ds-btn ds-btn--danger">
&nbsp;<span>Finalizar</span>
</button>
</div>
</form>

View File

@ -0,0 +1,24 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { EncuestaFinalizarDialogComponent } from './encuesta-finalizar-dialog.component';
describe('EncuestaFinalizarDialogComponent', () => {
let component: EncuestaFinalizarDialogComponent;
let fixture: ComponentFixture<EncuestaFinalizarDialogComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [EncuestaFinalizarDialogComponent],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(EncuestaFinalizarDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,36 @@
import { Component, OnInit } from '@angular/core';
import { IEncuesta } from '../encuesta.model';
import { EstadoEncuesta } from '../../enumerations/estado-encuesta.model';
import { EncuestaService } from '../service/encuesta.service';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import * as dayjs from 'dayjs';
import { DATE_TIME_FORMAT } from '../../../config/input.constants';
@Component({
selector: 'jhi-encuesta-finalizar-dialog',
templateUrl: './encuesta-finalizar-dialog.component.html',
styleUrls: ['./encuesta-finalizar-dialog.component.scss'],
})
export class EncuestaFinalizarDialogComponent implements OnInit {
encuesta?: IEncuesta;
constructor(protected encuestaService: EncuestaService, protected activeModal: NgbActiveModal) {}
ngOnInit(): void {}
confirmFinalizar(encuesta: IEncuesta): void {
debugger;
const now = dayjs();
encuesta.estado = EstadoEncuesta.FINISHED;
encuesta.fechaFinalizada = dayjs(now, DATE_TIME_FORMAT);
this.encuestaService.updateSurvey(encuesta).subscribe(() => {
this.activeModal.close('finalized');
});
}
cancel(): void {
this.activeModal.dismiss();
}
}

View File

@ -12,6 +12,8 @@ import { EncuestaDeleteOptionDialogComponent } from './encuesta-delete-option-di
import { EncuestaCompartirDialogComponent } from './encuesta-compartir-dialog/encuesta-compartir-dialog.component'; import { EncuestaCompartirDialogComponent } from './encuesta-compartir-dialog/encuesta-compartir-dialog.component';
import { EncuestaCompleteComponent } from './complete/complete.component'; import { EncuestaCompleteComponent } from './complete/complete.component';
import { EncuestaPasswordDialogComponent } from './encuesta-password-dialog/encuesta-password-dialog.component'; import { EncuestaPasswordDialogComponent } from './encuesta-password-dialog/encuesta-password-dialog.component';
import { EncuestaFinalizarDialogComponent } from './encuesta-finalizar-dialog/encuesta-finalizar-dialog.component';
import { EncuestaDeleteColaboratorDialogComponent } from './encuesta-delete-colaborator-dialog/encuesta-delete-colaborator-dialog.component';
@NgModule({ @NgModule({
imports: [SharedModule, EncuestaRoutingModule, FontAwesomeModule], imports: [SharedModule, EncuestaRoutingModule, FontAwesomeModule],
@ -26,6 +28,8 @@ import { EncuestaPasswordDialogComponent } from './encuesta-password-dialog/encu
EncuestaCompartirDialogComponent, EncuestaCompartirDialogComponent,
EncuestaCompleteComponent, EncuestaCompleteComponent,
EncuestaPasswordDialogComponent, EncuestaPasswordDialogComponent,
EncuestaFinalizarDialogComponent,
EncuestaDeleteColaboratorDialogComponent,
], ],
entryComponents: [EncuestaDeleteDialogComponent], entryComponents: [EncuestaDeleteDialogComponent],
}) })

View File

@ -26,6 +26,7 @@ export class EncuestaService {
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
} }
//update para publicar
update(encuesta: IEncuesta): Observable<EntityResponseType> { update(encuesta: IEncuesta): Observable<EntityResponseType> {
const copy = this.convertDateFromClient(encuesta); const copy = this.convertDateFromClient(encuesta);
return this.http return this.http
@ -33,6 +34,7 @@ export class EncuestaService {
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
} }
//update normal
updateSurvey(encuesta: IEncuesta): Observable<EntityResponseType> { updateSurvey(encuesta: IEncuesta): Observable<EntityResponseType> {
const copy = this.convertDateFromClient(encuesta); const copy = this.convertDateFromClient(encuesta);
return this.http return this.http
@ -100,6 +102,10 @@ export class EncuestaService {
return this.http.delete(`${this.resourceUrl}/notify/${encuesta.id}`, { observe: 'response' }); return this.http.delete(`${this.resourceUrl}/notify/${encuesta.id}`, { observe: 'response' });
} }
/*sendCorreoInvitacion(correo: string) {
return this.http.post(`${this.resourceUrl}/notify/${encuesta.id}`, { observe: 'response' });
}*/
addEncuestaToCollectionIfMissing(encuestaCollection: IEncuesta[], ...encuestasToCheck: (IEncuesta | null | undefined)[]): IEncuesta[] { addEncuestaToCollectionIfMissing(encuestaCollection: IEncuesta[], ...encuestasToCheck: (IEncuesta | null | undefined)[]): IEncuesta[] {
const encuestas: IEncuesta[] = encuestasToCheck.filter(isPresent); const encuestas: IEncuesta[] = encuestasToCheck.filter(isPresent);
if (encuestas.length > 0) { if (encuestas.length > 0) {

View File

@ -13,19 +13,27 @@
></fa-icon> ></fa-icon>
&nbsp;&nbsp;<fa-icon class="ds-info--icon" [icon]="faEye" (click)="openPreview()"></fa-icon> &nbsp;&nbsp;<fa-icon class="ds-info--icon" [icon]="faEye" (click)="openPreview()"></fa-icon>
<div class="d-flex px-4"> <div class="d-flex px-4">
<div class="col-12"> <div class="col-12 ds-list-collabs">
<div class="row" style="flex-direction: row-reverse"> <div class="row" style="flex-direction: row-reverse">
<div class="col-mb-2 iconos-colab"> <div class="col-mb-2 iconos-colab">
<div class="add-collab"> <div class="add-collab" data-toggle="modal" data-target="#modalAddColaborators">
<fa-icon icon="sync" [icon]="faPlus"></fa-icon> <fa-icon icon="sync" [icon]="faPlus"></fa-icon>
</div> </div>
</div> </div>
<div class="col-mb-2 iconos-colab" *ngFor="let colaborador of usuariosColaboradores">
<div
class="col-mb-2 iconos-colab"
*ngFor="let colaborador of usuariosColaboradores"
(click)="selectColaborator(colaborador)"
data-toggle="modal"
data-target="#modalUpdateColaborators"
>
<img <img
class="photo-collab" class="photo-collab"
*ngIf="colaborador.usuarioExtra" *ngIf="colaborador.usuarioExtra"
src="../../../../content/profile_icons/C{{ colaborador.usuarioExtra.iconoPerfil }}.png" src="../../../../content/profile_icons/C{{ colaborador.usuarioExtra.iconoPerfil }}.png"
alt="{{ colaborador.usuarioExtra.nombre }}" alt="{{ colaborador.usuarioExtra.nombre }}"
[attr.data-id]="colaborador.id"
/> />
</div> </div>
</div> </div>
@ -34,6 +42,9 @@
</div> </div>
<p class="ds-subtitle">Creada el día {{ encuesta!.fechaCreacion | formatShortDatetime | lowercase }}</p> <p class="ds-subtitle">Creada el día {{ encuesta!.fechaCreacion | formatShortDatetime | lowercase }}</p>
<button type="button" class="ds-btn ds-btn--danger" (click)="finalizar()" *ngIf="encuesta!.estado === 'ACTIVE'">
<fa-icon icon="sync" [icon]="faTimes"></fa-icon>&nbsp;&nbsp;<span>Finalizar</span>
</button>
<div class="d-flex justify-content-end"> <div class="d-flex justify-content-end">
<button type="button" class="ds-btn ds-btn--secondary" (click)="previousState()"> <button type="button" class="ds-btn ds-btn--secondary" (click)="previousState()">
@ -50,6 +61,7 @@
[disabled]="isLoading" [disabled]="isLoading"
data-toggle="modal" data-toggle="modal"
data-target="#crearPregunta" data-target="#crearPregunta"
*ngIf="encuesta!.estado !== 'FINISHED' && (isAutor() || isEscritor())"
> >
<fa-icon icon="sync" [icon]="faPlus"></fa-icon>&nbsp;&nbsp;<span>Crear pregunta</span> <fa-icon icon="sync" [icon]="faPlus"></fa-icon>&nbsp;&nbsp;<span>Crear pregunta</span>
</button> </button>
@ -100,7 +112,7 @@
> >
</span> </span>
<fa-icon <fa-icon
*ngIf="encuesta!.estado === 'DRAFT'" *ngIf="encuesta!.estado === 'DRAFT' && (isAutor() || isEscritor())"
class="ds-survey--titulo--icon" class="ds-survey--titulo--icon"
[icon]="faTimes" [icon]="faTimes"
(click)="deleteQuestion($event)" (click)="deleteQuestion($event)"
@ -132,7 +144,7 @@
<!-- <input class="ds-survey--checkbox" id="{{ ePregunta.id }}-{{ ePreguntaOpcionFinal.id }}" type="checkbox" disabled /> --> <!-- <input class="ds-survey--checkbox" id="{{ ePregunta.id }}-{{ ePreguntaOpcionFinal.id }}" type="checkbox" disabled /> -->
<label for="{{ ePregunta.id }}-{{ ePreguntaOpcionFinal.id }}">{{ ePreguntaOpcionFinal.nombre }}</label> <label for="{{ ePregunta.id }}-{{ ePreguntaOpcionFinal.id }}">{{ ePreguntaOpcionFinal.nombre }}</label>
<fa-icon <fa-icon
*ngIf="encuesta!.estado === 'DRAFT'" *ngIf="encuesta!.estado === 'DRAFT' && (isAutor() || isEscritor())"
class="ds-survey--titulo--icon ds-survey--titulo--icon--small" class="ds-survey--titulo--icon ds-survey--titulo--icon--small"
[icon]="faTimes" [icon]="faTimes"
(click)="deleteOption($event)" (click)="deleteOption($event)"
@ -148,6 +160,7 @@
data-toggle="modal" data-toggle="modal"
data-target="#crearOpcion" data-target="#crearOpcion"
[attr.data-id]="ePregunta.id" [attr.data-id]="ePregunta.id"
*ngIf="isAutor() || isEscritor()"
> >
<fa-icon <fa-icon
class="ds-survey--add-option--icon" class="ds-survey--add-option--icon"
@ -432,3 +445,163 @@
</div> </div>
<!-- ------------------------------------------------------------------------------------------------- --> <!-- ------------------------------------------------------------------------------------------------- -->
<!-- ------------------------------------------------------------------------------------------------- -->
<!-- Survey Update Colaborator -->
<div
class="modal fade ds-modal"
id="modalUpdateColaborators"
tabindex="-1"
role="dialog"
aria-labelledby="verColaboradoresTitle"
aria-hidden="true"
*ngIf="colaborador && isAutor()"
>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<form class="ds-form" name="editFormUpdateCollab" role="form" (ngSubmit)="saveCollab()" [formGroup]="editFormUpdateCollab">
<div class="modal-header">
<h1 class="modal-title" id="modalColaboradores">Colaborador</h1>
</div>
<div class="modal-body">
<div>
<div class="mb-5" *ngIf="colaborador.usuarioExtra">
<p class="ds-subtitle">Nombre</p>
<p>{{ colaborador!.usuarioExtra.nombre }}</p>
</div>
<div>
<label for="field_update_rol">Rol</label>
<select class="form-control" name="rol" formControlName="rol" id="field_update_rol" data-cy="rol">
<option value="READ" [selected]="colaborador.rol === 'READ'">Lector</option>
<option value="WRITE" [selected]="colaborador.rol === 'WRITE'">Escritor</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button id="btnCancelUbdateColaboradores" type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span>Cancelar</span>
</button>
<button type="button" (click)="deleteCollab(colaborador)" class="ds-btn ds-btn--danger btn-sm" data-cy="entityDeleteButton">
<fa-icon icon="times"></fa-icon>
<span class="d-none d-md-inline" jhiTranslate="dataSurveyApp.usuarioEncuesta.delete.action">Delete</span>
</button>
<button
id="btnUpdateColaboradores"
type="submit"
class="ds-btn ds-btn--primary"
data-cy="entityUpdateButton"
[disabled]="isSavingCollab"
>
&nbsp;<span>Guardar</span>
</button>
</div>
</form>
</div>
</div>
</div>
<!-- ------------------------------------------------------------------------------------------------- -->
<!-- Survey Add Colaborator -->
<div
class="modal fade ds-modal"
id="modalAddColaborators"
tabindex="-1"
role="dialog"
aria-labelledby="verColaboradoresTitle"
aria-hidden="true"
*ngIf="isAutor()"
>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<form class="ds-form" name="editFormAddCollab" role="form" (ngSubmit)="saveAddCollab()" [formGroup]="editFormAddCollab">
<div class="modal-header">
<h1 class="modal-title" id="modalAddColaboradores">Añadir Colaborador</h1>
</div>
<div class="modal-body">
<div *ngIf="userCollabNotExist" class="alert alert-danger alert-dismissible fade show" role="alert">
No existe un usuario con ese correo
</div>
<div *ngIf="userCollabIsCollab" class="alert alert-danger alert-dismissible fade show" role="alert">
Este usuario ya se encuentra colaborando
</div>
<div *ngIf="userCollabIsAutor" class="alert alert-danger alert-dismissible fade show" role="alert">
Usted es el autor de la encuesta, no puede ser colaborador
</div>
<div>
<div class="mb-5">
<p class="ds-subtitle">Correo electrónico</p>
<input type="email" class="form-control" name="email_add" id="field_add_email" data-cy="email" formControlName="email_add" />
<div
*ngIf="
editFormAddCollab.get('email_add')!.invalid &&
(editFormAddCollab.get('email_add')!.dirty || editFormAddCollab.get('email_add')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="editFormAddCollab.get('email_add')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
<small
class="form-text text-danger"
*ngIf="editFormAddCollab.get('email_add')?.errors?.invalid"
jhiTranslate="global.messages.validate.email.invalid"
>
Your email is invalid.
</small>
</div>
</div>
<div>
<label for="field_update_rol">Rol</label>
<select class="form-control" name="rol_add" formControlName="rol_add" id="field_rol_add" data-cy="rol_add">
<option value="READ">Lector</option>
<option value="WRITE">Escritor</option>
</select>
<div
*ngIf="
editFormAddCollab.get('rol_add')!.invalid &&
(editFormAddCollab.get('rol_add')!.dirty || editFormAddCollab.get('rol_add')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="editFormAddCollab.get('rol_add')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button
id="btnCancelAddColaboradores"
(click)="resetFormAddCollab()"
type="button"
class="ds-btn ds-btn--secondary"
data-dismiss="modal"
>
<fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span>Cancelar</span>
</button>
<button
id="btnAddColaboradores"
type="submit"
class="ds-btn ds-btn--primary"
data-cy="entityAddButton"
[disabled]="editFormAddCollab.invalid || isSavingAddCollab"
>
<span>Añadir</span>
</button>
</div>
</form>
</div>
</div>
</div>
<!-- ------------------------------------------------------------------------------------------------- -->

View File

@ -1,23 +1,23 @@
import { EPreguntaAbierta, IEPreguntaAbierta } from './../../e-pregunta-abierta/e-pregunta-abierta.model'; import { EPreguntaAbierta, IEPreguntaAbierta } from './../../e-pregunta-abierta/e-pregunta-abierta.model';
import { EPreguntaCerrada } from './../../e-pregunta-cerrada/e-pregunta-cerrada.model'; import { EPreguntaCerrada } from './../../e-pregunta-cerrada/e-pregunta-cerrada.model';
import { EPreguntaCerradaOpcion, IEPreguntaCerradaOpcion } from './../../e-pregunta-cerrada-opcion/e-pregunta-cerrada-opcion.model'; import { IEPreguntaCerradaOpcion } from './../../e-pregunta-cerrada-opcion/e-pregunta-cerrada-opcion.model';
import { EPreguntaAbiertaService } from './../../e-pregunta-abierta/service/e-pregunta-abierta.service'; import { EPreguntaAbiertaService } from './../../e-pregunta-abierta/service/e-pregunta-abierta.service';
import { EPreguntaCerradaOpcionService } from './../../e-pregunta-cerrada-opcion/service/e-pregunta-cerrada-opcion.service'; import { EPreguntaCerradaOpcionService } from './../../e-pregunta-cerrada-opcion/service/e-pregunta-cerrada-opcion.service';
import { AfterViewChecked, Component, OnInit } from '@angular/core'; import { AfterViewChecked, Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http'; import { HttpResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms'; import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { finalize, map } from 'rxjs/operators'; import { finalize } from 'rxjs/operators';
import * as dayjs from 'dayjs'; import * as dayjs from 'dayjs';
import { DATE_TIME_FORMAT } from 'app/config/input.constants'; import { DATE_TIME_FORMAT } from 'app/config/input.constants';
import { IEncuesta, Encuesta } from '../encuesta.model'; import { Encuesta } from '../encuesta.model';
import { EncuestaService } from '../service/encuesta.service'; import { EncuestaService } from '../service/encuesta.service';
import { ICategoria } from 'app/entities/categoria/categoria.model'; import { ICategoria } from 'app/entities/categoria/categoria.model';
import { CategoriaService } from 'app/entities/categoria/service/categoria.service'; import { CategoriaService } from 'app/entities/categoria/service/categoria.service';
import { IUsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model'; import { IUsuarioExtra, UsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model';
import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service'; import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@ -25,17 +25,26 @@ import { IEPreguntaCerrada } from 'app/entities/e-pregunta-cerrada/e-pregunta-ce
import { EPreguntaCerradaService } from 'app/entities/e-pregunta-cerrada/service/e-pregunta-cerrada.service'; import { EPreguntaCerradaService } from 'app/entities/e-pregunta-cerrada/service/e-pregunta-cerrada.service';
import { EPreguntaCerradaDeleteDialogComponent } from 'app/entities/e-pregunta-cerrada/delete/e-pregunta-cerrada-delete-dialog.component'; import { EPreguntaCerradaDeleteDialogComponent } from 'app/entities/e-pregunta-cerrada/delete/e-pregunta-cerrada-delete-dialog.component';
import { faTimes, faPlus, faQuestion, faPollH, faEye } from '@fortawesome/free-solid-svg-icons'; import { faEye, faPlus, faPollH, faQuestion, faTimes } from '@fortawesome/free-solid-svg-icons';
import { PreguntaCerradaTipo } from 'app/entities/enumerations/pregunta-cerrada-tipo.model'; import { PreguntaCerradaTipo } from 'app/entities/enumerations/pregunta-cerrada-tipo.model';
import { EncuestaDeleteQuestionDialogComponent } from '../encuesta-delete-question-dialog/encuesta-delete-question-dialog.component'; import { EncuestaDeleteQuestionDialogComponent } from '../encuesta-delete-question-dialog/encuesta-delete-question-dialog.component';
import { EncuestaDeleteOptionDialogComponent } from '../encuesta-delete-option-dialog/encuesta-delete-option-dialog.component'; import { EncuestaDeleteOptionDialogComponent } from '../encuesta-delete-option-dialog/encuesta-delete-option-dialog.component';
import { ParametroAplicacionService } from './../../parametro-aplicacion/service/parametro-aplicacion.service'; import { ParametroAplicacionService } from './../../parametro-aplicacion/service/parametro-aplicacion.service';
import { IParametroAplicacion } from './../../parametro-aplicacion/parametro-aplicacion.model'; import { IParametroAplicacion } from './../../parametro-aplicacion/parametro-aplicacion.model';
import { Router } from '@angular/router';
import { UsuarioEncuestaService } from 'app/entities/usuario-encuesta/service/usuario-encuesta.service'; import { UsuarioEncuestaService } from 'app/entities/usuario-encuesta/service/usuario-encuesta.service';
import { IUsuarioEncuesta } from '../../usuario-encuesta/usuario-encuesta.model'; import { IUsuarioEncuesta, UsuarioEncuesta } from '../../usuario-encuesta/usuario-encuesta.model';
import { RolColaborador } from '../../enumerations/rol-colaborador.model';
import { Account } from '../../../core/auth/account.model';
import { AccountService } from 'app/core/auth/account.service';
import { EncuestaFinalizarDialogComponent } from '../encuesta-finalizar-dialog/encuesta-finalizar-dialog.component';
import { EncuestaDeleteColaboratorDialogComponent } from '../encuesta-delete-colaborator-dialog/encuesta-delete-colaborator-dialog.component';
import { IUser } from '../../user/user.model';
import * as $ from 'jquery';
import { UserService } from '../../user/user.service';
import { EstadoColaborador } from '../../enumerations/estado-colaborador.model';
@Component({ @Component({
selector: 'jhi-encuesta-update', selector: 'jhi-encuesta-update',
@ -50,10 +59,17 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
isSaving = false; isSaving = false;
isSavingQuestion = false; isSavingQuestion = false;
isSavingCollab = false;
isSavingAddCollab = false;
finalizada = false;
public rolSeleccionado: RolColaborador | undefined = undefined;
categoriasSharedCollection: ICategoria[] = []; categoriasSharedCollection: ICategoria[] = [];
usuarioExtrasSharedCollection: IUsuarioExtra[] = []; usuarioExtrasSharedCollection: IUsuarioExtra[] = [];
usuariosColaboradores: IUsuarioEncuesta[] = []; usuariosColaboradores: IUsuarioEncuesta[] = [];
colaborador: IUsuarioEncuesta | null = null;
account: Account | null = null;
usuarioExtra: UsuarioExtra | null = null;
// editForm = this.fb.group({ // editForm = this.fb.group({
// id: [], // id: [],
@ -87,6 +103,15 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
tipopregunta: ['CLOSED'], tipopregunta: ['CLOSED'],
}); });
editFormUpdateCollab = this.fb.group({
rol: [null, [Validators.required]],
});
editFormAddCollab = this.fb.group({
email_add: [null, [Validators.required, Validators.email]],
rol_add: [null, [Validators.required]],
});
ePreguntas?: any[]; ePreguntas?: any[];
ePreguntasOpciones?: any[]; ePreguntasOpciones?: any[];
encuesta: Encuesta | null = null; encuesta: Encuesta | null = null;
@ -98,6 +123,11 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
createAnotherQuestion: Boolean = false; createAnotherQuestion: Boolean = false;
selectedQuestionToCreateOption: IEPreguntaCerrada | null = null; selectedQuestionToCreateOption: IEPreguntaCerrada | null = null;
userPublicCollab: IUser | null = null;
usuarioExtraCollab: UsuarioExtra | null = null;
userCollabNotExist: boolean = false;
userCollabIsCollab: boolean = false;
userCollabIsAutor: boolean = false;
constructor( constructor(
protected encuestaService: EncuestaService, protected encuestaService: EncuestaService,
protected categoriaService: CategoriaService, protected categoriaService: CategoriaService,
@ -110,7 +140,9 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
protected parametroAplicacionService: ParametroAplicacionService, protected parametroAplicacionService: ParametroAplicacionService,
protected ePreguntaAbiertaService: EPreguntaAbiertaService, protected ePreguntaAbiertaService: EPreguntaAbiertaService,
protected usuarioEncuestaService: UsuarioEncuestaService, protected usuarioEncuestaService: UsuarioEncuestaService,
protected router: Router protected router: Router,
protected accountService: AccountService,
protected userService: UserService
) {} ) {}
loadAll(): void { loadAll(): void {
@ -170,6 +202,15 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
// this.loadRelationshipsOptions(); // this.loadRelationshipsOptions();
}); });
// Get jhi_user and usuario_extra information
this.accountService.getAuthenticationState().subscribe(account => {
if (account !== null) {
this.usuarioExtraService.find(account.id).subscribe(usuarioExtra => {
this.usuarioExtra = usuarioExtra.body;
});
}
});
} }
ngAfterViewChecked(): void { ngAfterViewChecked(): void {
@ -595,4 +636,187 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
// usuarioExtra: this.editForm.get(['usuarioExtra'])!.value, // usuarioExtra: this.editForm.get(['usuarioExtra'])!.value,
// }; // };
// } // }
/* methods for colaborators*/
protected createFromFormCollab(): UsuarioEncuesta {
return {
id: undefined,
rol: this.editFormAddCollab.get(['rol_add'])!.value,
};
}
selectColaborator(c: IUsuarioEncuesta) {
this.colaborador = c;
this.rolSeleccionado = c.rol;
}
saveCollab(): void {
this.isSavingCollab = true;
const collab = this.colaborador;
if (collab !== null) {
collab.rol = this.editFormUpdateCollab.get('rol')!.value;
collab.fechaAgregado = dayjs(this.colaborador?.fechaAgregado, DATE_TIME_FORMAT);
/*this.usuarioEncuestaService.update(collab).subscribe(
res => {},
(error) => {console.log(error)}
);*/
this.subscribeToSaveResponseUpdateCollab(this.usuarioEncuestaService.update(collab));
}
}
resetFormAddCollab(): void {
this.editFormAddCollab.reset();
this.userPublicCollab = null;
}
saveAddCollab(): void {
this.isSavingAddCollab = true;
this.userCollabIsAutor = false;
this.userCollabIsCollab = false;
this.userCollabNotExist = false;
const collab = this.createFromFormCollab();
let rol = this.editFormAddCollab.get('rol_add')!.value;
if (rol === 'READ') {
collab.rol = RolColaborador.READ;
} else if (rol === 'WRITE') {
collab.rol = RolColaborador.WRITE;
}
let correoCollab = this.editFormAddCollab.get('email_add')!.value;
this.userService
.retrieveAllPublicUsers()
.pipe(
finalize(() => {
if (this.userPublicCollab?.id !== undefined) {
if (correoCollab === this.usuarioExtra?.user?.login) {
this.userCollabIsAutor = true;
this.isSavingAddCollab = false;
} else if (this.validarUserIsCollab(correoCollab)) {
this.userCollabIsCollab = true;
this.isSavingAddCollab = false;
} else {
this.usuarioExtraService.find(this.userPublicCollab?.id).subscribe(res => {
this.usuarioExtraCollab = res.body;
let now = new Date();
collab.fechaAgregado = dayjs(now);
collab.usuarioExtra = this.usuarioExtraCollab;
collab.estado = EstadoColaborador.PENDING;
collab.encuesta = this.encuesta;
let id = 0;
this.subscribeToSaveResponseAddCollab(this.usuarioEncuestaService.create(collab));
});
}
} else {
this.userCollabNotExist = true;
this.isSavingAddCollab = false;
}
this.resetFormAddCollab();
})
)
.subscribe(res => {
res.forEach(user => {
if (user.login === correoCollab) {
this.userPublicCollab = user;
}
if (user.id === this.usuarioExtra?.id) {
// @ts-ignore
this.usuarioExtra?.user?.login = user.login;
}
});
});
}
protected subscribeToSaveResponseUpdateCollab(result: Observable<HttpResponse<IUsuarioEncuesta>>): void {
result.pipe(finalize(() => this.onSaveFinalizeUpdateCollab())).subscribe(
() => this.onSaveSuccessUpdateCollab(),
() => this.onSaveErrorUpdateCollab()
);
}
protected onSaveSuccessUpdateCollab(): void {
this.loadAll();
$('#btnCancelUbdateColaboradores').click();
}
protected onSaveErrorUpdateCollab(): void {
// Api for inheritance.
}
protected onSaveFinalizeUpdateCollab(): void {
this.isSavingCollab = false;
}
protected subscribeToSaveResponseAddCollab(result: Observable<HttpResponse<IUsuarioEncuesta>>): void {
result.pipe(finalize(() => this.onSaveFinalizeAddCollab())).subscribe(
() => this.onSaveSuccessAddCollab(),
() => this.onSaveErrorAddCollab()
);
}
protected onSaveSuccessAddCollab(): void {
this.loadAll();
$('#btnCancelAddColaboradores').click();
}
protected onSaveErrorAddCollab(): void {
// Api for inheritance.
}
protected onSaveFinalizeAddCollab(): void {
this.isSavingAddCollab = false;
}
deleteCollab(collab: IUsuarioEncuesta) {
//$('#btnCancelUbdateColaboradores').click();
//setTimeout(() => {
const modalRef = this.modalService.open(EncuestaDeleteColaboratorDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.componentInstance.colaborador = collab;
// unsubscribe not needed because closed completes on modal close
modalRef.closed.subscribe(reason => {
if (reason === 'deleted') {
$('#btnCancelUbdateColaboradores').click();
this.loadAll();
}
});
//}, 500);
}
isAutor() {
return this.usuarioExtra?.id === this.encuesta?.usuarioExtra?.id;
}
isEscritor() {
let escritor = false;
this.usuariosColaboradores.forEach(c => {
if (this.usuarioExtra?.id === c.usuarioExtra?.id) {
if (c.rol === 'WRITE') {
escritor = true;
}
}
});
return escritor;
}
validarUserIsCollab(correoCollab: string) {
let isCollab = false;
this.usuariosColaboradores.forEach(c => {
if (c.usuarioExtra?.id === this.userPublicCollab?.id) {
isCollab = true;
}
});
return isCollab;
}
finalizar(): void {
const modalRef = this.modalService.open(EncuestaFinalizarDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.componentInstance.encuesta = this.encuesta;
// unsubscribe not needed because closed completes on modal close
modalRef.closed.subscribe(reason => {
if (reason === 'finalized') {
this.finalizada = true;
this.loadAll();
}
});
}
} }

View File

@ -42,7 +42,7 @@ import { RouterModule } from '@angular/router';
import('./e-pregunta-cerrada-opcion/e-pregunta-cerrada-opcion.module').then(m => m.EPreguntaCerradaOpcionModule), import('./e-pregunta-cerrada-opcion/e-pregunta-cerrada-opcion.module').then(m => m.EPreguntaCerradaOpcionModule),
}, },
{ {
path: 'usuario-encuesta', path: 'colaboraciones',
data: { pageTitle: 'dataSurveyApp.usuarioEncuesta.home.title' }, data: { pageTitle: 'dataSurveyApp.usuarioEncuesta.home.title' },
loadChildren: () => import('./usuario-encuesta/usuario-encuesta.module').then(m => m.UsuarioEncuestaModule), loadChildren: () => import('./usuario-encuesta/usuario-encuesta.module').then(m => m.UsuarioEncuestaModule),
}, },

View File

@ -16,8 +16,8 @@ export class PPreguntaCerradaOpcionService {
constructor(protected http: HttpClient, protected applicationConfigService: ApplicationConfigService) {} constructor(protected http: HttpClient, protected applicationConfigService: ApplicationConfigService) {}
create(pPreguntaCerradaOpcion: IPPreguntaCerradaOpcion): Observable<EntityResponseType> { create(pPreguntaCerradaOpcion: IPPreguntaCerradaOpcion, preguntaId?: number): Observable<EntityResponseType> {
return this.http.post<IPPreguntaCerradaOpcion>(this.resourceUrl, pPreguntaCerradaOpcion, { observe: 'response' }); return this.http.post<IPPreguntaCerradaOpcion>(`${this.resourceUrl}/${preguntaId}`, pPreguntaCerradaOpcion, { observe: 'response' });
} }
update(pPreguntaCerradaOpcion: IPPreguntaCerradaOpcion): Observable<EntityResponseType> { update(pPreguntaCerradaOpcion: IPPreguntaCerradaOpcion): Observable<EntityResponseType> {
@ -49,6 +49,10 @@ export class PPreguntaCerradaOpcionService {
return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' }); return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' });
} }
deleteMany(ids: number[]): Observable<EntityResponseType> {
return this.http.post<IPPreguntaCerradaOpcion>(`${this.resourceUrl}/deleteMany`, ids, { observe: 'response' });
}
addPPreguntaCerradaOpcionToCollectionIfMissing( addPPreguntaCerradaOpcionToCollectionIfMissing(
pPreguntaCerradaOpcionCollection: IPPreguntaCerradaOpcion[], pPreguntaCerradaOpcionCollection: IPPreguntaCerradaOpcion[],
...pPreguntaCerradaOpcionsToCheck: (IPPreguntaCerradaOpcion | null | undefined)[] ...pPreguntaCerradaOpcionsToCheck: (IPPreguntaCerradaOpcion | null | undefined)[]

View File

@ -1,58 +1,86 @@
<div class="row justify-content-center"> <div class="container-fluid" *ngIf="plantilla">
<div class="col-8"> <div>
<div *ngIf="plantilla"> <h2 id="page-heading" data-cy="PPreguntaCerradaHeading">
<h2 data-cy="plantillaDetailsHeading"><span jhiTranslate="dataSurveyApp.plantilla.detail.title">Plantilla</span></h2> <div class="d-flex align-items-center">
<p class="ds-title">Vista previa de {{ plantilla!.nombre }}</p>
</div>
<hr /> <p class="ds-subtitle">Creada el día {{ plantilla!.fechaCreacion | formatShortDatetime | lowercase }}</p>
<div class="d-flex justify-content-end">
<button type="button" class="ds-btn ds-btn--secondary" (click)="previousState()">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span jhiTranslate="entity.action.back">Back</span>
</button>
</div>
</h2>
<jhi-alert-error></jhi-alert-error> <jhi-alert-error></jhi-alert-error>
<jhi-alert></jhi-alert> <!-- <jhi-alert></jhi-alert> -->
<dl class="row-md jh-entity-details"> <div class="ds-survey preview-survey" id="entities">
<dt><span jhiTranslate="global.field.id">ID</span></dt> <div class="ds-survey--all-question-wrapper col-8">
<dd> <ng-container *ngIf="pPreguntas && pPreguntas.length === 0">
<span>{{ plantilla.id }}</span> <p class="ds-title text-center">Plantilla vacía</p>
</dd> <p class="ds-subtitle text-center">Inicie creando preguntas y opciones para su plantilla.</p>
<dt><span jhiTranslate="dataSurveyApp.plantilla.nombre">Nombre</span></dt> </ng-container>
<dd>
<span>{{ plantilla.nombre }}</span> <div class="ds-survey--question-wrapper card-plantilla lift" *ngFor="let pPregunta of pPreguntas; let i = index; trackBy: trackId">
</dd> <div
<dt><span jhiTranslate="dataSurveyApp.plantilla.descripcion">Descripcion</span></dt> [attr.data-index]="pPregunta.id"
<dd> [attr.data-tipo]="pPregunta.tipo"
<span>{{ plantilla.descripcion }}</span> [attr.data-opcional]="pPregunta.opcional"
</dd> class="ds-survey--question"
<dt><span jhiTranslate="dataSurveyApp.plantilla.fechaCreacion">Fecha Creacion</span></dt> >
<dd> <div class="ds-survey--titulo">
<span>{{ plantilla.fechaCreacion | formatMediumDatetime }}</span> <span class="ds-survey--titulo--name">{{ i + 1 }}. {{ pPregunta.nombre }}</span>
</dd> </div>
<dt><span jhiTranslate="dataSurveyApp.plantilla.fechaPublicacionTienda">Fecha Publicacion Tienda</span></dt> <div>
<dd> <span *ngIf="pPregunta.tipo === 'SINGLE'" class="ds-subtitle"
<span>{{ plantilla.fechaPublicacionTienda | formatMediumDatetime }}</span> >Pregunta de respuesta {{ 'dataSurveyApp.PreguntaCerradaTipo.SINGLE' | translate | lowercase }}
</dd> {{ pPregunta.opcional ? '(opcional)' : '' }}</span
<dt><span jhiTranslate="dataSurveyApp.plantilla.estado">Estado</span></dt> >
<dd> <span *ngIf="pPregunta.tipo === 'MULTIPLE'" class="ds-subtitle"
<span jhiTranslate="{{ 'dataSurveyApp.EstadoPlantilla.' + plantilla.estado }}">{{ plantilla.estado }}</span> >Pregunta de respuesta {{ 'dataSurveyApp.PreguntaCerradaTipo.MULTIPLE' | translate | lowercase }}
</dd> {{ pPregunta.opcional ? '(opcional)' : '' }}</span
<dt><span jhiTranslate="dataSurveyApp.plantilla.precio">Precio</span></dt> >
<dd> <span *ngIf="!pPregunta.tipo" class="ds-subtitle"
<span>{{ plantilla.precio }}</span> >Pregunta de respuesta abierta {{ pPregunta.opcional ? '(opcional)' : '' }}</span
</dd> >
<dt><span jhiTranslate="dataSurveyApp.plantilla.categoria">Categoria</span></dt> </div>
<dd> <ng-container *ngIf="pPregunta.tipo">
<div *ngIf="plantilla.categoria"> <ng-container *ngFor="let pPreguntaOpcion of pPreguntasOpciones; let j = index; trackBy: trackId">
<a [routerLink]="['/categoria', plantilla.categoria?.id, 'view']">{{ plantilla.categoria?.nombre }}</a> <ng-container *ngFor="let pPreguntaOpcionFinal of pPreguntaOpcion">
<ng-container *ngIf="pPregunta.id === pPreguntaOpcionFinal.ppreguntaCerrada.id">
<div
class="ds-survey--option ds-survey--option--base ds-survey--closed-option can-delete"
[attr.data-id]="pPreguntaOpcionFinal.id"
>
<div class="radio" *ngIf="pPregunta.tipo === 'SINGLE'">
<input
type="radio"
style="border-radius: 3px"
name="{{ 'radio' + pPregunta.id }}"
id="{{ 'radio' + pPreguntaOpcionFinal.id }}"
/>
<!-- <input class="ds-survey--checkbox" id="{{ pPregunta.id }}-{{ pPreguntaOpcionFinal.id }}" type="checkbox" disabled /> -->
<label for="{{ 'radio' + pPreguntaOpcionFinal.id }}">{{ pPreguntaOpcionFinal.nombre }}</label>
</div>
<div class="checkbox" *ngIf="pPregunta.tipo === 'MULTIPLE'">
<input type="checkbox" style="border-radius: 3px" id="{{ 'checkbox' + pPreguntaOpcionFinal.id }}" />
<!-- <input class="ds-survey--checkbox" id="{{ pPregunta.id }}-{{ pPreguntaOpcionFinal.id }}" type="checkbox" disabled /> -->
<label for="{{ 'checkbox' + pPreguntaOpcionFinal.id }}">{{ pPreguntaOpcionFinal.nombre }}</label>
</div>
</div>
</ng-container>
</ng-container>
</ng-container>
</ng-container>
<div class="ds-survey--option ds-survey--option--base ds-survey--open-option" *ngIf="!pPregunta.tipo">
<textarea cols="30" rows="10" disabled></textarea>
</div>
</div> </div>
</dd> </div>
</dl> </div>
<button type="submit" (click)="previousState()" class="btn btn-info" data-cy="entityDetailsBackButton">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;<span jhiTranslate="entity.action.back">Back</span>
</button>
<button type="button" [routerLink]="['/plantilla', plantilla.id, 'edit']" class="btn btn-primary">
<fa-icon icon="pencil-alt"></fa-icon>&nbsp;<span jhiTranslate="entity.action.edit">Edit</span>
</button>
</div> </div>
</div> </div>
</div> </div>

View File

@ -1,21 +1,152 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router'; import { ActivatedRoute } from '@angular/router';
import { EstadoPlantilla } from 'app/entities/enumerations/estado-plantilla.model';
import { IPlantilla } from '../plantilla.model'; import { Observable } from 'rxjs';
import { finalize, map } from 'rxjs/operators';
import * as dayjs from 'dayjs';
import { DATE_TIME_FORMAT } from 'app/config/input.constants';
import { IPlantilla, Plantilla } from '../plantilla.model';
import { PlantillaService } from '../service/plantilla.service';
import { ICategoria } from 'app/entities/categoria/categoria.model';
import { CategoriaService } from 'app/entities/categoria/service/categoria.service';
import { IUsuarioExtra, UsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model';
import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { IPPreguntaCerrada } from 'app/entities/p-pregunta-cerrada/p-pregunta-cerrada.model';
import { PPreguntaCerradaService } from 'app/entities/p-pregunta-cerrada/service/p-pregunta-cerrada.service';
import { PPreguntaCerradaDeleteDialogComponent } from 'app/entities/p-pregunta-cerrada/delete/p-pregunta-cerrada-delete-dialog.component';
import { IPPreguntaAbierta } from '../../p-pregunta-abierta/p-pregunta-abierta.model';
import { PPreguntaCerrada } from '../../p-pregunta-cerrada/p-pregunta-cerrada.model';
import { PPreguntaCerradaOpcion, IPPreguntaCerradaOpcion } from '../../p-pregunta-cerrada-opcion/p-pregunta-cerrada-opcion.model';
import { PPreguntaAbiertaService } from '../../p-pregunta-abierta/service/p-pregunta-abierta.service';
import { PPreguntaCerradaOpcionService } from '../../p-pregunta-cerrada-opcion/service/p-pregunta-cerrada-opcion.service';
import { PreguntaCerradaTipo } from 'app/entities/enumerations/pregunta-cerrada-tipo.model';
import { faTimes, faPlus, faStar, faQuestion } from '@fortawesome/free-solid-svg-icons';
import { Account } from '../../../core/auth/account.model';
import { AccountService } from 'app/core/auth/account.service';
@Component({ @Component({
selector: 'jhi-plantilla-detail', selector: 'jhi-plantilla-detail',
templateUrl: './plantilla-detail.component.html', templateUrl: './plantilla-detail.component.html',
}) })
export class PlantillaDetailComponent implements OnInit { export class PlantillaDetailComponent implements OnInit {
categoriasSharedCollection: ICategoria[] = [];
usuarioExtrasSharedCollection: IUsuarioExtra[] = [];
faTimes = faTimes;
faPlus = faPlus;
faStar = faStar;
faQuestion = faQuestion;
plantilla: IPlantilla | null = null; plantilla: IPlantilla | null = null;
isLoading = false;
successPublished = false;
pPreguntas?: any[];
pPreguntasOpciones?: any[];
usuarioExtra: UsuarioExtra | null = null;
constructor(protected activatedRoute: ActivatedRoute) {} constructor(
protected activatedRoute: ActivatedRoute,
protected plantillaService: PlantillaService,
protected categoriaService: CategoriaService,
protected usuarioExtraService: UsuarioExtraService,
protected fb: FormBuilder,
protected modalService: NgbModal,
protected pPreguntaCerradaService: PPreguntaCerradaService,
protected pPreguntaCerradaOpcionService: PPreguntaCerradaOpcionService,
protected pPreguntaAbiertaService: PPreguntaAbiertaService,
protected accountService: AccountService
) {}
ngOnInit(): void { ngOnInit(): void {
this.activatedRoute.data.subscribe(({ plantilla }) => { this.activatedRoute.data.subscribe(({ plantilla }) => {
this.plantilla = plantilla; if (plantilla) {
this.plantilla = plantilla;
this.loadAll();
} else {
this.previousState();
}
}); });
// Get jhi_user and usuario_extra information
this.accountService.getAuthenticationState().subscribe(account => {
if (account !== null) {
this.usuarioExtraService.find(account.id).subscribe(usuarioExtra => {
this.usuarioExtra = usuarioExtra.body;
});
}
});
}
ngAfterViewChecked(): void {
this.initListeners();
}
initListeners(): void {
const checkboxes = document.getElementsByClassName('ds-survey--checkbox');
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', e => {
if ((e.target as HTMLInputElement).checked) {
(e.target as HTMLElement).offsetParent!.classList.add('ds-survey--closed-option--active');
} else {
(e.target as HTMLElement).offsetParent!.classList.remove('ds-survey--closed-option--active');
}
});
}
}
trackId(index: number, item: IPPreguntaCerrada): number {
return item.id!;
}
trackPPreguntaCerradaById(index: number, item: IPPreguntaCerrada): number {
return item.id!;
}
trackCategoriaById(index: number, item: ICategoria): number {
return item.id!;
}
trackUsuarioExtraById(index: number, item: IUsuarioExtra): number {
return item.id!;
}
getPlantilla(id: number) {
return this.plantillaService.findPlantilla(id);
}
loadAll(): void {
this.isLoading = true;
this.plantillaService
.findQuestions(this.plantilla?.id!)
.pipe(
finalize(() =>
this.plantillaService.findQuestionsOptions(this.plantilla?.id!).subscribe(
(res: any) => {
this.isLoading = false;
this.pPreguntasOpciones = res.body ?? [];
},
() => {
this.isLoading = false;
}
)
)
)
.subscribe(
(res: any) => {
this.isLoading = false;
this.pPreguntas = res.body ?? [];
},
() => {
this.isLoading = false;
}
);
} }
previousState(): void { previousState(): void {

View File

@ -1,28 +1,34 @@
<div> <div>
<h2 id="page-heading" data-cy="PlantillaHeading"> <h2 id="page-heading" data-cy="PlantillaHeading">
<span jhiTranslate="dataSurveyApp.plantilla.home.title">Plantillas</span> <div class="d-flex flex-sm-row flex-column justify-content-between align-items-center">
<div>
<span class="ds-title" jhiTranslate="dataSurveyApp.plantilla.home.title">Encuestas</span>
<p class="ds-subtitle">Administre las plantillas comprables de la tienda</p>
</div>
<div class="d-flex justify-content-end"> <div>
<button class="ds-btn btn-info mr-2" (click)="loadAll()" [disabled]="isLoading"> <button class="ds-btn ds-btn--secondary" (click)="loadAll()" [disabled]="isLoading">
<fa-icon icon="sync" [spin]="isLoading"></fa-icon> <fa-icon icon="sync" [spin]="isLoading"></fa-icon>
<span jhiTranslate="dataSurveyApp.plantilla.home.refreshListLabel">Refresh List</span> <span jhiTranslate="dataSurveyApp.plantilla.home.refreshListLabel">Refresh List</span>
</button> </button>
<button <button
id="jh-create-entity" *ngIf="isAdmin() && isAuthenticated()"
data-cy="entityCreateButton" type="button"
class="ds-btn ds-btn--primary jh-create-entity create-plantilla" class="ds-btn ds-btn--primary"
[routerLink]="['/plantilla/new']" (click)="resetCreateTemplateForm()"
> data-toggle="modal"
<fa-icon icon="plus"></fa-icon> data-target="#crearPlantilla"
<span jhiTranslate="dataSurveyApp.plantilla.home.createLabel"> Create a new Template </span> >
</button> Crear plantilla
</button>
</div>
</div> </div>
</h2> </h2>
<jhi-alert-error></jhi-alert-error> <!-- <jhi-alert-error></jhi-alert-error>
<jhi-alert></jhi-alert> <jhi-alert></jhi-alert> -->
<div class="alert alert-warning" id="no-result" *ngIf="plantillas?.length === 0"> <div class="alert alert-warning" id="no-result" *ngIf="plantillas?.length === 0">
<span jhiTranslate="dataSurveyApp.plantilla.home.notFound">No templates found</span> <span jhiTranslate="dataSurveyApp.plantilla.home.notFound">No templates found</span>
@ -34,7 +40,7 @@
<tr> <tr>
<th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.nombre">Nombre</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.nombre">Nombre</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.descripcion">Descripcion</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.descripcion">Descripcion</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.fechaCreacion">Fecha Creacion</span></th> <!-- <th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.fechaCreacion">Fecha Creacion</span></th> -->
<th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.fechaPublicacionTienda">Fecha Publicacion Tienda</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.fechaPublicacionTienda">Fecha Publicacion Tienda</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.estado">Estado</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.estado">Estado</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.precio">Precio</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.precio">Precio</span></th>
@ -46,25 +52,23 @@
<tr *ngFor="let plantilla of plantillas; trackBy: trackId" data-cy="entityTable"> <tr *ngFor="let plantilla of plantillas; trackBy: trackId" data-cy="entityTable">
<td>{{ plantilla.nombre }}</td> <td>{{ plantilla.nombre }}</td>
<td>{{ plantilla.descripcion }}</td> <td>{{ plantilla.descripcion }}</td>
<td>{{ plantilla.fechaCreacion | formatMediumDatetime }}</td> <!-- <td>{{ plantilla.fechaCreacion | formatMediumDatetime }}</td> -->
<td>{{ plantilla.fechaPublicacionTienda | formatMediumDatetime }}</td> <td *ngIf="plantilla.fechaPublicacionTienda">{{ plantilla.fechaPublicacionTienda | formatShortDatetime | titlecase }}</td>
<td *ngIf="!plantilla.fechaPublicacionTienda">No establecida</td>
<td jhiTranslate="{{ 'dataSurveyApp.EstadoPlantilla.' + plantilla.estado }}">{{ plantilla.estado }}</td> <td jhiTranslate="{{ 'dataSurveyApp.EstadoPlantilla.' + plantilla.estado }}">{{ plantilla.estado }}</td>
<td>{{ plantilla.precio }}</td> <td *ngIf="plantilla.precio! > 0">${{ plantilla.precio | number: '1.2' }}</td>
<td> <td *ngIf="plantilla.precio! === 0">Gratis</td>
<div *ngIf="plantilla.categoria"> <td>{{ plantilla.categoria?.nombre }}</td>
<a [routerLink]="['/categoria', plantilla.categoria?.id, 'view']">{{ plantilla.categoria?.nombre }}</a>
</div>
</td>
<td class="text-right"> <td class="text-right">
<div class="btn-group"> <div class="btn-group">
<button <button
type="submit" type="submit"
[routerLink]="['/plantilla', plantilla.id, 'view']" [routerLink]="['/plantilla', plantilla.id, 'view']"
class="ds-btn btn-info btn-sm" class="ds-btn ds-btn--secondary btn-sm"
data-cy="entityDetailsButton" data-cy="entityDetailsButton"
> >
<fa-icon icon="eye"></fa-icon> <fa-icon icon="eye"></fa-icon>
<span class="d-none d-md-inline" jhiTranslate="entity.action.view">View</span> <span class="d-none d-md-inline">Vista previa</span>
</button> </button>
<button <button
@ -73,7 +77,6 @@
class="ds-btn ds-btn--primary btn-sm" class="ds-btn ds-btn--primary btn-sm"
data-cy="entityEditButton" data-cy="entityEditButton"
> >
<fa-icon icon="pencil-alt"></fa-icon>
<span class="d-none d-md-inline" jhiTranslate="entity.action.edit">Edit</span> <span class="d-none d-md-inline" jhiTranslate="entity.action.edit">Edit</span>
</button> </button>
@ -88,3 +91,164 @@
</table> </table>
</div> </div>
</div> </div>
<!-- Modal -->
<div
class="modal fade ds-modal"
id="crearPlantilla"
tabindex="-1"
role="dialog"
aria-labelledby="exampleModalCenterTitle"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<form
autocomplete="off"
class="ds-form"
name="templateCreateForm"
role="form"
novalidate
(ngSubmit)="save()"
[formGroup]="templateCreateForm"
>
<div class="modal-header">
<h1 class="modal-title" id="exampleModalLongTitle">Crear Plantilla</h1>
</div>
<div class="modal-body">
<!-- Template Registration Modal -->
<div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.encuesta.nombre" for="field_nombre">Nombre</label>
<input type="text" class="form-control" name="nombre" id="field_nombre" data-cy="nombre" formControlName="nombre" />
<div
*ngIf="
templateCreateForm.get('nombre')!.invalid &&
(templateCreateForm.get('nombre')!.dirty || templateCreateForm.get('nombre')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="templateCreateForm.get('nombre')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
<small
class="form-text text-danger"
*ngIf="templateCreateForm.get('nombre')?.errors?.minlength"
jhiTranslate="entity.validation.minlength"
[translateValues]="{ min: 1 }"
>
This field is required to be at least 1 characters.
</small>
<small
class="form-text text-danger"
*ngIf="templateCreateForm.get('nombre')?.errors?.maxlength"
jhiTranslate="entity.validation.maxlength"
[translateValues]="{ max: 50 }"
>
This field cannot be longer than 50 characters.
</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.encuesta.descripcion" for="field_descripcion"
>Descripcion</label
>
<input
type="text"
class="form-control"
name="descripcion"
id="field_descripcion"
data-cy="descripcion"
formControlName="descripcion"
/>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.plantilla.precio" for="field_precio">Precio</label>
<input type="number" min="0" class="form-control" name="precio" id="field_precio" data-cy="precio" formControlName="precio" />
<div
*ngIf="
templateCreateForm.get('precio')!.invalid &&
(templateCreateForm.get('precio')!.dirty || templateCreateForm.get('precio')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="templateCreateForm.get('precio')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
<small
class="form-text text-danger"
[hidden]="!templateCreateForm.get('precio')?.errors?.number"
jhiTranslate="entity.validation.number"
>
This field should be a number.
</small>
<small
class="form-text text-danger"
[hidden]="!templateCreateForm.get('precio')?.errors?.min"
jhiTranslate="entity.validation.minoigual"
>
This field should be great than or equals to 0.
</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.plantilla.categoria" for="field_categoria">Categoria</label>
<select class="form-control" id="field_categoria" data-cy="categoria" name="categoria" formControlName="categoria">
<option [ngValue]="null"></option>
<option
[ngValue]="
categoriaOption.id === templateCreateForm.get('categoria')!.value?.id
? templateCreateForm.get('categoria')!.value
: categoriaOption
"
*ngFor="let categoriaOption of categoriasSharedCollection; trackBy: trackCategoriaById"
>
{{ categoriaOption.nombre }}
</option>
</select>
<div
*ngIf="
templateCreateForm.get('categoria')!.invalid &&
(templateCreateForm.get('categoria')!.dirty || templateCreateForm.get('categoria')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="templateCreateForm.get('categoria')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input id="createAnother" type="checkbox" (change)="createAnotherTemplateChange($event)" />
<label for="createAnother">Crear otra</label>
<button id="cancelBtn" type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
class="ds-btn ds-btn--primary"
[disabled]="templateCreateForm.invalid || isSaving"
>
<span jhiTranslate="entity.action.create">Create</span>
</button>
</div>
</form>
</div>
</div>
</div>

View File

@ -1,11 +1,23 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http'; import { HttpResponse } from '@angular/common/http';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Observable } from 'rxjs';
import { finalize, map } from 'rxjs/operators';
import { IPlantilla } from '../plantilla.model'; import { IPlantilla, Plantilla } from '../plantilla.model';
import { PlantillaService } from '../service/plantilla.service'; import { PlantillaService } from '../service/plantilla.service';
import { PlantillaDeleteDialogComponent } from '../delete/plantilla-delete-dialog.component'; import { PlantillaDeleteDialogComponent } from '../delete/plantilla-delete-dialog.component';
import { AccountService } from 'app/core/auth/account.service';
import { Account } from 'app/core/auth/account.model';
import { FormBuilder, Validators } from '@angular/forms';
import { EstadoPlantilla } from 'app/entities/enumerations/estado-plantilla.model';
import { ICategoria } from 'app/entities/categoria/categoria.model';
import { CategoriaService } from 'app/entities/categoria/service/categoria.service';
import * as dayjs from 'dayjs';
import { DATE_TIME_FORMAT } from 'app/config/input.constants';
@Component({ @Component({
selector: 'jhi-plantilla', selector: 'jhi-plantilla',
templateUrl: './plantilla.component.html', templateUrl: './plantilla.component.html',
@ -13,8 +25,27 @@ import { PlantillaDeleteDialogComponent } from '../delete/plantilla-delete-dialo
export class PlantillaComponent implements OnInit { export class PlantillaComponent implements OnInit {
plantillas?: IPlantilla[]; plantillas?: IPlantilla[];
isLoading = false; isLoading = false;
isSaving = false;
createAnotherTemplate: Boolean = false;
constructor(protected plantillaService: PlantillaService, protected modalService: NgbModal) {} account: Account | null = null;
categoriasSharedCollection: ICategoria[] = [];
templateCreateForm = this.fb.group({
id: [],
nombre: [null, [Validators.required, Validators.minLength(1), Validators.maxLength(50)]],
descripcion: [[Validators.required]],
precio: [null, [Validators.required, Validators.min(0)]],
categoria: [null, [Validators.required]],
});
constructor(
protected plantillaService: PlantillaService,
protected modalService: NgbModal,
protected accountService: AccountService,
protected fb: FormBuilder,
protected categoriaService: CategoriaService
) {}
loadAll(): void { loadAll(): void {
this.isLoading = true; this.isLoading = true;
@ -32,6 +63,7 @@ export class PlantillaComponent implements OnInit {
ngOnInit(): void { ngOnInit(): void {
this.loadAll(); this.loadAll();
this.loadRelationshipsOptions();
} }
trackId(_index: number, item: IPlantilla): number { trackId(_index: number, item: IPlantilla): number {
@ -48,4 +80,90 @@ export class PlantillaComponent implements OnInit {
} }
}); });
} }
isAdmin(): boolean {
return this.accountService.hasAnyAuthority('ROLE_ADMIN');
}
isAuthenticated(): boolean {
return this.accountService.isAuthenticated();
}
resetCreateTemplateForm(): void {
this.templateCreateForm.reset();
}
createAnotherTemplateChange(event: any): void {
// ID: #crearPlantilla
this.createAnotherTemplate = event.target.checked;
}
previousState(): void {
window.history.back();
}
save(): void {
this.isSaving = true;
const plantilla = this.createFromForm();
if (plantilla.id !== undefined) {
this.subscribeToSaveResponse(this.plantillaService.update(plantilla));
} else {
this.subscribeToSaveResponse(this.plantillaService.create(plantilla));
}
}
trackCategoriaById(index: number, item: ICategoria): number {
return item.id!;
}
protected subscribeToSaveResponse(result: Observable<HttpResponse<IPlantilla>>): void {
result.pipe(finalize(() => this.onSaveFinalize())).subscribe(
() => this.onSaveSuccess(),
() => this.onSaveError()
);
}
protected onSaveSuccess(): void {
this.templateCreateForm.reset();
this.plantillas = [];
this.loadAll();
if (!this.createAnotherTemplate) {
$('#cancelBtn').click();
}
}
protected onSaveError(): void {
// Api for inheritance.
}
protected onSaveFinalize(): void {
this.isSaving = false;
}
protected loadRelationshipsOptions(): void {
this.categoriaService
.query()
.pipe(map((res: HttpResponse<ICategoria[]>) => res.body ?? []))
.pipe(
map((categorias: ICategoria[]) =>
this.categoriaService.addCategoriaToCollectionIfMissing(categorias, this.templateCreateForm.get('categoria')!.value)
)
)
.subscribe((categorias: ICategoria[]) => (this.categoriasSharedCollection = categorias));
}
protected createFromForm(): IPlantilla {
const now = dayjs();
return {
...new Plantilla(),
id: undefined,
nombre: this.templateCreateForm.get(['nombre'])!.value,
descripcion: this.templateCreateForm.get(['descripcion'])!.value,
fechaCreacion: dayjs(now, DATE_TIME_FORMAT),
estado: EstadoPlantilla.DRAFT,
precio: this.templateCreateForm.get(['precio'])!.value,
categoria: this.templateCreateForm.get(['categoria'])!.value,
};
}
} }

View File

@ -0,0 +1,24 @@
<form class="ds-form" name="deleteForm" (ngSubmit)="confirmDelete()">
<div class="modal-header">
<!-- <h2 class="ds-title" data-cy="encuestaDeleteDialogHeading" jhiTranslate="entity.delete.title">Confirm delete operation</h2>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click)="cancel()">&times;</button>-->
</div>
<div class="modal-body">
<p class="ds-title--small">Eliminar opción</p>
<p class="ds-subtitle" id="jhi-delete-encuesta-heading" jhiTranslate="dataSurveyApp.encuesta.delete.deleteoption">
Are you sure you want to delete this option?
</p>
</div>
<div class="modal-footer">
<button type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal" (click)="cancel()">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button id="jhi-confirm-delete-option" data-cy="entityConfirmDeleteButton" type="submit" class="ds-btn ds-btn--danger">
<fa-icon icon="times"></fa-icon>&nbsp;<span jhiTranslate="entity.action.delete">Delete</span>
</button>
</div>
</form>

View File

@ -0,0 +1,17 @@
import { Component } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
templateUrl: './plantilla-delete-option-dialog.component.html',
})
export class PlantillaDeleteOptionDialogComponent {
constructor(protected activeModal: NgbActiveModal) {}
cancel(): void {
this.activeModal.dismiss();
}
confirmDelete(): void {
this.activeModal.close('confirm');
}
}

View File

@ -0,0 +1,24 @@
<form class="ds-form" name="deleteForm" (ngSubmit)="confirmDelete()">
<div class="modal-header">
<!-- <h2 class="ds-title" data-cy="encuestaDeleteDialogHeading" jhiTranslate="entity.delete.title">Confirm delete operation</h2>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click)="cancel()">&times;</button>-->
</div>
<div class="modal-body">
<p class="ds-title--small">Eliminar pregunta</p>
<p class="ds-subtitle" id="jhi-delete-encuesta-heading" jhiTranslate="dataSurveyApp.encuesta.delete.deletequestion">
Are you sure you want to delete this question?
</p>
</div>
<div class="modal-footer">
<button type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal" (click)="cancel()">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button id="jhi-confirm-delete-question" data-cy="entityConfirmDeleteButton" type="submit" class="ds-btn ds-btn--danger">
<fa-icon icon="times"></fa-icon>&nbsp;<span jhiTranslate="entity.action.delete">Delete</span>
</button>
</div>
</form>

View File

@ -0,0 +1,17 @@
import { Component } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
templateUrl: './plantilla-delete-question-dialog.component.html',
})
export class PlantillaDeleteQuestionDialogComponent {
constructor(protected activeModal: NgbActiveModal) {}
cancel(): void {
this.activeModal.dismiss();
}
confirmDelete(): void {
this.activeModal.close('confirm');
}
}

View File

@ -0,0 +1,24 @@
<form class="ds-form" name="deleteForm" (ngSubmit)="confirmDeleteFromStore()">
<div class="modal-header">
<!-- <h2 class="ds-title" data-cy="encuestaDeleteDialogHeading" jhiTranslate="entity.delete.title">Confirm delete operation</h2>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click)="cancel()">&times;</button>-->
</div>
<div class="modal-body">
<p class="ds-title--small">Eliminar de la tienda</p>
<p class="ds-subtitle" id="jhi-delete-encuesta-heading" jhiTranslate="dataSurveyApp.plantilla.delete.deletefromstore">
Are you sure you want to delete this template from the store?
</p>
</div>
<div class="modal-footer">
<button type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal" (click)="cancel()">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button id="jhi-confirm-delete-option" data-cy="entityConfirmDeleteButton" type="submit" class="ds-btn ds-btn--danger">
<fa-icon icon="times"></fa-icon>&nbsp;<span jhiTranslate="entity.action.delete">Delete</span>
</button>
</div>
</form>

View File

@ -0,0 +1,17 @@
import { Component } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
templateUrl: './plantilla-delete-store-dialog.component.html',
})
export class PlantillaDeleteStoreDialogComponent {
constructor(protected activeModal: NgbActiveModal) {}
cancel(): void {
this.activeModal.dismiss();
}
confirmDeleteFromStore(): void {
this.activeModal.close('confirm');
}
}

View File

@ -0,0 +1,24 @@
<form class="ds-form" name="deleteForm" (ngSubmit)="confirmPublishToStore()">
<div class="modal-header">
<!-- <h2 class="ds-title" data-cy="encuestaDeleteDialogHeading" jhiTranslate="entity.delete.title">Confirm delete operation</h2>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click)="cancel()">&times;</button>-->
</div>
<div class="modal-body">
<p class="ds-title--small">Publicar en la tienda</p>
<p class="ds-subtitle" id="jhi-delete-encuesta-heading" jhiTranslate="dataSurveyApp.plantilla.publish.store">
Are you sure you want to publish this template to the store?
</p>
</div>
<div class="modal-footer">
<button type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal" (click)="cancel()">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button id="jhi-confirm-delete-option" data-cy="entityConfirmDeleteButton" type="submit" class="ds-btn ds-btn--primary">
<fa-icon [icon]="faStore"></fa-icon>&nbsp;<span jhiTranslate="entity.action.publish">Publish</span>
</button>
</div>
</form>

View File

@ -0,0 +1,20 @@
import { Component } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { faStore } from '@fortawesome/free-solid-svg-icons';
@Component({
templateUrl: './plantilla-publish-store-dialog.component.html',
})
export class PlantillaPublishStoreDialogComponent {
faStore = faStore;
constructor(protected activeModal: NgbActiveModal) {}
cancel(): void {
this.activeModal.dismiss();
}
confirmPublishToStore(): void {
this.activeModal.close('confirm');
}
}

View File

@ -5,10 +5,24 @@ import { PlantillaDetailComponent } from './detail/plantilla-detail.component';
import { PlantillaUpdateComponent } from './update/plantilla-update.component'; import { PlantillaUpdateComponent } from './update/plantilla-update.component';
import { PlantillaDeleteDialogComponent } from './delete/plantilla-delete-dialog.component'; import { PlantillaDeleteDialogComponent } from './delete/plantilla-delete-dialog.component';
import { PlantillaRoutingModule } from './route/plantilla-routing.module'; import { PlantillaRoutingModule } from './route/plantilla-routing.module';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { PlantillaDeleteQuestionDialogComponent } from './plantilla-delete-question-dialog/plantilla-delete-question-dialog.component';
import { PlantillaDeleteOptionDialogComponent } from './plantilla-delete-option-dialog/plantilla-delete-option-dialog.component';
import { PlantillaPublishStoreDialogComponent } from './plantilla-publish-store-dialog/plantilla-publish-store-dialog.component';
import { PlantillaDeleteStoreDialogComponent } from './plantilla-delete-store-dialog/plantilla-delete-store-dialog.component';
@NgModule({ @NgModule({
imports: [SharedModule, PlantillaRoutingModule], imports: [SharedModule, PlantillaRoutingModule, FontAwesomeModule],
declarations: [PlantillaComponent, PlantillaDetailComponent, PlantillaUpdateComponent, PlantillaDeleteDialogComponent], declarations: [
PlantillaComponent,
PlantillaDetailComponent,
PlantillaUpdateComponent,
PlantillaDeleteDialogComponent,
PlantillaDeleteQuestionDialogComponent,
PlantillaDeleteOptionDialogComponent,
PlantillaPublishStoreDialogComponent,
PlantillaDeleteStoreDialogComponent,
],
entryComponents: [PlantillaDeleteDialogComponent], entryComponents: [PlantillaDeleteDialogComponent],
}) })
export class PlantillaModule {} export class PlantillaModule {}

View File

@ -45,6 +45,22 @@ export class PlantillaService {
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
} }
findPlantilla(id: number): Observable<IPlantilla> {
return this.http.get<IPlantilla>(`${this.resourceUrl}/${id}`);
}
findQuestions(id: number): Observable<EntityResponseType> {
return this.http
.get<any>(`${this.resourceUrl}/preguntas/${id}`, { observe: 'response' })
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}
findQuestionsOptions(id: number): Observable<EntityResponseType> {
return this.http
.get<any>(`${this.resourceUrl}/preguntas-opciones/${id}`, { observe: 'response' })
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}
query(req?: any): Observable<EntityArrayResponseType> { query(req?: any): Observable<EntityArrayResponseType> {
const options = createRequestOption(req); const options = createRequestOption(req);
return this.http return this.http

View File

@ -1,165 +1,375 @@
<div class="row justify-content-center"> <div>
<div class="col-8"> <h2 id="page-heading" data-cy="EPreguntaCerradaHeading">
<form name="editForm" role="form" novalidate (ngSubmit)="save()" [formGroup]="editForm"> <div class="d-flex align-items-center">
<h2 id="jhi-plantilla-heading" data-cy="PlantillaCreateUpdateHeading" jhiTranslate="dataSurveyApp.plantilla.home.createOrEditLabel"> <p class="ds-title ds-contenteditable" contenteditable="true" spellcheck="false" (blur)="updateTemplateName($event)">
Create or edit a Plantilla {{ plantilla!.nombre }}
</h2> </p>
</div>
<div> <p class="ds-subtitle">Creada el día {{ plantilla!.fechaCreacion | formatShortDatetime | lowercase }}</p>
<jhi-alert-error></jhi-alert-error>
<div class="form-group" [hidden]="editForm.get('id')!.value == null"> <div class="d-flex justify-content-end">
<label class="form-control-label" jhiTranslate="global.field.id" for="field_id">ID</label> <button type="button" class="ds-btn ds-btn--secondary" (click)="previousState()">
<input type="number" class="form-control" name="id" id="field_id" data-cy="id" formControlName="id" [readonly]="true" /> <fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span jhiTranslate="entity.action.back">Back</span>
</div> </button>
<button type="button" class="ds-btn ds-btn--secondary" (click)="loadAll()" [disabled]="isLoading">
<fa-icon icon="sync" [spin]="isLoading"></fa-icon>&nbsp;&nbsp;<span>Refrescar preguntas</span>
</button>
<div class="form-group"> <button
<label class="form-control-label" jhiTranslate="dataSurveyApp.plantilla.nombre" for="field_nombre">Nombre</label> type="button"
<input type="text" class="form-control" name="nombre" id="field_nombre" data-cy="nombre" formControlName="nombre" /> class="ds-btn ds-btn--primary"
<div *ngIf="editForm.get('nombre')!.invalid && (editForm.get('nombre')!.dirty || editForm.get('nombre')!.touched)"> (click)="createQuestion()"
<small [disabled]="isLoading"
class="form-text text-danger" data-toggle="modal"
*ngIf="editForm.get('nombre')?.errors?.minlength" data-target="#crearPregunta"
jhiTranslate="entity.validation.minlength" >
[translateValues]="{ min: 1 }" <fa-icon icon="sync" [icon]="faPlus"></fa-icon>&nbsp;&nbsp;<span>Crear pregunta</span>
> </button>
This field is required to be at least 1 characters.
</small>
<small
class="form-text text-danger"
*ngIf="editForm.get('nombre')?.errors?.maxlength"
jhiTranslate="entity.validation.maxlength"
[translateValues]="{ max: 50 }"
>
This field cannot be longer than 50 characters.
</small>
</div>
</div>
<div class="form-group"> <button
<label class="form-control-label" jhiTranslate="dataSurveyApp.plantilla.descripcion" for="field_descripcion">Descripcion</label> type="button"
<input class="ds-btn ds-btn--primary"
type="text" (click)="publishTemplateToStore()"
class="form-control" [disabled]="isLoading"
name="descripcion" *ngIf="plantilla!.estado === 'DRAFT' && pPreguntas && pPreguntas.length > 0"
id="field_descripcion" >
data-cy="descripcion" <fa-icon icon="sync" [icon]="faStore"></fa-icon>&nbsp;&nbsp;<span>Publicar en tienda</span>
formControlName="descripcion" </button>
/>
</div>
<div class="form-group"> <button
<label class="form-control-label" jhiTranslate="dataSurveyApp.plantilla.fechaCreacion" for="field_fechaCreacion" type="button"
>Fecha Creacion</label class="ds-btn ds-btn--danger"
> (click)="deleteTemplateFromStore()"
<div class="d-flex"> [disabled]="isLoading"
<input *ngIf="plantilla!.estado === 'ACTIVE'"
id="field_fechaCreacion" >
data-cy="fechaCreacion" <fa-icon icon="sync" [icon]="faStore"></fa-icon>&nbsp;&nbsp;<span>Eliminar de tienda</span>
type="datetime-local" </button>
class="form-control" </div>
name="fechaCreacion" </h2>
formControlName="fechaCreacion"
placeholder="YYYY-MM-DD HH:mm" <jhi-alert-error></jhi-alert-error>
/>
</div> <!-- <jhi-alert></jhi-alert> -->
<!-- <div class="alert alert-warning" id="no-result" *ngIf="pPreguntas?.length === 0">
<span>No se encontraron preguntas</span>
</div> -->
<!-- *ngIf="pPreguntas && pPreguntas.length > 0" -->
<div class="ds-survey" id="entities">
<div class="ds-survey--all-question-wrapper">
<ng-container *ngIf="plantilla!.estado === 'ACTIVE'">
<p class="ds-title text-center">Plantilla en tienda</p>
<p class="ds-subtitle">No puede modificar la plantilla debido a que esta ya está en la tienda.</p>
</ng-container>
<ng-container *ngIf="plantilla!.estado === 'DRAFT' && pPreguntas && pPreguntas.length === 0">
<p class="ds-title text-center">Plantilla vacía</p>
<p class="ds-subtitle">Inicie creando preguntas y opciones para la plantilla.</p>
</ng-container>
<ng-container *ngIf="plantilla!.estado === 'DRAFT'">
<div class="ds-survey--question-wrapper" *ngFor="let pPregunta of pPreguntas; let i = index; trackBy: trackId">
<div <div
*ngIf=" [attr.data-index]="pPregunta.id"
editForm.get('fechaCreacion')!.invalid && (editForm.get('fechaCreacion')!.dirty || editForm.get('fechaCreacion')!.touched) [attr.data-tipo]="pPregunta.tipo"
" [attr.data-opcional]="pPregunta.opcional"
class="ds-survey--question"
> >
<small <div class="ds-survey--titulo">
class="form-text text-danger" <span class="ds-survey--titulo--name">
*ngIf="editForm.get('fechaCreacion')?.errors?.required" <span>{{ i + 1 }}.</span>&nbsp;
jhiTranslate="entity.validation.required" <span
> class="ds-contenteditable"
This field is required. [attr.data-id]="pPregunta.id"
</small> [attr.data-tipo]="pPregunta.tipo"
<small contenteditable="true"
class="form-text text-danger" spellcheck="false"
[hidden]="!editForm.get('fechaCreacion')?.errors?.ZonedDateTimelocal" (blur)="updateQuestionName($event)"
jhiTranslate="entity.validation.ZonedDateTimelocal" >{{ pPregunta.nombre }}</span
> >
This field should be a date and time. </span>
</small> <fa-icon
*ngIf="plantilla!.estado === 'DRAFT'"
class="ds-survey--titulo--icon"
[icon]="faTimes"
(click)="deleteQuestion($event)"
[attr.data-id]="pPregunta.id"
[attr.data-type]="pPregunta.tipo"
></fa-icon>
</div>
<div>
<span *ngIf="pPregunta.tipo === 'SINGLE'" class="ds-subtitle"
>Pregunta de respuesta {{ 'dataSurveyApp.PreguntaCerradaTipo.SINGLE' | translate | lowercase }}
{{ pPregunta.opcional ? '(opcional)' : '' }}</span
>
<span *ngIf="pPregunta.tipo === 'MULTIPLE'" class="ds-subtitle"
>Pregunta de respuesta {{ 'dataSurveyApp.PreguntaCerradaTipo.MULTIPLE' | translate | lowercase }}
{{ pPregunta.opcional ? '(opcional)' : '' }}</span
>
<span *ngIf="!pPregunta.tipo" class="ds-subtitle"
>Pregunta de respuesta abierta {{ pPregunta.opcional ? '(opcional)' : '' }}</span
>
</div>
<ng-container *ngIf="pPregunta.tipo">
<ng-container *ngFor="let pPreguntaOpcion of pPreguntasOpciones; let j = index; trackBy: trackId">
<ng-container *ngFor="let pPreguntaOpcionFinal of pPreguntaOpcion">
<ng-container *ngIf="pPregunta.id === pPreguntaOpcionFinal.ppreguntaCerrada.id">
<div
class="ds-survey--option ds-survey--option--base ds-survey--closed-option can-delete"
[attr.data-id]="pPreguntaOpcionFinal.id"
>
<!-- <input class="ds-survey--checkbox" id="{{ pPregunta.id }}-{{ pPreguntaOpcionFinal.id }}" type="checkbox" disabled /> -->
<label for="{{ pPregunta.id }}-{{ pPreguntaOpcionFinal.id }}">{{ pPreguntaOpcionFinal.nombre }}</label>
<fa-icon
*ngIf="plantilla!.estado === 'DRAFT'"
class="ds-survey--titulo--icon ds-survey--titulo--icon--small"
[icon]="faTimes"
(click)="deleteOption($event)"
[attr.data-optionid]="pPreguntaOpcionFinal.id"
></fa-icon>
</div>
</ng-container>
</ng-container>
</ng-container>
<div
class="ds-survey--option ds-survey--option--add ds-survey--closed-option"
(click)="resetForm($event)"
data-toggle="modal"
data-target="#crearOpcion"
[attr.data-id]="pPregunta.id"
>
<fa-icon
class="ds-survey--add-option--icon"
[icon]="faPlus"
[attr.data-id]="pPregunta.id"
[attr.data-type]="pPregunta.tipo"
></fa-icon>
<span class="ds-survey--add-option">Añadir opción</span>
</div>
</ng-container>
<div class="ds-survey--option ds-survey--option--base ds-survey--open-option" *ngIf="!pPregunta.tipo">
<textarea name="" id="" cols="30" rows="10" disabled></textarea>
</div>
</div> </div>
</div> </div>
</ng-container>
<div class="form-group"> </div>
<label class="form-control-label" jhiTranslate="dataSurveyApp.plantilla.fechaPublicacionTienda" for="field_fechaPublicacionTienda" </div>
>Fecha Publicacion Tienda</label </div>
>
<div class="d-flex"> <!-- Create Option Modal -->
<input <div class="modal fade ds-modal" id="crearOpcion" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
id="field_fechaPublicacionTienda" <div class="modal-dialog modal-dialog-centered" role="document">
data-cy="fechaPublicacionTienda" <div class="modal-content">
type="datetime-local" <form autocomplete="off" class="ds-form" name="editForm" role="form" novalidate (ngSubmit)="save()" [formGroup]="editForm">
class="form-control" <div class="modal-header">
name="fechaPublicacionTienda" <h1 class="modal-title" id="exampleModalLongTitle">Crear Opción</h1>
formControlName="fechaPublicacionTienda" </div>
placeholder="YYYY-MM-DD HH:mm" <div class="modal-body">
/> <!-- Survey Closed Question Create Option Modal -->
</div> <div>
</div> <jhi-alert-error></jhi-alert-error>
<div class="form-group"> <div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.plantilla.estado" for="field_estado">Estado</label> <label class="form-control-label" jhiTranslate="dataSurveyApp.pPreguntaCerradaOpcion.nombre" for="field_nombre">Nombre</label>
<select class="form-control" name="estado" formControlName="estado" id="field_estado" data-cy="estado"> <input type="text" class="form-control" name="nombre" id="field_nombre" data-cy="nombre" formControlName="nombre" />
<option [ngValue]="null">{{ 'dataSurveyApp.EstadoPlantilla.null' | translate }}</option> <div *ngIf="editForm.get('nombre')!.invalid && (editForm.get('nombre')!.dirty || editForm.get('nombre')!.touched)">
<option value="DRAFT">{{ 'dataSurveyApp.EstadoPlantilla.DRAFT' | translate }}</option> <small
<option value="ACTIVE">{{ 'dataSurveyApp.EstadoPlantilla.ACTIVE' | translate }}</option> class="form-text text-danger"
<option value="DELETED">{{ 'dataSurveyApp.EstadoPlantilla.DELETED' | translate }}</option> *ngIf="editForm.get('nombre')?.errors?.required"
<option value="DISABLED">{{ 'dataSurveyApp.EstadoPlantilla.DISABLED' | translate }}</option> jhiTranslate="entity.validation.required"
</select> >
<div *ngIf="editForm.get('estado')!.invalid && (editForm.get('estado')!.dirty || editForm.get('estado')!.touched)"> This field is required.
<small class="form-text text-danger" *ngIf="editForm.get('estado')?.errors?.required" jhiTranslate="entity.validation.required"> </small>
This field is required. <small
</small> class="form-text text-danger"
</div> *ngIf="editForm.get('nombre')?.errors?.minlength"
</div> jhiTranslate="entity.validation.minlength"
[translateValues]="{ min: 1 }"
<div class="form-group"> >
<label class="form-control-label" jhiTranslate="dataSurveyApp.plantilla.precio" for="field_precio">Precio</label> This field is required to be at least 1 characters.
<input type="number" class="form-control" name="precio" id="field_precio" data-cy="precio" formControlName="precio" /> </small>
<div *ngIf="editForm.get('precio')!.invalid && (editForm.get('precio')!.dirty || editForm.get('precio')!.touched)"> <small
<small class="form-text text-danger" *ngIf="editForm.get('precio')?.errors?.required" jhiTranslate="entity.validation.required"> class="form-text text-danger"
This field is required. *ngIf="editForm.get('nombre')?.errors?.maxlength"
</small> jhiTranslate="entity.validation.maxlength"
<small class="form-text text-danger" [hidden]="!editForm.get('precio')?.errors?.number" jhiTranslate="entity.validation.number"> [translateValues]="{ max: 500 }"
This field should be a number. >
</small> This field cannot be longer than 500 characters.
</div> </small>
</div> </div>
</div>
<div class="form-group"> </div>
<label class="form-control-label" jhiTranslate="dataSurveyApp.plantilla.categoria" for="field_categoria">Categoria</label> </div>
<select class="form-control" id="field_categoria" data-cy="categoria" name="categoria" formControlName="categoria"> <div class="modal-footer">
<option [ngValue]="null"></option> <input id="createAnother" type="checkbox" (change)="createAnotherChange($event)" />
<option <label for="createAnother">Crear otra</label>
[ngValue]="categoriaOption.id === editForm.get('categoria')!.value?.id ? editForm.get('categoria')!.value : categoriaOption" <button id="cancelBtn" type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal">
*ngFor="let categoriaOption of categoriasSharedCollection; trackBy: trackCategoriaById" <fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
> </button>
{{ categoriaOption.nombre }} <button
</option> type="submit"
</select> id="save-entity"
</div> data-cy="entityCreateSaveButton"
</div> class="ds-btn ds-btn--primary"
[disabled]="editForm.invalid || isSaving"
<div> >
<button type="button" id="cancel-save" data-cy="entityCreateCancelButton" class="btn btn-secondary" (click)="previousState()"> <span jhiTranslate="entity.action.create">Create</span>
<fa-icon icon="ban"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span> </button>
</button> </div>
</form>
<button </div>
type="submit" </div>
id="save-entity" </div>
data-cy="entityCreateSaveButton"
[disabled]="editForm.invalid || isSaving" <!-- ------------------------------------------------------------------------------------------------- -->
class="btn btn-primary"
> <!-- Create Question Modal -->
<fa-icon icon="save"></fa-icon>&nbsp;<span jhiTranslate="entity.action.save">Save</span> <div
</button> class="modal fade ds-modal"
</div> id="crearPregunta"
</form> tabindex="-1"
role="dialog"
aria-labelledby="exampleModalCenterTitle"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<form
autocomplete="off"
class="ds-form"
name="editFormQuestion"
role="form"
novalidate
(ngSubmit)="saveQuestion()"
[formGroup]="editFormQuestion"
>
<div class="modal-header">
<h1 class="modal-title" id="exampleModalLongTitle1">Crear Pregunta</h1>
</div>
<div class="modal-body">
<!-- Survey Create Question Modal -->
<div>
<jhi-alert-error></jhi-alert-error>
<div class="form-group">
<label class="form-control-label" for="field_nombre">Pregunta</label>
<input type="text" class="form-control" name="nombre" id="field_nombre2" data-cy="nombre" formControlName="nombre" />
<div
*ngIf="
editFormQuestion.get('nombre')!.invalid &&
(editFormQuestion.get('nombre')!.dirty || editFormQuestion.get('nombre')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="editFormQuestion.get('nombre')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
<small
class="form-text text-danger"
*ngIf="editFormQuestion.get('nombre')?.errors?.minlength"
jhiTranslate="entity.validation.minlength"
[translateValues]="{ min: 1 }"
>
This field is required to be at least 1 characters.
</small>
<small
class="form-text text-danger"
*ngIf="editFormQuestion.get('nombre')?.errors?.maxlength"
jhiTranslate="entity.validation.maxlength"
[translateValues]="{ max: 500 }"
>
This field cannot be longer than 500 characters.
</small>
</div>
</div>
<!-- Custom Form Group (Closed & Open Question Validation) -->
<div class="form-group">
<label class="form-control-label" for="field_tipo">Tipo de pregunta</label>
<select class="form-control" name="tipopregunta" formControlName="tipopregunta" id="field_tipo2" data-cy="tipopregunta">
<option selected value="CLOSED">Opción multiple</option>
<option value="OPEN">Respuesta abierta</option>
</select>
<div
*ngIf="
editFormQuestion.get('tipopregunta')!.invalid &&
(editFormQuestion.get('tipopregunta')!.dirty || editFormQuestion.get('tipopregunta')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="editFormQuestion.get('tipopregunta')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
<ng-container *ngIf="editFormQuestion.get('tipopregunta')!.value === 'CLOSED'">
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.ePreguntaCerrada.tiporespuesta" for="field_tipo">Tipo</label>
<select class="form-control" name="tipo" formControlName="tipo" id="field_tipo" data-cy="tipo">
<option selected value="SINGLE">{{ 'dataSurveyApp.PreguntaCerradaTipo.SINGLE' | translate }}</option>
<option value="MULTIPLE">{{ 'dataSurveyApp.PreguntaCerradaTipo.MULTIPLE' | translate }}</option>
</select>
<div
*ngIf="
editFormQuestion.get('tipo')!.invalid && (editFormQuestion.get('tipo')!.dirty || editFormQuestion.get('tipo')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="editFormQuestion.get('tipo')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
</ng-container>
<div class="form-group">
<label class="form-control-label" for="field_opcional">Opcional</label>
<input type="checkbox" class="form-check" name="opcional" id="field_opcional" data-cy="opcional" formControlName="opcional" />
<div
*ngIf="
editFormQuestion.get('opcional')!.invalid &&
(editFormQuestion.get('opcional')!.dirty || editFormQuestion.get('opcional')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="editFormQuestion.get('opcional')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input id="createAnotherQuestion" type="checkbox" (change)="createAnotherQuestionChange($event)" />
<label for="createAnotherQuestion">Crear otra</label>
<button id="cancelBtnQuestion" type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button
type="submit"
id="save-question"
data-cy="entityCreateSaveButton"
class="ds-btn ds-btn--primary"
[disabled]="editFormQuestion.invalid || isSaving"
>
<span jhiTranslate="entity.action.create">Create</span>
</button>
</div>
</form>
</div>
</div> </div>
</div> </div>

View File

@ -1,4 +1,9 @@
import { Component, OnInit } from '@angular/core'; import { PPreguntaAbierta, IPPreguntaAbierta } from './../../p-pregunta-abierta/p-pregunta-abierta.model';
import { PPreguntaCerrada } from './../../p-pregunta-cerrada/p-pregunta-cerrada.model';
import { PPreguntaCerradaOpcion, IPPreguntaCerradaOpcion } from './../../p-pregunta-cerrada-opcion/p-pregunta-cerrada-opcion.model';
import { PPreguntaAbiertaService } from './../../p-pregunta-abierta/service/p-pregunta-abierta.service';
import { PPreguntaCerradaOpcionService } from './../../p-pregunta-cerrada-opcion/service/p-pregunta-cerrada-opcion.service';
import { AfterViewChecked, Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http'; import { HttpResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms'; import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router'; import { ActivatedRoute } from '@angular/router';
@ -12,67 +17,262 @@ import { IPlantilla, Plantilla } from '../plantilla.model';
import { PlantillaService } from '../service/plantilla.service'; import { PlantillaService } from '../service/plantilla.service';
import { ICategoria } from 'app/entities/categoria/categoria.model'; import { ICategoria } from 'app/entities/categoria/categoria.model';
import { CategoriaService } from 'app/entities/categoria/service/categoria.service'; import { CategoriaService } from 'app/entities/categoria/service/categoria.service';
import { IUsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model';
import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { IPPreguntaCerrada } from 'app/entities/p-pregunta-cerrada/p-pregunta-cerrada.model';
import { PPreguntaCerradaService } from 'app/entities/p-pregunta-cerrada/service/p-pregunta-cerrada.service';
import { PPreguntaCerradaDeleteDialogComponent } from 'app/entities/p-pregunta-cerrada/delete/p-pregunta-cerrada-delete-dialog.component';
import { faTimes, faPlus, faQuestion, faPollH, faEye, faStore } from '@fortawesome/free-solid-svg-icons';
import { PreguntaCerradaTipo } from 'app/entities/enumerations/pregunta-cerrada-tipo.model';
import { PlantillaDeleteQuestionDialogComponent } from '../plantilla-delete-question-dialog/plantilla-delete-question-dialog.component';
import { PlantillaDeleteOptionDialogComponent } from '../plantilla-delete-option-dialog/plantilla-delete-option-dialog.component';
import { ParametroAplicacionService } from './../../parametro-aplicacion/service/parametro-aplicacion.service';
import { IParametroAplicacion } from './../../parametro-aplicacion/parametro-aplicacion.model';
import { Router } from '@angular/router';
import { EstadoPlantilla } from 'app/entities/enumerations/estado-plantilla.model';
import { PlantillaDeleteStoreDialogComponent } from '../plantilla-delete-store-dialog/plantilla-delete-store-dialog.component';
import { PlantillaPublishStoreDialogComponent } from '../plantilla-publish-store-dialog/plantilla-publish-store-dialog.component';
@Component({ @Component({
selector: 'jhi-plantilla-update', selector: 'jhi-plantilla-update',
templateUrl: './plantilla-update.component.html', templateUrl: './plantilla-update.component.html',
}) })
export class PlantillaUpdateComponent implements OnInit { export class PlantillaUpdateComponent implements OnInit, AfterViewChecked {
faTimes = faTimes;
faPlus = faPlus;
faPollH = faPollH;
faQuestion = faQuestion;
faEye = faEye;
faStore = faStore;
isSaving = false; isSaving = false;
isSavingQuestion = false;
categoriasSharedCollection: ICategoria[] = []; categoriasSharedCollection: ICategoria[] = [];
usuarioExtrasSharedCollection: IUsuarioExtra[] = [];
editForm = this.fb.group({ editForm = this.fb.group({
id: [], id: [],
nombre: [null, [Validators.minLength(1), Validators.maxLength(50)]], nombre: [null, [Validators.required, Validators.minLength(1), Validators.maxLength(500)]],
descripcion: [],
fechaCreacion: [null, [Validators.required]],
fechaPublicacionTienda: [],
estado: [null, [Validators.required]],
precio: [null, [Validators.required]],
categoria: [],
}); });
editFormQuestion = this.fb.group({
id: [],
nombre: [null, [Validators.required, Validators.minLength(1), Validators.maxLength(500)]],
tipo: [PreguntaCerradaTipo.SINGLE],
opcional: [false],
tipopregunta: ['CLOSED'],
});
pPreguntas?: any[];
pPreguntasOpciones?: any[];
plantilla: Plantilla | null = null;
parametrosAplicacion?: IParametroAplicacion | null = null;
isLoading = false;
createAnother: Boolean = false;
createAnotherQuestion: Boolean = false;
selectedQuestionToCreateOption: IPPreguntaCerrada | null = null;
constructor( constructor(
protected plantillaService: PlantillaService, protected plantillaService: PlantillaService,
protected categoriaService: CategoriaService, protected categoriaService: CategoriaService,
protected usuarioExtraService: UsuarioExtraService,
protected activatedRoute: ActivatedRoute, protected activatedRoute: ActivatedRoute,
protected fb: FormBuilder protected fb: FormBuilder,
protected modalService: NgbModal,
protected pPreguntaCerradaService: PPreguntaCerradaService,
protected pPreguntaCerradaOpcionService: PPreguntaCerradaOpcionService,
protected parametroAplicacionService: ParametroAplicacionService,
protected pPreguntaAbiertaService: PPreguntaAbiertaService,
protected router: Router
) {} ) {}
loadAll(): void {
this.isLoading = true;
this.plantillaService.findQuestions(this.plantilla?.id!).subscribe(
(res: any) => {
this.isLoading = false;
this.pPreguntas = res.body ?? [];
},
() => {
this.isLoading = false;
}
);
this.plantillaService.findQuestionsOptions(this.plantilla?.id!).subscribe(
(res: any) => {
this.isLoading = false;
this.pPreguntasOpciones = res.body ?? [];
},
() => {
this.isLoading = false;
}
);
}
async loadAplicationParameters(): Promise<void> {
const params = await this.parametroAplicacionService.find(1).toPromise();
this.parametrosAplicacion = params.body;
}
ngOnInit(): void { ngOnInit(): void {
this.activatedRoute.data.subscribe(({ plantilla }) => { this.activatedRoute.data.subscribe(({ plantilla }) => {
if (plantilla.id === undefined) { if (plantilla.id === undefined) {
const today = dayjs().startOf('day'); const today = dayjs().startOf('day');
plantilla.fechaCreacion = today; plantilla.fechaCreacion = today;
plantilla.fechaPublicacionTienda = today; plantilla.fechaPublicacion = today;
plantilla.fechaFinalizar = today;
plantilla.fechaFinalizada = today;
} else {
this.plantilla = plantilla;
this.loadAll();
this.loadAplicationParameters();
} }
this.updateForm(plantilla); // this.updateForm(plantilla);
this.loadRelationshipsOptions(); // this.loadRelationshipsOptions();
}); });
} }
ngAfterViewChecked(): void {
// this.initListeners();
}
trackId(index: number, item: IPPreguntaCerrada): number {
return item.id!;
}
delete(pPreguntaCerrada: IPPreguntaCerrada): void {
const modalRef = this.modalService.open(PPreguntaCerradaDeleteDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.componentInstance.pPreguntaCerrada = pPreguntaCerrada;
// unsubscribe not needed because closed completes on modal close
modalRef.closed.subscribe(reason => {
if (reason === 'deleted') {
this.loadAll();
}
});
}
// initListeners(): void {
// const checkboxes = document.getElementsByClassName('ds-survey--checkbox');
// for (let i = 0; i < checkboxes.length; i++) {
// checkboxes[i].addEventListener('click', e => {
// if ((e.target as HTMLInputElement).checked) {
// (e.target as HTMLElement).offsetParent!.classList.add('ds-survey--closed-option--active');
// } else {
// (e.target as HTMLElement).offsetParent!.classList.remove('ds-survey--closed-option--active');
// }
// });
// }
// }
previousState(): void { previousState(): void {
window.history.back(); window.history.back();
} }
save(): void { publishSurvey(): void {}
this.isSaving = true;
const plantilla = this.createFromForm(); finishSurvey(): void {}
if (plantilla.id !== undefined) {
this.subscribeToSaveResponse(this.plantillaService.update(plantilla)); addOption(event: any): void {}
} else {
this.subscribeToSaveResponse(this.plantillaService.create(plantilla)); openPreview() {
const surveyId = this.plantilla?.id;
this.router.navigate(['/plantilla', surveyId, 'preview']);
}
resetForm(event: any): void {
this.editForm.reset();
if (event !== null) {
const id = event.target.dataset.id;
this.pPreguntaCerradaService.find(id).subscribe(e => {
this.selectedQuestionToCreateOption = e.body;
});
} }
} }
trackCategoriaById(index: number, item: ICategoria): number { deleteQuestion(event: any) {
const modalRef = this.modalService.open(PlantillaDeleteQuestionDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.closed.subscribe(reason => {
if (reason === 'confirm') {
const id = event.target.dataset.id;
if (event.target.dataset.type) {
// Delete closed question
const questionElement = (event.target as HTMLElement).parentElement?.parentElement;
const optionIdsToDelete: number[] = [];
// Get options IDs
questionElement?.childNodes.forEach((e, i) => {
if (e.nodeName !== 'DIV') return;
if (i === 0) return;
if ((e as HTMLElement).dataset.id === undefined) return;
if (!(e as HTMLElement).classList.contains('can-delete')) return;
let optionId = (e as HTMLElement).dataset.id;
optionIdsToDelete.push(+optionId!);
});
if (optionIdsToDelete.length === 0) {
this.pPreguntaCerradaService.delete(id).subscribe(e => {
this.loadAll();
});
} else {
// Delete question options
this.pPreguntaCerradaOpcionService.deleteMany(optionIdsToDelete).subscribe(e => {
// Delete question
this.pPreguntaCerradaService.delete(id).subscribe(e => {
this.loadAll();
});
});
}
} else {
// Delete open question
this.pPreguntaAbiertaService.delete(id).subscribe(e => {
this.loadAll();
});
}
}
});
}
deleteOption(event: any): void {
const modalRef = this.modalService.open(PlantillaDeleteOptionDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.closed.subscribe(reason => {
if (reason === 'confirm') {
const id = event.target.dataset.optionid;
this.pPreguntaCerradaOpcionService.delete(id).subscribe(e => {
this.pPreguntas = [];
this.pPreguntasOpciones = [];
this.loadAll();
});
}
});
}
save(): void {
this.isSaving = true;
const pPreguntaCerradaOpcion = this.createFromForm();
if (pPreguntaCerradaOpcion.id !== undefined) {
this.subscribeToSaveResponse(this.pPreguntaCerradaOpcionService.update(pPreguntaCerradaOpcion));
} else {
this.subscribeToSaveResponse(
this.pPreguntaCerradaOpcionService.create(pPreguntaCerradaOpcion, this.selectedQuestionToCreateOption?.id!)
);
}
}
trackPPreguntaCerradaById(index: number, item: IPPreguntaCerrada): number {
return item.id!; return item.id!;
} }
protected subscribeToSaveResponse(result: Observable<HttpResponse<IPlantilla>>): void { protected subscribeToSaveResponse(result: Observable<HttpResponse<IPPreguntaCerradaOpcion>>): void {
result.pipe(finalize(() => this.onSaveFinalize())).subscribe( result.pipe(finalize(() => this.onSaveFinalize())).subscribe(
() => this.onSaveSuccess(), () => this.onSaveSuccess(),
() => this.onSaveError() () => this.onSaveError()
@ -80,7 +280,14 @@ export class PlantillaUpdateComponent implements OnInit {
} }
protected onSaveSuccess(): void { protected onSaveSuccess(): void {
this.previousState(); // this.previousState();
this.resetForm(null);
this.pPreguntas = [];
this.pPreguntasOpciones = [];
this.loadAll();
if (!this.createAnother) {
$('#cancelBtn').click();
}
} }
protected onSaveError(): void { protected onSaveError(): void {
@ -91,51 +298,179 @@ export class PlantillaUpdateComponent implements OnInit {
this.isSaving = false; this.isSaving = false;
} }
protected updateForm(plantilla: IPlantilla): void { protected createFromForm(): IPPreguntaCerradaOpcion {
this.editForm.patchValue({ return {
id: plantilla.id, ...new PPreguntaCerradaOpcion(),
nombre: plantilla.nombre, id: undefined,
descripcion: plantilla.descripcion, nombre: this.editForm.get(['nombre'])!.value,
fechaCreacion: plantilla.fechaCreacion ? plantilla.fechaCreacion.format(DATE_TIME_FORMAT) : null, orden: 10,
fechaPublicacionTienda: plantilla.fechaPublicacionTienda ? plantilla.fechaPublicacionTienda.format(DATE_TIME_FORMAT) : null, pPreguntaCerrada: this.selectedQuestionToCreateOption,
estado: plantilla.estado, };
precio: plantilla.precio, }
categoria: plantilla.categoria,
});
this.categoriasSharedCollection = this.categoriaService.addCategoriaToCollectionIfMissing( createAnotherChange(event: any) {
this.categoriasSharedCollection, this.createAnother = event.target.checked;
plantilla.categoria }
createQuestion(): void {
const surveyId = this.plantilla?.id;
}
protected createFromFormClosedQuestion(): IPPreguntaCerrada {
return {
// ...new PPreguntaCerrada(),
id: undefined,
nombre: this.editFormQuestion.get(['nombre'])!.value,
tipo: this.editFormQuestion.get(['tipo'])!.value,
opcional: this.editFormQuestion.get(['opcional'])!.value,
orden: 10,
plantilla: this.plantilla,
};
}
protected createFromFormOpenQuestion(): IPPreguntaAbierta {
return {
// ...new PPreguntaAbierta(),
id: undefined,
nombre: this.editFormQuestion.get(['nombre'])!.value,
opcional: this.editFormQuestion.get(['opcional'])!.value,
orden: 10,
plantilla: this.plantilla,
};
}
createAnotherQuestionChange(event: any) {
this.createAnotherQuestion = event.target.checked;
}
saveQuestion(): void {
this.isSavingQuestion = true;
const tipoPregunta = this.editFormQuestion.get(['tipopregunta'])!.value;
if (tipoPregunta === 'CLOSED') {
const pPreguntaCerrada = this.createFromFormClosedQuestion();
if (pPreguntaCerrada.id !== undefined) {
this.subscribeToSaveResponseQuestionClosed(this.pPreguntaCerradaService.update(pPreguntaCerrada));
} else {
this.subscribeToSaveResponseQuestionClosed(this.pPreguntaCerradaService.create(pPreguntaCerrada));
}
} else if (tipoPregunta === 'OPEN') {
const pPreguntaAbierta = this.createFromFormOpenQuestion();
if (pPreguntaAbierta.id !== undefined) {
this.subscribeToSaveResponseQuestionOpen(this.pPreguntaAbiertaService.update(pPreguntaAbierta));
} else {
this.subscribeToSaveResponseQuestionOpen(this.pPreguntaAbiertaService.create(pPreguntaAbierta));
}
}
}
protected subscribeToSaveResponseQuestionClosed(result: Observable<HttpResponse<IPPreguntaCerrada>>): void {
result.pipe(finalize(() => this.onSaveFinalizeQuestion())).subscribe(
() => this.onSaveSuccessQuestion(),
() => this.onSaveErrorQuestion()
); );
} }
protected loadRelationshipsOptions(): void { protected subscribeToSaveResponseQuestionOpen(result: Observable<HttpResponse<IPPreguntaAbierta>>): void {
this.categoriaService result.pipe(finalize(() => this.onSaveFinalizeQuestion())).subscribe(
.query() () => this.onSaveSuccessQuestion(),
.pipe(map((res: HttpResponse<ICategoria[]>) => res.body ?? [])) () => this.onSaveErrorQuestion()
.pipe( );
map((categorias: ICategoria[]) =>
this.categoriaService.addCategoriaToCollectionIfMissing(categorias, this.editForm.get('categoria')!.value)
)
)
.subscribe((categorias: ICategoria[]) => (this.categoriasSharedCollection = categorias));
} }
protected createFromForm(): IPlantilla { protected onSaveSuccessQuestion(): void {
return { this.editFormQuestion.reset({ tipo: PreguntaCerradaTipo.SINGLE, tipopregunta: 'CLOSED', opcional: false });
...new Plantilla(), this.editForm.reset();
id: this.editForm.get(['id'])!.value, this.pPreguntas = [];
nombre: this.editForm.get(['nombre'])!.value, this.pPreguntasOpciones = [];
descripcion: this.editForm.get(['descripcion'])!.value, this.loadAll();
fechaCreacion: this.editForm.get(['fechaCreacion'])!.value if (!this.createAnotherQuestion) {
? dayjs(this.editForm.get(['fechaCreacion'])!.value, DATE_TIME_FORMAT) $('#cancelBtnQuestion').click();
: undefined, }
fechaPublicacionTienda: this.editForm.get(['fechaPublicacionTienda'])!.value }
? dayjs(this.editForm.get(['fechaPublicacionTienda'])!.value, DATE_TIME_FORMAT)
: undefined, protected onSaveErrorQuestion(): void {
estado: this.editForm.get(['estado'])!.value, // Api for inheritance.
precio: this.editForm.get(['precio'])!.value, }
categoria: this.editForm.get(['categoria'])!.value,
}; protected onSaveFinalizeQuestion(): void {
this.isSavingQuestion = false;
}
updateTemplateName(event: any) {
const updatedSurveyName = event.target.innerText;
if (updatedSurveyName !== this.plantilla?.nombre) {
const survey = { ...this.plantilla };
survey.nombre = updatedSurveyName;
this.plantillaService.update(survey).subscribe(res => {});
}
}
updateQuestionName(event: any): void {
const questionType = event.target.dataset.tipo;
const questionId = event.target.dataset.id;
const questionName = event.target.innerText;
if (questionType) {
// Closed question
this.pPreguntaCerradaService.find(questionId).subscribe(res => {
const pPreguntaCerrada: PPreguntaCerrada | null = res.body ?? null;
const updatedPPreguntaCerrada = { ...pPreguntaCerrada };
if (questionName !== pPreguntaCerrada?.nombre && pPreguntaCerrada !== null) {
updatedPPreguntaCerrada.nombre = questionName;
this.pPreguntaCerradaService.update(updatedPPreguntaCerrada).subscribe(updatedQuestion => {
console.log(updatedQuestion);
});
}
});
} else {
// Open question
// Closed question
this.pPreguntaAbiertaService.find(questionId).subscribe(res => {
const pPreguntaAbierta: PPreguntaAbierta | null = res.body ?? null;
const updatedPPreguntaAbierta = { ...pPreguntaAbierta };
if (questionName !== pPreguntaAbierta?.nombre && pPreguntaAbierta !== null) {
updatedPPreguntaAbierta.nombre = questionName;
this.pPreguntaAbiertaService.update(updatedPPreguntaAbierta).subscribe(updatedQuestion => {
console.log(updatedQuestion);
});
}
});
}
// const questionId = event.target.dataset.id;
// const survey = { ...this.plantilla };
// survey.nombre = updatedQuestionName;
// // Prevent user update by setting to null
// survey.usuarioExtra!.user = null;
// this.plantillaService.updateSurvey(survey).subscribe(res => {});
}
trackCategoriaById(index: number, item: ICategoria): number {
return item.id!;
}
trackUsuarioExtraById(index: number, item: IUsuarioExtra): number {
return item.id!;
}
publishTemplateToStore(): void {
const modalRef = this.modalService.open(PlantillaPublishStoreDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.closed.subscribe(reason => {
if (reason === 'confirm') {
this.plantilla!.estado = EstadoPlantilla.ACTIVE;
this.plantillaService.update(this.plantilla!).subscribe(res => {});
}
});
}
deleteTemplateFromStore(): void {
const modalRef = this.modalService.open(PlantillaDeleteStoreDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.closed.subscribe(reason => {
if (reason === 'confirm') {
this.plantilla!.estado = EstadoPlantilla.DRAFT;
this.plantillaService.update(this.plantilla!).subscribe(res => {});
}
});
} }
} }

View File

@ -22,6 +22,10 @@ export class UserService {
return this.http.get<IUser[]>(this.resourceUrl, { params: options, observe: 'response' }); return this.http.get<IUser[]>(this.resourceUrl, { params: options, observe: 'response' });
} }
retrieveAllPublicUsers(): Observable<IUser[]> {
return this.http.get<IUser[]>(this.resourceUrl);
}
addUserToCollectionIfMissing(userCollection: IUser[], ...usersToCheck: (IUser | null | undefined)[]): IUser[] { addUserToCollectionIfMissing(userCollection: IUser[], ...usersToCheck: (IUser | null | undefined)[]): IUser[] {
const users: IUser[] = usersToCheck.filter(isPresent); const users: IUser[] = usersToCheck.filter(isPresent);
if (users.length > 0) { if (users.length > 0) {

View File

@ -1,16 +1,10 @@
<form *ngIf="usuarioEncuesta" name="deleteForm" (ngSubmit)="confirmDelete(usuarioEncuesta.id!)"> <form class="ds-form" *ngIf="usuarioEncuesta" name="deleteForm" (ngSubmit)="confirmDelete(usuarioEncuesta.id!)">
<div class="modal-header">
<h4 class="modal-title" data-cy="usuarioEncuestaDeleteDialogHeading" jhiTranslate="entity.delete.title">Confirm delete operation</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click)="cancel()">&times;</button>
</div>
<div class="modal-body"> <div class="modal-body">
<jhi-alert-error></jhi-alert-error> <p class="ds-title--small">Salir de colaboración</p>
<p <p
class="ds-subtitle"
id="jhi-delete-usuarioEncuesta-heading" id="jhi-delete-usuarioEncuesta-heading"
jhiTranslate="dataSurveyApp.usuarioEncuesta.delete.question" jhiTranslate="dataSurveyApp.usuarioEncuesta.delete.questionGetOut"
[translateValues]="{ id: usuarioEncuesta.id }" [translateValues]="{ id: usuarioEncuesta.id }"
> >
Are you sure you want to delete this Usuario Encuesta? Are you sure you want to delete this Usuario Encuesta?
@ -18,12 +12,12 @@
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" (click)="cancel()"> <button type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal" (click)="cancel()">
<fa-icon icon="ban"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span> <fa-icon icon="arrow-left"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button> </button>
<button id="jhi-confirm-delete-usuarioEncuesta" data-cy="entityConfirmDeleteButton" type="submit" class="btn btn-danger"> <button id="jhi-confirm-delete-usuarioEncuesta" data-cy="entityConfirmDeleteButton" type="submit" class="btn btn-danger">
<fa-icon icon="times"></fa-icon>&nbsp;<span jhiTranslate="entity.action.delete">Delete</span> <fa-icon icon="sign-out-alt"></fa-icon>&nbsp;<span jhiTranslate="dataSurveyApp.usuarioEncuesta.delete.getOut">Get Out</span>
</button> </button>
</div> </div>
</form> </form>

View File

@ -1,29 +1,38 @@
<div> <div>
<h2 id="page-heading" data-cy="UsuarioEncuestaHeading"> <h2 id="page-heading" data-cy="UsuarioEncuestaHeading">
<span jhiTranslate="dataSurveyApp.usuarioEncuesta.home.title">Usuario Encuestas</span> <span class="ds-title" jhiTranslate="dataSurveyApp.usuarioEncuesta.home.title">Colaboraciones </span>
<p class="ds-subtitle">Gestione las colaboraciones en encuestas a las que se encuentra agregado</p>
<div class="d-flex justify-content-end"> <div class="d-flex justify-content-end">
<button class="btn btn-info mr-2" (click)="loadAll()" [disabled]="isLoading"> <button class="ds-btn ds-btn--secondary mr-2" (click)="loadAll()" [disabled]="isLoading">
<fa-icon icon="sync" [spin]="isLoading"></fa-icon> <fa-icon icon="sync" [spin]="isLoading"></fa-icon>
<span jhiTranslate="dataSurveyApp.usuarioEncuesta.home.refreshListLabel">Refresh List</span> <span jhiTranslate="dataSurveyApp.usuarioEncuesta.home.refreshListLabel">Refresh List</span>
</button> </button>
<button
id="jh-create-entity"
data-cy="entityCreateButton"
class="btn btn-primary jh-create-entity create-usuario-encuesta"
[routerLink]="['/usuario-encuesta/new']"
>
<fa-icon icon="plus"></fa-icon>
<span jhiTranslate="dataSurveyApp.usuarioEncuesta.home.createLabel"> Create a new Usuario Encuesta </span>
</button>
</div> </div>
</h2> </h2>
<jhi-alert-error></jhi-alert-error> <jhi-alert-error></jhi-alert-error>
<jhi-alert></jhi-alert> <jhi-alert></jhi-alert>
<form class="ds-form">
<div class="input-group">
<div class="ds-filter">
<div class="input-group-addon"><i class="glyphicon glyphicon-search"></i></div>
<select name="searchRol" id="searchRol" [(ngModel)]="searchRol" style="width: 200px">
<option value="" selected="selected" disabled="disabled">Filtrar por rol</option>
<option value="">Todos los roles</option>
<option value="Read">Lector</option>
<option value="Write">Escritor</option>
</select>
<select name="searchRol" id="searchEstado" [(ngModel)]="searchEstado" style="width: 200px">
<option value="" selected="selected" disabled="disabled">Filtrar por estado</option>
<option value="">Todos los estados</option>
<option value="ACTIVE">Activos</option>
<option value="PENDING">Pendientes</option>
</select>
</div>
</div>
</form>
<div class="alert alert-warning" id="no-result" *ngIf="usuarioEncuestas?.length === 0"> <div class="alert alert-warning" id="no-result" *ngIf="usuarioEncuestas?.length === 0">
<span jhiTranslate="dataSurveyApp.usuarioEncuesta.home.notFound">No usuarioEncuestas found</span> <span jhiTranslate="dataSurveyApp.usuarioEncuesta.home.notFound">No usuarioEncuestas found</span>
</div> </div>
@ -32,58 +41,49 @@
<table class="table table-striped" aria-describedby="page-heading"> <table class="table table-striped" aria-describedby="page-heading">
<thead> <thead>
<tr> <tr>
<th scope="col"><span jhiTranslate="global.field.id">ID</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.usuarioEncuesta.rol">Rol</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.usuarioEncuesta.rol">Rol</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.usuarioEncuesta.estado">Estado</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.usuarioEncuesta.estado">Estado</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.usuarioEncuesta.fechaAgregado">Fecha Agregado</span></th> <th scope="col"><span jhiTranslate="dataSurveyApp.usuarioEncuesta.fechaAgregado">Fecha Agregado</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.usuarioEncuesta.usuarioExtra">Usuario Extra</span></th> <th scope="col"><span>Encuesta</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.usuarioEncuesta.encuesta">Encuesta</span></th>
<th scope="col"></th> <th scope="col"></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<tr *ngFor="let usuarioEncuesta of usuarioEncuestas; trackBy: trackId" data-cy="entityTable"> <tr
<td> *ngFor="let usuarioEncuesta of usuarioEncuestas | filter: 'rol':searchRol | filter: 'estado':searchEstado; trackBy: trackId"
<a [routerLink]="['/usuario-encuesta', usuarioEncuesta.id, 'view']">{{ usuarioEncuesta.id }}</a> data-cy="entityTable"
</td> >
<td jhiTranslate="{{ 'dataSurveyApp.RolColaborador.' + usuarioEncuesta.rol }}">{{ usuarioEncuesta.rol }}</td> <td jhiTranslate="{{ 'dataSurveyApp.RolColaborador.' + usuarioEncuesta.rol }}">{{ usuarioEncuesta.rol }}</td>
<td jhiTranslate="{{ 'dataSurveyApp.EstadoColaborador.' + usuarioEncuesta.estado }}">{{ usuarioEncuesta.estado }}</td> <td jhiTranslate="{{ 'dataSurveyApp.EstadoColaborador.' + usuarioEncuesta.estado }}">{{ usuarioEncuesta.estado }}</td>
<td>{{ usuarioEncuesta.fechaAgregado | formatMediumDatetime }}</td> <td>{{ usuarioEncuesta.fechaAgregado | formatShortDatetime | titlecase }}</td>
<td>
<div *ngIf="usuarioEncuesta.usuarioExtra">
<a [routerLink]="['/usuario-extra', usuarioEncuesta.usuarioExtra?.id, 'view']">{{ usuarioEncuesta.usuarioExtra?.id }}</a>
</div>
</td>
<td> <td>
<div *ngIf="usuarioEncuesta.encuesta"> <div *ngIf="usuarioEncuesta.encuesta">
<a [routerLink]="['/encuesta', usuarioEncuesta.encuesta?.id, 'view']">{{ usuarioEncuesta.encuesta?.id }}</a> <a>{{ usuarioEncuesta.encuesta?.nombre }} (#{{ usuarioEncuesta.encuesta?.id }})</a>
</div> </div>
</td> </td>
<td class="text-right"> <td class="text-right">
<div class="btn-group"> <div class="btn-group" *ngIf="usuarioEncuesta.encuesta">
<button <button
type="submit" *ngIf="usuarioEncuesta.estado === 'ACTIVE'"
[routerLink]="['/usuario-encuesta', usuarioEncuesta.id, 'view']" type="button"
class="btn btn-info btn-sm" [routerLink]="['/encuesta', usuarioEncuesta.encuesta.id, 'edit']"
data-cy="entityDetailsButton" class="ds-btn ds-btn--primary"
[disabled]="isLoading"
> >
<fa-icon icon="eye"></fa-icon> <span>Editar encuesta</span>
<span class="d-none d-md-inline" jhiTranslate="entity.action.view">View</span>
</button> </button>
<button <button
type="submit" *ngIf="usuarioEncuesta.estado === 'PENDING'"
[routerLink]="['/usuario-encuesta', usuarioEncuesta.id, 'edit']" type="button"
class="btn btn-primary btn-sm" (click)="aceptarInvitacion(usuarioEncuesta)"
data-cy="entityEditButton" class="ds-btn btn-success"
[disabled]="isLoading"
> >
<fa-icon icon="pencil-alt"></fa-icon> <span>Aceptar invitación</span>
<span class="d-none d-md-inline" jhiTranslate="entity.action.edit">Edit</span>
</button> </button>
<button type="submit" (click)="delete(usuarioEncuesta)" class="ds-btn ds-btn--danger btn-sm" data-cy="entityDeleteButton">
<button type="submit" (click)="delete(usuarioEncuesta)" class="btn btn-danger btn-sm" data-cy="entityDeleteButton"> <fa-icon icon="sign-out-alt"></fa-icon>
<fa-icon icon="times"></fa-icon> <span class="d-none d-md-inline" jhiTranslate="dataSurveyApp.usuarioEncuesta.delete.getOut">Get Out</span>
<span class="d-none d-md-inline" jhiTranslate="entity.action.delete">Delete</span>
</button> </button>
</div> </div>
</td> </td>

View File

@ -5,16 +5,47 @@ import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { IUsuarioEncuesta } from '../usuario-encuesta.model'; import { IUsuarioEncuesta } from '../usuario-encuesta.model';
import { UsuarioEncuestaService } from '../service/usuario-encuesta.service'; import { UsuarioEncuestaService } from '../service/usuario-encuesta.service';
import { UsuarioEncuestaDeleteDialogComponent } from '../delete/usuario-encuesta-delete-dialog.component'; import { UsuarioEncuestaDeleteDialogComponent } from '../delete/usuario-encuesta-delete-dialog.component';
import * as dayjs from 'dayjs';
import { faPencilAlt, faPollH } from '@fortawesome/free-solid-svg-icons';
import { AccountService } from 'app/core/auth/account.service';
import { IUsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model';
import { IUser } from '../../user/user.model';
import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service';
import { ActivatedRoute, Router } from '@angular/router';
import { EstadoColaborador } from '../../enumerations/estado-colaborador.model';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import * as $ from 'jquery';
import { DATE_TIME_FORMAT } from '../../../config/input.constants';
@Component({ @Component({
selector: 'jhi-usuario-encuesta', selector: 'jhi-usuario-encuesta',
templateUrl: './usuario-encuesta.component.html', templateUrl: './usuario-encuesta.component.html',
}) })
export class UsuarioEncuestaComponent implements OnInit { export class UsuarioEncuestaComponent implements OnInit {
faPollH = faPollH;
faPencilAlt = faPencilAlt;
usuarioEncuestas?: IUsuarioEncuesta[]; usuarioEncuestas?: IUsuarioEncuesta[];
isLoading = false; isLoading = false;
usuarioExtra: IUsuarioExtra | null = null;
user: IUser | null = null;
isSavingCollab = false;
public searchRol: string;
public searchEstado: string;
constructor(protected usuarioEncuestaService: UsuarioEncuestaService, protected modalService: NgbModal) {} constructor(
protected usuarioEncuestaService: UsuarioEncuestaService,
protected modalService: NgbModal,
protected usuarioExtraService: UsuarioExtraService,
protected activatedRoute: ActivatedRoute,
protected accountService: AccountService,
protected router: Router
) {
this.searchRol = '';
this.searchEstado = '';
}
loadAll(): void { loadAll(): void {
this.isLoading = true; this.isLoading = true;
@ -22,7 +53,10 @@ export class UsuarioEncuestaComponent implements OnInit {
this.usuarioEncuestaService.query().subscribe( this.usuarioEncuestaService.query().subscribe(
(res: HttpResponse<IUsuarioEncuesta[]>) => { (res: HttpResponse<IUsuarioEncuesta[]>) => {
this.isLoading = false; this.isLoading = false;
this.usuarioEncuestas = res.body ?? []; const tempUsuarioEncuestas = res.body ?? [];
this.usuarioEncuestas = tempUsuarioEncuestas
.filter(c => c.usuarioExtra?.id === this.usuarioExtra?.id)
.filter(c => c.encuesta?.estado !== 'DELETED');
}, },
() => { () => {
this.isLoading = false; this.isLoading = false;
@ -31,7 +65,22 @@ export class UsuarioEncuestaComponent implements OnInit {
} }
ngOnInit(): void { ngOnInit(): void {
this.loadAll(); this.searchRol = '';
this.searchEstado = '';
this.accountService.getAuthenticationState().subscribe(account => {
if (account !== null) {
this.usuarioExtraService.find(account.id).subscribe(usuarioExtra => {
this.usuarioExtra = usuarioExtra.body;
this.loadAll();
if (this.usuarioExtra !== null) {
if (this.usuarioExtra.id === undefined) {
const today = dayjs().startOf('day');
this.usuarioExtra.fechaNacimiento = today;
}
}
});
}
});
} }
trackId(index: number, item: IUsuarioEncuesta): number { trackId(index: number, item: IUsuarioEncuesta): number {
@ -48,4 +97,29 @@ export class UsuarioEncuestaComponent implements OnInit {
} }
}); });
} }
aceptarInvitacion(usuarioEncuesta: IUsuarioEncuesta) {
usuarioEncuesta.estado = EstadoColaborador.ACTIVE;
usuarioEncuesta.fechaAgregado = dayjs(usuarioEncuesta.fechaAgregado, DATE_TIME_FORMAT);
this.subscribeToSaveResponseCollab(this.usuarioEncuestaService.update(usuarioEncuesta));
}
protected subscribeToSaveResponseCollab(result: Observable<HttpResponse<IUsuarioEncuesta>>): void {
result.pipe(finalize(() => this.onSaveFinalizeCollab())).subscribe(
() => this.onSaveSuccessCollab(),
() => this.onSaveErrorCollab()
);
}
protected onSaveSuccessCollab(): void {
this.loadAll();
}
protected onSaveErrorCollab(): void {
// Api for inheritance.
}
protected onSaveFinalizeCollab(): void {
this.isSavingCollab = false;
}
} }

View File

@ -6,6 +6,9 @@ import { UsuarioEncuestaComponent } from '../list/usuario-encuesta.component';
import { UsuarioEncuestaDetailComponent } from '../detail/usuario-encuesta-detail.component'; import { UsuarioEncuestaDetailComponent } from '../detail/usuario-encuesta-detail.component';
import { UsuarioEncuestaUpdateComponent } from '../update/usuario-encuesta-update.component'; import { UsuarioEncuestaUpdateComponent } from '../update/usuario-encuesta-update.component';
import { UsuarioEncuestaRoutingResolveService } from './usuario-encuesta-routing-resolve.service'; import { UsuarioEncuestaRoutingResolveService } from './usuario-encuesta-routing-resolve.service';
import { EncuestaDetailComponent } from '../../encuesta/detail/encuesta-detail.component';
import { EncuestaUpdateComponent } from '../../encuesta/update/encuesta-update.component';
import { EncuestaRoutingResolveService } from '../../encuesta/route/encuesta-routing-resolve.service';
const usuarioEncuestaRoute: Routes = [ const usuarioEncuestaRoute: Routes = [
{ {
@ -37,6 +40,22 @@ const usuarioEncuestaRoute: Routes = [
}, },
canActivate: [UserRouteAccessService], canActivate: [UserRouteAccessService],
}, },
{
path: '/encuesta/:id/preview',
component: EncuestaDetailComponent,
resolve: {
usuarioEncuesta: EncuestaRoutingResolveService,
},
canActivate: [UserRouteAccessService],
},
{
path: '/encuesta/:id/edit',
component: EncuestaUpdateComponent,
resolve: {
usuarioEncuesta: EncuestaRoutingResolveService,
},
canActivate: [UserRouteAccessService],
},
]; ];
@NgModule({ @NgModule({

View File

@ -27,8 +27,9 @@ export class UsuarioEncuestaService {
update(usuarioEncuesta: IUsuarioEncuesta): Observable<EntityResponseType> { update(usuarioEncuesta: IUsuarioEncuesta): Observable<EntityResponseType> {
const copy = this.convertDateFromClient(usuarioEncuesta); const copy = this.convertDateFromClient(usuarioEncuesta);
const url = `${this.resourceUrl}/${getUsuarioEncuestaIdentifier(usuarioEncuesta) as number}`;
return this.http return this.http
.put<IUsuarioEncuesta>(`${this.resourceUrl}/${getUsuarioEncuestaIdentifier(usuarioEncuesta) as number}`, copy, { .put<IUsuarioEncuesta>(url, copy, {
observe: 'response', observe: 'response',
}) })
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
@ -36,8 +37,9 @@ export class UsuarioEncuestaService {
partialUpdate(usuarioEncuesta: IUsuarioEncuesta): Observable<EntityResponseType> { partialUpdate(usuarioEncuesta: IUsuarioEncuesta): Observable<EntityResponseType> {
const copy = this.convertDateFromClient(usuarioEncuesta); const copy = this.convertDateFromClient(usuarioEncuesta);
const url = `${this.resourceUrl}/${getUsuarioEncuestaIdentifier(usuarioEncuesta) as number}`;
return this.http return this.http
.patch<IUsuarioEncuesta>(`${this.resourceUrl}/${getUsuarioEncuestaIdentifier(usuarioEncuesta) as number}`, copy, { .patch<IUsuarioEncuesta>(url, copy, {
observe: 'response', observe: 'response',
}) })
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
@ -66,6 +68,10 @@ export class UsuarioEncuestaService {
return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' }); return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' });
} }
sendCorreoInvitacion(colaborator: IUsuarioEncuesta) {
return this.http.post(`${this.resourceUrl}/notify/${colaborator.id}`, { body: colaborator, observe: 'response' });
}
addUsuarioEncuestaToCollectionIfMissing( addUsuarioEncuestaToCollectionIfMissing(
usuarioEncuestaCollection: IUsuarioEncuesta[], usuarioEncuestaCollection: IUsuarioEncuesta[],
...usuarioEncuestasToCheck: (IUsuarioEncuesta | null | undefined)[] ...usuarioEncuestasToCheck: (IUsuarioEncuesta | null | undefined)[]

View File

@ -76,10 +76,10 @@ export const USER_ROUTES: RouteInfo[] = [
// type: 'link', // type: 'link',
// icontype: 'nc-icon nc-album-2', // icontype: 'nc-icon nc-album-2',
// }, // },
// { {
// path: '/colaboraciones', path: '/colaboraciones',
// title: 'Colaboraciones', title: 'Colaboraciones',
// type: 'link', type: 'link',
// icontype: 'nc-icon nc-world-2', icontype: 'nc-icon nc-world-2',
// }, },
]; ];

View File

@ -94,7 +94,6 @@ export class LoginComponent implements OnInit, AfterViewInit {
} }
}, },
response => { response => {
debugger;
if (response.status == 401 && response.error.detail == 'Bad credentials') { if (response.status == 401 && response.error.detail == 'Bad credentials') {
this.activateGoogle(); this.activateGoogle();
} else { } else {
@ -109,7 +108,6 @@ export class LoginComponent implements OnInit, AfterViewInit {
} }
processError(response: HttpErrorResponse): void { processError(response: HttpErrorResponse): void {
debugger;
if (response.status === 400 && response.error.type === LOGIN_ALREADY_USED_TYPE) { if (response.status === 400 && response.error.type === LOGIN_ALREADY_USED_TYPE) {
this.errorUserExists = true; this.errorUserExists = true;
} else if (response.status === 400 && response.error.type === EMAIL_ALREADY_USED_TYPE) { } else if (response.status === 400 && response.error.type === EMAIL_ALREADY_USED_TYPE) {
@ -153,7 +151,6 @@ export class LoginComponent implements OnInit, AfterViewInit {
login(): void { login(): void {
this.error = false; this.error = false;
this.userSuspended = false; this.userSuspended = false;
debugger;
this.loginService this.loginService
.login({ .login({
username: this.loginForm.get('username')!.value, username: this.loginForm.get('username')!.value,
@ -162,9 +159,6 @@ export class LoginComponent implements OnInit, AfterViewInit {
}) })
.subscribe( .subscribe(
value => { value => {
debugger;
console.log(value);
/*if (value?.activated == false){ /*if (value?.activated == false){
this.userSuspended = true; this.userSuspended = true;
@ -178,7 +172,6 @@ export class LoginComponent implements OnInit, AfterViewInit {
// } // }
}, },
response => { response => {
debugger;
if (response.status == 401 && response.error.detail == 'Bad credentials') { if (response.status == 401 && response.error.detail == 'Bad credentials') {
this.error = true; this.error = true;
} else { } else {

View File

@ -12,7 +12,6 @@ export class LoginService {
constructor(private accountService: AccountService, private authServerProvider: AuthServerProvider) {} constructor(private accountService: AccountService, private authServerProvider: AuthServerProvider) {}
login(credentials: Login): Observable<Account | null> { login(credentials: Login): Observable<Account | null> {
debugger;
return this.authServerProvider.login(credentials).pipe(mergeMap(() => this.accountService.identity(true))); return this.authServerProvider.login(credentials).pipe(mergeMap(() => this.accountService.identity(true)));
} }

View File

@ -14,7 +14,7 @@
} }
.preview-survey > div { .preview-survey > div {
padding: 20px 0; padding: 20px 0;
border-bottom: 1px solid #ccc; // border-bottom: 1px solid #ccc;
} }
.preview-survey .radio label, .preview-survey .radio label,
.preview-survey .checkbox label { .preview-survey .checkbox label {

View File

@ -3,7 +3,7 @@
"EstadoPlantilla": { "EstadoPlantilla": {
"null": "", "null": "",
"DRAFT": "Borrador", "DRAFT": "Borrador",
"ACTIVE": "Activa", "ACTIVE": "En tienda",
"DELETED": "Eliminada", "DELETED": "Eliminada",
"DISABLED": "Desactivada" "DISABLED": "Desactivada"
} }

View File

@ -152,7 +152,8 @@
"pattern": "Este campo debe seguir el patrón {{pattern}}.", "pattern": "Este campo debe seguir el patrón {{pattern}}.",
"number": "Este campo debe ser un número.", "number": "Este campo debe ser un número.",
"integerNumber": "Este campo debe ser un número entero.", "integerNumber": "Este campo debe ser un número entero.",
"datetimelocal": "Este campo debe ser una fecha y hora." "datetimelocal": "Este campo debe ser una fecha y hora.",
"minoigual": "Este campo debe ser mayor o igual que 0."
}, },
"publish": { "publish": {
"title": "Publicar encuesta", "title": "Publicar encuesta",

View File

@ -12,7 +12,11 @@
"updated": "Una plantilla ha sido actualizada con el identificador {{ param }}", "updated": "Una plantilla ha sido actualizada con el identificador {{ param }}",
"deleted": "Una plantilla ha sido eliminada con el identificador {{ param }}", "deleted": "Una plantilla ha sido eliminada con el identificador {{ param }}",
"delete": { "delete": {
"question": "¿Seguro que quiere eliminar Plantilla {{ id }}?" "question": "¿Seguro que quiere eliminar Plantilla {{ id }}?",
"deletefromstore": "¿Seguro que quiere eliminar esta plantilla de la tienda?"
},
"publish": {
"store": "¿Seguro que quiere publicar esta plantilla a la tienda?"
}, },
"detail": { "detail": {
"title": "Plantilla" "title": "Plantilla"

View File

@ -2,26 +2,29 @@
"dataSurveyApp": { "dataSurveyApp": {
"usuarioEncuesta": { "usuarioEncuesta": {
"home": { "home": {
"title": "Usuario Encuestas", "title": "Colaboraciones",
"refreshListLabel": "Refrescar lista", "refreshListLabel": "Refrescar lista",
"createLabel": "Crear nuevo Usuario Encuesta", "createLabel": "Crear nuevo Colaborador",
"createOrEditLabel": "Crear o editar Usuario Encuesta", "createOrEditLabel": "Crear o editar Colaborador",
"notFound": "Ningún Usuario Encuestas encontrado" "notFound": "Ningún Colaborador encontrado"
}, },
"created": "Un nuevo Usuario Encuesta ha sido creado con el identificador {{ param }}", "created": "Un Colaborador ha sido creado con el identificador {{ param }}",
"updated": "Un Usuario Encuesta ha sido actualizado con el identificador {{ param }}", "updated": "Ha aceptado la colaboración en la encuesta #{{ param }}",
"deleted": "Un Usuario Encuesta ha sido eliminado con el identificador {{ param }}", "deleted": "Un Colaborador ha sido expulsado de la encuesta",
"delete": { "delete": {
"question": "¿Seguro que quiere eliminar Usuario Encuesta {{ id }}?" "question": "¿Seguro que quiere expulsar al colaborador de la encuesta?",
"action": "Expulsar",
"questionGetOut": "¿Seguro que quiere salirse de la colaboracion de encuesta?",
"getOut": "Salir"
}, },
"detail": { "detail": {
"title": "Usuario Encuesta" "title": "Colaborador"
}, },
"id": "ID", "id": "ID",
"rol": "Rol", "rol": "Rol",
"estado": "Estado", "estado": "Estado",
"fechaAgregado": "Fecha Agregado", "fechaAgregado": "Fecha Agregado",
"usuarioExtra": "Usuario Extra", "usuarioExtra": "Usuario",
"encuesta": "Encuesta" "encuesta": "Encuesta"
} }
} }