Merge pull request #132 from Quantum-P3/qa

deploy
This commit is contained in:
Eduardo Quiros 2021-08-15 06:12:21 +00:00 committed by GitHub
commit d5633430ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
170 changed files with 10106 additions and 1702 deletions

View File

@ -43,7 +43,11 @@
{ "glob": "axios.min.js", "input": "./node_modules/axios/dist", "output": "swagger-ui" },
{ "glob": "**/*", "input": "src/main/webapp/swagger-ui/", "output": "swagger-ui" }
],
"styles": ["src/main/webapp/content/scss/paper-dashboard.scss", "./node_modules/swiper/swiper-bundle.min.css"],
"styles": [
"src/main/webapp/content/scss/paper-dashboard.scss",
"./node_modules/swiper/swiper-bundle.min.css",
"node_modules/chartist/dist/chartist.css"
],
"scripts": [
"./node_modules/jquery/dist/jquery.min.js",
"src/main/webapp/content/js/jquery.bootstrap.wizard.min.js",

2899
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -58,7 +58,8 @@
"preci:e2e:server:start": "npm run docker:db:await --if-present && npm run docker:others:await --if-present",
"ci:e2e:server:start": "java -jar target/e2e.$npm_package_config_packaging --spring.profiles.active=$npm_package_config_default_environment -Dlogging.level.ROOT=OFF -Dlogging.level.org.zalando=OFF -Dlogging.level.tech.jhipster=OFF -Dlogging.level.org.datasurvey=OFF -Dlogging.level.org.springframework=OFF -Dlogging.level.org.springframework.web=OFF -Dlogging.level.org.springframework.security=OFF --logging.level.org.springframework.web=ERROR",
"ci:frontend:build": "npm run webapp:build:$npm_package_config_default_environment",
"ci:frontend:test": "npm run ci:frontend:build && npm test"
"ci:frontend:test": "npm run ci:frontend:build && npm test",
"postinstall": "ngcc"
},
"config": {
"backend_port": 8080,
@ -66,6 +67,7 @@
"packaging": "jar"
},
"dependencies": {
"@angular/cdk": "^12.1.4",
"@angular/common": "12.0.5",
"@angular/compiler": "12.0.5",
"@angular/core": "12.0.5",
@ -74,18 +76,28 @@
"@angular/platform-browser": "12.0.5",
"@angular/platform-browser-dynamic": "12.0.5",
"@angular/router": "12.0.5",
"@fortawesome/angular-fontawesome": "0.9.0",
"@fortawesome/fontawesome-svg-core": "1.2.35",
"@fortawesome/free-solid-svg-icons": "5.15.3",
"@fortawesome/angular-fontawesome": "^0.9.0",
"@fortawesome/fontawesome-svg-core": "^1.2.35",
"@fortawesome/free-brands-svg-icons": "^5.15.3",
"@fortawesome/free-solid-svg-icons": "^5.15.3",
"@ng-bootstrap/ng-bootstrap": "9.1.3",
"@ngx-translate/core": "13.0.0",
"@ngx-translate/http-loader": "6.0.0",
"@types/gapi.auth2": "0.0.54",
"angularx-social-login": "^4.0.1",
"bootstrap": "4.6.0",
"chart.js": "^3.5.0",
"chartist": "^0.11.4",
"dayjs": "1.10.5",
"file-saver": "^2.0.5",
"jquery": "^3.6.0",
"jspdf": "^2.3.1",
"jw-angular-social-buttons": "^1.0.0",
"ng-chartist": "^5.0.0",
"ng2-charts": "^2.4.2",
"ngx-infinite-scroll": "10.0.1",
"ngx-paypal": "^8.0.0",
"ngx-sharebuttons": "^8.0.5",
"ngx-webstorage": "8.0.0",
"rxjs": "6.6.7",
"sockjs-client": "1.5.0",
@ -93,6 +105,7 @@
"swiper": "^6.7.5",
"tslib": "2.3.0",
"webstomp-client": "1.2.6",
"xlsx": "^0.17.0",
"zone.js": "0.11.4"
},
"devDependencies": {
@ -103,6 +116,8 @@
"@angular/compiler-cli": "12.0.5",
"@angular/service-worker": "12.0.5",
"@types/bootstrap": "^5.0.17",
"@types/chartist": "^0.11.1",
"@types/file-saver": "^2.0.3",
"@types/jest": "26.0.23",
"@types/jquery": "^3.5.6",
"@types/node": "15.12.2",

View File

@ -318,6 +318,12 @@
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.0.0-2</version>
</dependency>
<!-- jhipster-needle-maven-add-dependency -->
</dependencies>

View File

@ -64,7 +64,7 @@ public class UsuarioExtra implements Serializable {
joinColumns = @JoinColumn(name = "usuario_extra_id"),
inverseJoinColumns = @JoinColumn(name = "plantilla_id")
)
@JsonIgnoreProperties(value = { "pPreguntaCerradas", "pPreguntaAbiertas", "categoria", "usuarioExtras" }, allowSetters = true)
@JsonIgnoreProperties(value = { "pPreguntaCerradas", "pPreguntaAbiertas", "usuarioExtras" }, allowSetters = true)
private Set<Plantilla> plantillas = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here

View File

@ -4,7 +4,9 @@ import java.nio.charset.StandardCharsets;
import java.util.Locale;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.datasurvey.domain.Factura;
import org.datasurvey.domain.User;
import org.datasurvey.domain.UsuarioEncuesta;
import org.datasurvey.domain.UsuarioExtra;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -32,6 +34,8 @@ public class MailService {
private static final String CONTRASENNA = "contrasenna";
private static final String FACTURA = "factura";
private static final String BASE_URL = "baseUrl";
private final JHipsterProperties jHipsterProperties;
@ -111,6 +115,38 @@ public class MailService {
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
public void sendEmailFromTemplateFactura(User user, Factura factura, 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(FACTURA, factura);
context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
String content = templateEngine.process(templateName, context);
String subject = messageSource.getMessage(titleKey, null, locale);
sendEmail(user.getEmail(), subject, content, false, true);
}
@Async
public void sendActivationEmail(User user) {
log.debug("Sending activation email to '{}'", user.getEmail());
@ -164,4 +200,32 @@ public class MailService {
log.debug("Sending encuesta deletion notification mail to '{}'", user.getUser().getEmail());
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"
);
}
@Async
public void sendReceiptUser(UsuarioExtra user, Factura factura) {
log.debug("Sending paypal receipt mail to '{}'", user.getUser().getEmail());
sendEmailFromTemplateFactura(user.getUser(), factura, "mail/facturaPayPalEmail", "email.receipt.title");
}
}

View File

@ -80,6 +80,14 @@ public class EPreguntaCerradaOpcionResource {
.body(result);
}
@PostMapping("/e-pregunta-cerrada-opcions/count/{id}")
public ResponseEntity<EPreguntaCerradaOpcion> updateOpcionCount(@PathVariable(value = "id", required = true) final Long id) {
EPreguntaCerradaOpcion updatedOpcion = getEPreguntaCerradaOpcion(id).getBody();
int cantidad = updatedOpcion.getCantidad();
updatedOpcion.setCantidad(cantidad += 1);
return ResponseEntity.ok(updatedOpcion);
}
/**
* {@code PUT /e-pregunta-cerrada-opcions/:id} : Updates an existing ePreguntaCerradaOpcion.
*

View File

@ -11,10 +11,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.datasurvey.domain.EPreguntaAbierta;
import org.datasurvey.domain.EPreguntaCerrada;
import org.datasurvey.domain.EPreguntaCerradaOpcion;
import org.datasurvey.domain.Encuesta;
import org.datasurvey.domain.*;
import org.datasurvey.domain.enumeration.AccesoEncuesta;
import org.datasurvey.repository.EncuestaRepository;
import org.datasurvey.service.*;
@ -59,6 +56,14 @@ public class EncuestaResource {
private final EPreguntaCerradaOpcionService ePreguntaCerradaOpcionService;
private final PlantillaService plantillaService;
private final PPreguntaCerradaService pPreguntaCerradaService;
private final PPreguntaAbiertaService pPreguntaAbiertaService;
private final PPreguntaCerradaOpcionService pPreguntaCerradaOpcionService;
public EncuestaResource(
EncuestaService encuestaService,
EncuestaRepository encuestaRepository,
@ -66,7 +71,11 @@ public class EncuestaResource {
MailService mailService,
EPreguntaCerradaService ePreguntaCerradaService,
EPreguntaAbiertaService ePreguntaAbiertaService,
EPreguntaCerradaOpcionService ePreguntaCerradaOpcionService
EPreguntaCerradaOpcionService ePreguntaCerradaOpcionService,
PlantillaService plantillaService,
PPreguntaCerradaService pPreguntaCerradaService,
PPreguntaAbiertaService pPreguntaAbiertaService,
PPreguntaCerradaOpcionService pPreguntaCerradaOpcionService
) {
this.encuestaService = encuestaService;
this.encuestaRepository = encuestaRepository;
@ -75,6 +84,10 @@ public class EncuestaResource {
this.ePreguntaCerradaService = ePreguntaCerradaService;
this.ePreguntaAbiertaService = ePreguntaAbiertaService;
this.ePreguntaCerradaOpcionService = ePreguntaCerradaOpcionService;
this.plantillaService = plantillaService;
this.pPreguntaCerradaService = pPreguntaCerradaService;
this.pPreguntaAbiertaService = pPreguntaAbiertaService;
this.pPreguntaCerradaOpcionService = pPreguntaCerradaOpcionService;
}
/**
@ -97,6 +110,78 @@ public class EncuestaResource {
.body(result);
}
@PostMapping("/encuestas/{plantillaId}")
public ResponseEntity<Encuesta> createEncuestaFromTemplate(
@Valid @RequestBody Encuesta encuesta,
@PathVariable(value = "plantillaId", required = false) final Long plantillaId
) throws URISyntaxException {
log.debug("REST request to save Encuesta : {}", encuesta);
if (encuesta.getId() != null) {
throw new BadRequestAlertException("A new encuesta cannot already have an ID", ENTITY_NAME, "idexists");
}
// Copy from survey template to survey
Optional<Plantilla> plantilla = plantillaService.findOne(plantillaId);
if (plantilla.isPresent()) {
encuesta.setNombre(plantilla.get().getNombre());
encuesta.setDescripcion(plantilla.get().getDescripcion());
encuesta.setCategoria(plantilla.get().getCategoria());
Encuesta encuestaCreated = encuestaService.save(encuesta);
// Preguntas cerradas
List<PPreguntaCerrada> preguntasCerradas = pPreguntaCerradaService.findAll();
for (PPreguntaCerrada pPreguntaCerrada : preguntasCerradas) {
if (pPreguntaCerrada.getPlantilla().getId().equals(plantillaId)) {
EPreguntaCerrada newEPreguntaCerrada = new EPreguntaCerrada();
newEPreguntaCerrada.setNombre(pPreguntaCerrada.getNombre());
newEPreguntaCerrada.setTipo(pPreguntaCerrada.getTipo());
newEPreguntaCerrada.setOpcional(pPreguntaCerrada.getOpcional());
newEPreguntaCerrada.setOrden(pPreguntaCerrada.getOrden());
newEPreguntaCerrada.setEncuesta(encuestaCreated);
ePreguntaCerradaService.save(newEPreguntaCerrada);
// Opciones de preguntas cerradas
List<PPreguntaCerradaOpcion> opciones = pPreguntaCerradaOpcionService.findAll();
for (PPreguntaCerradaOpcion pPreguntaCerradaOpcion : opciones) {
if (pPreguntaCerradaOpcion.getPPreguntaCerrada().getId().equals(pPreguntaCerrada.getId())) {
EPreguntaCerradaOpcion newEPreguntaCerradaOpcion = new EPreguntaCerradaOpcion();
newEPreguntaCerradaOpcion.setNombre(pPreguntaCerradaOpcion.getNombre());
newEPreguntaCerradaOpcion.setOrden(pPreguntaCerradaOpcion.getOrden());
newEPreguntaCerradaOpcion.setCantidad(0);
newEPreguntaCerradaOpcion.setEPreguntaCerrada(newEPreguntaCerrada);
ePreguntaCerradaOpcionService.save(newEPreguntaCerradaOpcion);
}
}
}
}
// Preguntas abiertas
List<PPreguntaAbierta> preguntasAbiertas = pPreguntaAbiertaService.findAll();
for (PPreguntaAbierta pPreguntaAbierta : preguntasAbiertas) {
if (pPreguntaAbierta.getPlantilla().getId().equals(plantillaId)) {
EPreguntaAbierta newEPreguntaAbierta = new EPreguntaAbierta();
newEPreguntaAbierta.setNombre(pPreguntaAbierta.getNombre());
newEPreguntaAbierta.setOpcional(pPreguntaAbierta.getOpcional());
newEPreguntaAbierta.setOrden(pPreguntaAbierta.getOrden());
newEPreguntaAbierta.setEncuesta(encuestaCreated);
ePreguntaAbiertaService.save(newEPreguntaAbierta);
}
}
return ResponseEntity
.created(new URI("/api/encuestas/" + encuestaCreated.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, encuestaCreated.getId().toString()))
.body(encuestaCreated);
}
return ResponseEntity.ok().body(null);
}
/**
* {@code PUT /encuestas/:id} : Updates an existing encuesta.
*
@ -136,6 +221,31 @@ public class EncuestaResource {
.body(result);
}
@PutMapping("/encuestas/update/{id}")
public ResponseEntity<Encuesta> updateEncuestaReal(
@PathVariable(value = "id", required = false) final Long id,
@Valid @RequestBody Encuesta encuesta
) throws URISyntaxException {
log.debug("REST request to update Encuesta : {}, {}", id, encuesta);
if (encuesta.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
if (!Objects.equals(id, encuesta.getId())) {
throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
}
if (!encuestaRepository.existsById(id)) {
throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
}
Encuesta result = encuestaService.save(encuesta);
return ResponseEntity
.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, encuesta.getId().toString()))
.body(result);
}
@PutMapping("/encuestas/publish/{id}")
public ResponseEntity<Encuesta> publishEncuesta(
@PathVariable(value = "id", required = false) final Long id,

View File

@ -8,9 +8,12 @@ import java.util.Optional;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.datasurvey.domain.Factura;
import org.datasurvey.domain.UsuarioExtra;
import org.datasurvey.repository.FacturaRepository;
import org.datasurvey.service.FacturaQueryService;
import org.datasurvey.service.FacturaService;
import org.datasurvey.service.MailService;
import org.datasurvey.service.UsuarioExtraService;
import org.datasurvey.service.criteria.FacturaCriteria;
import org.datasurvey.web.rest.errors.BadRequestAlertException;
import org.slf4j.Logger;
@ -41,10 +44,22 @@ public class FacturaResource {
private final FacturaQueryService facturaQueryService;
public FacturaResource(FacturaService facturaService, FacturaRepository facturaRepository, FacturaQueryService facturaQueryService) {
private final UsuarioExtraService userExtraService;
private final MailService mailService;
public FacturaResource(
FacturaService facturaService,
FacturaRepository facturaRepository,
FacturaQueryService facturaQueryService,
UsuarioExtraService userExtraService,
MailService mailService
) {
this.facturaService = facturaService;
this.facturaRepository = facturaRepository;
this.facturaQueryService = facturaQueryService;
this.userExtraService = userExtraService;
this.mailService = mailService;
}
/**
@ -60,11 +75,22 @@ public class FacturaResource {
if (factura.getId() != null) {
throw new BadRequestAlertException("A new factura cannot already have an ID", ENTITY_NAME, "idexists");
}
Optional<UsuarioExtra> usuarioExtra = userExtraService.findOne(Long.parseLong(factura.getNombreUsuario()));
factura.setNombreUsuario(usuarioExtra.get().getNombre());
Factura result = facturaService.save(factura);
mailService.sendReceiptUser(usuarioExtra.get(), factura);
return ResponseEntity
.created(new URI("/api/facturas/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(result);
//retrieve yser
//Enviar el correo
}
/**

View File

@ -2,11 +2,14 @@ package org.datasurvey.web.rest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.datasurvey.domain.EPreguntaCerrada;
import org.datasurvey.domain.PPreguntaCerrada;
import org.datasurvey.domain.PPreguntaCerradaOpcion;
import org.datasurvey.repository.PPreguntaCerradaOpcionRepository;
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.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/p-pregunta-cerrada-opcions")
@PostMapping("/p-pregunta-cerrada-opcions/{id}")
public ResponseEntity<PPreguntaCerradaOpcion> createPPreguntaCerradaOpcion(
@Valid @RequestBody PPreguntaCerradaOpcion pPreguntaCerradaOpcion
@Valid @RequestBody PPreguntaCerradaOpcion pPreguntaCerradaOpcion,
@PathVariable(value = "id", required = false) final Long id
) throws URISyntaxException {
PPreguntaCerrada pPreguntaCerrada = new PPreguntaCerrada();
pPreguntaCerrada.setId(id);
pPreguntaCerradaOpcion.setPPreguntaCerrada(pPreguntaCerrada);
log.debug("REST request to save PPreguntaCerradaOpcion : {}", pPreguntaCerradaOpcion);
if (pPreguntaCerradaOpcion.getId() != null) {
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()))
.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.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.datasurvey.domain.Plantilla;
import org.datasurvey.domain.*;
import org.datasurvey.repository.PlantillaRepository;
import org.datasurvey.service.PlantillaQueryService;
import org.datasurvey.service.PlantillaService;
import org.datasurvey.service.*;
import org.datasurvey.service.criteria.PlantillaCriteria;
import org.datasurvey.web.rest.errors.BadRequestAlertException;
import org.slf4j.Logger;
@ -41,14 +43,26 @@ public class PlantillaResource {
private final PlantillaQueryService plantillaQueryService;
private final PPreguntaCerradaService pPreguntaCerradaService;
private final PPreguntaAbiertaService pPreguntaAbiertaService;
private final PPreguntaCerradaOpcionService pPreguntaCerradaOpcionService;
public PlantillaResource(
PlantillaService plantillaService,
PlantillaRepository plantillaRepository,
PlantillaQueryService plantillaQueryService
PlantillaQueryService plantillaQueryService,
PPreguntaCerradaService pPreguntaCerradaService,
PPreguntaAbiertaService pPreguntaAbiertaService,
PPreguntaCerradaOpcionService ePreguntaCerradaOpcionService
) {
this.plantillaService = plantillaService;
this.plantillaRepository = plantillaRepository;
this.plantillaQueryService = plantillaQueryService;
this.pPreguntaCerradaService = pPreguntaCerradaService;
this.pPreguntaAbiertaService = pPreguntaAbiertaService;
this.pPreguntaCerradaOpcionService = ePreguntaCerradaOpcionService;
}
/**
@ -154,6 +168,55 @@ public class PlantillaResource {
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.
*

View File

@ -2,15 +2,18 @@ package org.datasurvey.web.rest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.datasurvey.domain.Encuesta;
import org.datasurvey.domain.UsuarioEncuesta;
import org.datasurvey.domain.UsuarioExtra;
import org.datasurvey.repository.UsuarioEncuestaRepository;
import org.datasurvey.service.UsuarioEncuestaQueryService;
import org.datasurvey.service.UsuarioEncuestaService;
import org.datasurvey.service.*;
import org.datasurvey.service.criteria.UsuarioEncuestaCriteria;
import org.datasurvey.web.rest.errors.BadRequestAlertException;
import org.slf4j.Logger;
@ -36,19 +39,29 @@ public class UsuarioEncuestaResource {
private String applicationName;
private final UsuarioEncuestaService usuarioEncuestaService;
private final UsuarioExtraService usuarioExtraService;
private final EncuestaService encuestaService;
private final UsuarioEncuestaRepository usuarioEncuestaRepository;
private final UsuarioEncuestaQueryService usuarioEncuestaQueryService;
private final MailService mailService;
public UsuarioEncuestaResource(
UsuarioEncuestaService usuarioEncuestaService,
UsuarioEncuestaRepository usuarioEncuestaRepository,
UsuarioEncuestaQueryService usuarioEncuestaQueryService
UsuarioEncuestaQueryService usuarioEncuestaQueryService,
UsuarioExtraService usuarioExtraService,
EncuestaService encuestaService,
MailService mailService
) {
this.usuarioEncuestaService = usuarioEncuestaService;
this.usuarioEncuestaRepository = usuarioEncuestaRepository;
this.usuarioEncuestaQueryService = usuarioEncuestaQueryService;
this.usuarioExtraService = usuarioExtraService;
this.encuestaService = encuestaService;
this.mailService = mailService;
}
/**
@ -66,6 +79,9 @@ public class UsuarioEncuestaResource {
throw new BadRequestAlertException("A new usuarioEncuesta cannot already have an ID", ENTITY_NAME, "idexists");
}
UsuarioEncuesta result = usuarioEncuestaService.save(usuarioEncuesta);
if (result.getId() != null) {
mailService.sendInvitationColaborator(usuarioEncuesta);
}
return ResponseEntity
.created(new URI("/api/usuario-encuestas/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
@ -189,10 +205,40 @@ public class UsuarioEncuestaResource {
@DeleteMapping("/usuario-encuestas/{id}")
public ResponseEntity<Void> deleteUsuarioEncuesta(@PathVariable Long id) {
log.debug("REST request to delete UsuarioEncuesta : {}", id);
Optional<UsuarioEncuesta> usuarioEncuesta = usuarioEncuestaService.findOne(id);
usuarioEncuestaService.delete(id);
if (usuarioEncuesta != null) {
mailService.sendNotifyDeleteColaborator(usuarioEncuesta.get());
}
return ResponseEntity
.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
.build();
}
@GetMapping("/usuario-encuestas/encuesta/{id}")
public ResponseEntity<List<UsuarioEncuesta>> getColaboradores(@PathVariable Long id) {
List<UsuarioExtra> usuariosExtras = usuarioExtraService.findAll();
List<UsuarioEncuesta> usuariosEncuestas = usuarioEncuestaService
.findAll()
.stream()
.filter(uE -> Objects.nonNull(uE.getEncuesta()))
.filter(uE -> uE.getEncuesta().getId().equals(id))
.collect(Collectors.toList());
for (UsuarioEncuesta usuarioEncuesta : usuariosEncuestas) {
long usuarioExtraId = usuarioEncuesta.getUsuarioExtra().getId();
UsuarioExtra usuarioExtra = usuariosExtras.stream().filter(u -> u.getId() == usuarioExtraId).findFirst().get();
usuarioEncuesta.getUsuarioExtra().setNombre(usuarioExtra.getNombre());
usuarioEncuesta.getUsuarioExtra().setIconoPerfil(usuarioExtra.getIconoPerfil());
}
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,33 @@ email.suspended.text2=Saludos,
#PublicEncuesta
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.text2=Saludos,
#PrivateEncuesta
email.private.title=Su encuesta ha sido publicada de manera privada
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.greeting=¡Felicidades {0}!
email.private.text1=Su encuesta ha sdo publicada de manera privada. Su contraseña de acceso es: {0}
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=Eliminado de colaboración
email.deleteColaborator.greeting=Hola, {0}
email.deleteColaborator.text1=Le informamos que ya no cuenta con los permisos de colaborador para la encuesta {0}(#{1}), ya que su colaboración ha sido eliminada por el dueño de la encuesta"
email.deleteColaborator.text2=Saludos,
email.receipt.title=Comprobante de pago
email.receipt.user={0}
email.receipt.fecha={0}
email.receipt.plantilla={0}
email.receipt.precio=${0}

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,262 @@
<!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.receipt.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" />
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
crossorigin="anonymous"
/>
<style>
body {
margin-top: 20px;
color: #484b51;
}
.brc-default-l1 {
border-color: #dce9f0 !important;
}
.ml-n1,
.mx-n1 {
margin-left: -0.25rem !important;
}
.mr-n1,
.mx-n1 {
margin-right: -0.25rem !important;
}
.mb-4,
.my-4 {
margin-bottom: 1.5rem !important;
}
hr {
margin-top: 1rem;
margin-bottom: 1rem;
border: 0;
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.text-grey-m2 {
color: #888a8d !important;
}
.font-bolder,
.text-600 {
font-weight: 600 !important;
}
.text-110 {
font-size: 110% !important;
}
.text-blue {
color: #478fcc !important;
}
.pb-25,
.py-25 {
padding-bottom: 0.75rem !important;
}
.pt-25,
.py-25 {
padding-top: 0.75rem !important;
}
.bgc-default-tp1 {
background-color: rgba(121, 169, 197, 0.92) !important;
}
.page-header .page-tools {
-ms-flex-item-align: end;
align-self: flex-end;
}
.text-blue-m2 {
color: #68a3d5 !important;
}
.text-150 {
font-size: 150% !important;
}
</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 -->
<!-- end tr -->
<div class="page-content container">
<div class="container px-0">
<div class="row mt-4">
<div class="col-12 col-lg-10 offset-lg-1">
<!-- .row -->
<hr class="row brc-default-l1 mx-n1 mb-4" />
<div class="row">
<div class="col-sm-6">
<div>
<span class="text-sm text-grey-m2 align-middle">Usuario:</span>
<span
class="text-600 text-110 text-blue align-middle"
th:text="#{email.receipt.user(${factura.getNombreUsuario()})}"
></span>
</div>
</div>
<!-- /.col -->
<div class="text-95 col-sm-6 align-self-start d-sm-flex justify-content-end">
<hr class="d-sm-none" />
<div class="text-grey-m2">
<div class="my-2">
<i class="fa fa-circle text-blue-m2 text-xs mr-1"></i>
<span class="text-600 text-90" th:text="#{email.receipt.fecha(${factura.getFecha()}, 'dd-MM-yyyy HH:mm' )}"
>Fecha:</span
>
</div>
</div>
</div>
<!-- /.col -->
</div>
<div class="mt-4">
<div class="row text-600 text-white bgc-default-tp1 py-25">
<div class="col-9 col-sm-5">Plantilla</div>
<div class="d-none d-sm-block col-4 col-sm-2">Cantidad</div>
<div class="d-none d-sm-block col-sm-2">Precio</div>
</div>
<div class="text-95 text-secondary-d3">
<div class="row mb-2 mb-sm-0 py-25">
<div class="col-9 col-sm-5" th:text="#{email.receipt.plantilla(${factura.getNombrePlantilla()})}"></div>
<div class="d-none d-sm-block col-2">1</div>
<div class="d-none d-sm-block col-2 text-95" th:text="#{email.receipt.precio(${factura.getCosto()})}"></div>
</div>
</div>
</div>
<div class="row mt-3">
<div class="col-12 col-sm-5 text-grey text-90 order-first order-sm-last">
<div class="row my-2 align-items-center bgc-primary-l3 p-2">
<div class="col-7 text-right">Monto total</div>
<div class="col-5">
<span class="text-150 text-success-d3 opacity-2" th:text="#{email.receipt.precio(${factura.getCosto()})}"></span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 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>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.4.1/cjs/popper.min.js"
integrity="sha256-T3bYsIPyOLpEfeZOX4M7J59ZoDMzuYFUsPiSN3Xcc2M="
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
crossorigin="anonymous"
></script>
</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

@ -38,8 +38,8 @@
</div>
<div class="d-flex justify-content-center">
<button class="ds-btn ds-btn--primary" routerLink="/login" jhiTranslate="global.messages.info.authenticated.botonInicio">
sign in</button
>.
sign in
</button>
</div>
</div>

View File

@ -91,7 +91,7 @@ export class RegisterComponent implements AfterViewInit {
login,
email,
password,
langKey: this.translateService.currentLang,
langKey: this.translateService.currentLang!,
name,
firstName,
profileIcon: this.profileIcon,

View File

@ -33,6 +33,12 @@ import { PageRibbonComponent } from './layouts/profiles/page-ribbon.component';
import { ErrorComponent } from './layouts/error/error.component';
import { SidebarComponent } from './layouts/sidebar/sidebar.component';
import { PaginaPrincipalComponent } from './pagina-principal/pagina-principal.component';
import { ChartistModule } from 'ng-chartist';
import { ListarPlantillaTiendaModule } from './entities/tienda/listar-tienda-plantilla/listar-plantilla-tienda.module';
import { PaypalDialogComponent } from './entities/tienda/paypal-dialog/paypal-dialog.component';
import { NgxPayPalModule } from 'ngx-paypal';
import { ShareButtonsModule } from 'ngx-sharebuttons/buttons';
import { ShareIconsModule } from 'ngx-sharebuttons/icons';
@NgModule({
imports: [
@ -41,6 +47,7 @@ import { PaginaPrincipalComponent } from './pagina-principal/pagina-principal.co
SharedModule,
HomeModule,
PaginaPrincipalModule,
ListarPlantillaTiendaModule,
// jhipster-needle-angular-add-module JHipster will add new module here
EntityRoutingModule,
AppRoutingModule,
@ -60,6 +67,10 @@ import { PaginaPrincipalComponent } from './pagina-principal/pagina-principal.co
useFactory: missingTranslationHandler,
},
}),
ChartistModule, // add ChartistModule to your imports
ShareButtonsModule,
ShareIconsModule,
NgxPayPalModule,
],
providers: [
Title,
@ -79,7 +90,15 @@ import { PaginaPrincipalComponent } from './pagina-principal/pagina-principal.co
} as SocialAuthServiceConfig,
},
],
declarations: [MainComponent, NavbarComponent, ErrorComponent, PageRibbonComponent, FooterComponent, SidebarComponent],
declarations: [
MainComponent,
NavbarComponent,
ErrorComponent,
PageRibbonComponent,
FooterComponent,
SidebarComponent,
PaypalDialogComponent,
],
bootstrap: [MainComponent],
})
export class AppModule {

View File

@ -19,7 +19,7 @@
<fa-icon icon="arrow-left"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button id="jhi-confirm-delete-categoria" data-cy="entityConfirmDeleteButton" type="submit" class="ds-btn ds-btn--danger">
<button id="jhi-confirm-delete-categoria" data-cy="entityConfirmDeleteButton" type="submit" class="ds-btn ds-btn--toggle">
<fa-icon [icon]="faExchangeAlt"></fa-icon>
<span jhiTranslate="entity.action.toggleStatus">Toggle Status</span>
</button>

View File

@ -5,7 +5,7 @@ import { IEncuesta } from 'app/entities/encuesta/encuesta.model';
import { EncuestaService } from 'app/entities/encuesta/service/encuesta.service';
import { EstadoCategoria } from 'app/entities/enumerations/estado-categoria.model';
import { Observable } from 'rxjs';
import { finalize, map } from 'rxjs/operators';
import { finalize } from 'rxjs/operators';
import { Categoria, ICategoria } from '../categoria.model';
import { CategoriaService } from '../service/categoria.service';
@ -42,7 +42,7 @@ export class CategoriaDeleteDialogComponent {
this.encuestas!.forEach(encuesta => {
if (encuesta.categoria != null && encuesta.categoria!.id === categoria.id) {
encuesta.categoria = categoriaNula;
this.subscribeToSaveResponse(this.encuestaService.update(encuesta));
this.subscribeToSaveResponse(this.encuestaService.updateSurvey(encuesta));
}
});
categoria.estado = EstadoCategoria.INACTIVE;

View File

@ -44,7 +44,7 @@
<input type="text" name="searchString" placeholder="Buscar..." [(ngModel)]="searchString" />
</div>
</form>
<table class="table table-striped" aria-describedby="page-heading">
<table class="ds-table table table-striped" aria-describedby="page-heading">
<thead>
<tr>
<th scope="col"><span jhiTranslate="dataSurveyApp.categoria.nombre">Nombre</span></th>
@ -67,7 +67,7 @@
<span class="d-none d-md-inline" jhiTranslate="entity.action.edit">Edit</span>
</button>
<button type="submit" (click)="toggleStatus(categoria)" class="ds-btn ds-btn--danger" data-cy="entityDeleteButton">
<button type="submit" (click)="toggleStatus(categoria)" class="ds-btn ds-btn--toggle" data-cy="entityDeleteButton">
<fa-icon [icon]="faExchangeAlt"></fa-icon>
<span class="d-none d-md-inline" jhiTranslate="entity.action.toggleStatus">Toggle Status</span>
</button>

View File

@ -0,0 +1,246 @@
<div class="content">
<div class="py-2">
<button type="button" class="ds-btn ds-btn--primary" (click)="exportReportesGeneralesAdministradorExcel()">Export as Excel</button>
<button type="button" class="ds-btn ds-btn--primary" (click)="exportReportesGeneralesAdministradorPDF()">Export as PDF</button>
<button type="button" [hidden]="reportsGeneral" class="ds-btn ds-btn--primary" style="float: right" (click)="cambiarVista()">
Ver Reporte de Usuarios
</button>
<button type="button" [hidden]="reportForUsers" class="ds-btn ds-btn--primary" style="float: right" (click)="cambiarVista()">
Ver Reporte Generales
</button>
</div>
<div class="container-fluid py-5" [hidden]="reportsGeneral">
<div class="row justify-content-around">
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-content">
<div class="row">
<div class="col-xs-5 w-25 px-1">
<div class="icon-big icon-success text-center">
<fa-icon [icon]="faWallet"></fa-icon>
</div>
</div>
<div class="col-xs-7 w-50">
<div class="numbers">
<p class="ds-title">Ganancias por plantillas</p>
${{ gananciasTotales | number: '1.2' }}
</div>
</div>
</div>
</div>
<div class="card-footer">
<hr />
<br />
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-content">
<div class="row justify-content-center">
<div class="col-xs-5 w-25 px-1">
<div class="icon-big icon-users-active text-center">
<fa-icon [icon]="faUsers"></fa-icon>
</div>
</div>
<div class="col-xs-7 w-75">
<div class="numbers">
<p class="ds-title">Cantidad usuarios activos</p>
{{ cantUsuarioActivos }}
</div>
</div>
</div>
</div>
<div class="card-footer">
<hr />
<br />
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-content">
<div class="row justify-content-center">
<div class="col-xs-4 w-25 px-1">
<div class="icon-big icon-users-block text-center">
<fa-icon [icon]="faUsersSlash"></fa-icon>
</div>
</div>
<div class="col-xs-5 w-75">
<div class="numbers">
<p class="ds-title">Cantidad usuarios bloqueados</p>
{{ cantUsuarioBloqueados }}
</div>
</div>
</div>
</div>
<div class="card-footer">
<hr />
<br />
</div>
</div>
</div>
</div>
<div class="row justify-content-around por-categoria">
<div class="col-md-5">
<div class="grafico-encuestas-fecha">
<div class="card">
<h1 class="ds-title">Cantidad de encuestas publicadas por mes</h1>
<div class="ct-chart ct-chart-line"></div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card encuestas-por-categoria">
<div class="card-header w-100">
<h4 class="ds-title">Cantidad de Encuestas Publicadas por Categoria</h4>
</div>
<div class="card-content">
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table">
<tbody>
<tr *ngFor="let categoria of categorias; let i = index; trackBy: trackId">
<td>{{ categoria.nombre }}</td>
<td class="text-right">
{{ encuestasPublicadasCategoria[i] }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card encuestas-por-categoria">
<div class="card-header w-100">
<h4 class="ds-title">Cantidad de Encuestas Finalizadas por Categoria</h4>
</div>
<div class="card-content">
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table">
<tbody>
<tr *ngFor="let categoria of categorias; let i = index; trackBy: trackId">
<td>{{ categoria.nombre }}</td>
<td class="text-right">
{{ encuestasFinalzadasCategoria[i] }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-3 col-sm-6">
<div class="card card-circle-chart" data-background-color="blue" style="background-color: #88c5d6eb">
<div class="card-header text-center">
<h5 class="card-title ds-subtitle" style="color: #082463">Encuestas En Borrador</h5>
</div>
<div class="card-content">
<div id="surveyDraft" class="chart-circle">{{ encuestasBorrador }}<canvas height="160" width="160"></canvas></div>
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card card-circle-chart" data-background-color="green" style="background-color: #67ceb6">
<div class="card-header text-center">
<h5 class="card-title ds-subtitle" style="color: #0a2922">Encuestas Publicadas</h5>
</div>
<div class="card-content">
<div id="surveyActive" class="chart-circle">{{ encuestasPublicadas }}<canvas height="160" width="160"></canvas></div>
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card card-circle-chart" style="background-color: #de8e78">
<div class="card-header text-center">
<h5 class="card-title ds-subtitle" style="color: #671a04">Encuestas Finalizadas</h5>
</div>
<div class="card-content">
<div id="surveyFinished" class="chart-circle">{{ encuestasFinalizadas }}<canvas height="160" width="160"></canvas></div>
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card card-circle-chart" data-background-color="brown" style="background-color: #d6c1ab">
<div class="card-header text-center">
<h5 class="card-title ds-subtitle" style="color: #252422">Encuestas Completadas por Usuarios</h5>
</div>
<div class="card-content">
<div id="surveyCountCompletede" class="chart-circle">{{ encuestasCompletadas }}<canvas height="160" width="160"></canvas></div>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid" [hidden]="reportForUsers">
<div class="row justify-content-around">
<div class="col-md-10">
<div class="card encuestas-por-usuario">
<div class="card-header w-100">
<h4 class="ds-title">Reporte de Encuestas Usuarios</h4>
</div>
<div class="card-content">
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Usuario</th>
<th></th>
<th>Total de encuestas</th>
<th>Encuestas en borrador</th>
<th>Encuestas publicadas</th>
<th>Encuestas finalizadas</th>
<th>Encuestas completadas por usuario</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let usuario of usuarios; let j = index; trackBy: trackIdUsuario">
<td>
<div class="photo mb-2"><img src="../../../../content/profile_icons/C{{ usuario.iconoPerfil }}.png" /></div>
</td>
<td>{{ usuario.nombre }}</td>
<td class="text-center">
{{ encuestasUsuario[j] }}
</td>
<td class="text-center">
{{ encuestasUsuarioBorrador[j] }}
</td>
<td class="text-center">
{{ encuestasUsuarioPublicadas[j] }}
</td>
<td class="text-center">
{{ encuestasUsuarioFinalizadas[j] }}
</td>
<td class="text-center">
{{ encuestasUsuarioCompletadas[j] }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@ -0,0 +1,46 @@
.ct-chart {
width: 100%;
height: 400px;
overflow-x: scroll;
}
.grafico-encuestas-fecha .card {
width: 100%;
}
.card .icon-big {
font-size: 3em;
}
.icon-success {
color: #00b88d;
}
.icon-users-active {
color: #018adf;
}
.icon-users-block {
color: #da1b2b;
}
.encuestas-por-categoria .table-responsive {
height: 300px;
max-height: 300px;
}
.por-categoria {
padding: 5% 0;
}
.encuestas-por-usuario .table-responsive {
height: 500px;
max-height: 500px;
}
.encuestas-por-usuario .photo {
width: 40px;
height: 40px;
}
.encuestas-por-usuario .photo img {
border-radius: 100%;
}

View File

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

View File

@ -0,0 +1,534 @@
import { Component, OnInit } from '@angular/core';
import * as XLSX from 'xlsx';
import * as FileSaver from 'file-saver';
import { jsPDF } from 'jspdf';
import { exportAsExcelFile, exportAsExcelTable } from '../export/export_excel';
import { generatePDFTableData, createPDFTableHeaders, generatePDFTable, saveGeneratedPDF } from '../export/export_pdf';
import { FacturaService } from '../../factura/service/factura.service';
import { UsuarioExtraService } from '../../usuario-extra/service/usuario-extra.service';
import { CategoriaService } from '../../categoria/service/categoria.service';
import { EncuestaService } from '../../encuesta/service/encuesta.service';
import { ICategoria } from '../../categoria/categoria.model';
import { IEncuesta } from '../../encuesta/encuesta.model';
import { finalize } from 'rxjs/operators';
import * as Chartist from 'chartist';
import { faWallet, faUsers, faUsersSlash } from '@fortawesome/free-solid-svg-icons';
import { IUsuarioExtra } from '../../usuario-extra/usuario-extra.model';
import { IUser } from '../../user/user.model';
@Component({
selector: 'jhi-dashboard-admin',
templateUrl: './dashboard-admin.component.html',
styleUrls: ['./dashboard-admin.component.scss'],
})
export class DashboardAdminComponent implements OnInit {
cantUsuarioActivos: number | undefined = 0;
cantUsuarioBloqueados: number | undefined = 0;
encuestasPublicadasCategoria: number[] = [];
encuestasFinalzadasCategoria: number[] = [];
encuestasPublicadasMesAnno: number[] = [];
listaMesesAnnos: string[] = [];
gananciasTotales: number = 0;
categorias: ICategoria[] | undefined = [];
encuestas: IEncuesta[] | undefined = [];
usuarios: IUsuarioExtra[] | undefined = [];
faWallet = faWallet;
faUsers = faUsers;
faUsersSlash = faUsersSlash;
encuestasPublicadas: number = 0;
encuestasFinalizadas: number = 0;
encuestasBorrador: number = 0;
encuestasCompletadas: number = 0;
encuestasUsuario: number[] = [];
encuestasUsuarioPublicadas: number[] = [];
encuestasUsuarioFinalizadas: number[] = [];
encuestasUsuarioBorrador: number[] = [];
encuestasUsuarioCompletadas: number[] = [];
usuariosGenerales: IUser[] | null = [];
reportsGeneral = false;
reportForUsers = true;
chartFechas = [];
constructor(
protected facturaService: FacturaService,
protected usuarioExtraService: UsuarioExtraService,
protected encuestaService: EncuestaService,
protected categoriaService: CategoriaService
) {}
ngOnInit(): void {
this.loadAll();
}
trackId(_index: number, item: ICategoria): number {
return item.id!;
}
trackIdUsuario(_index: number, item: IUsuarioExtra): number {
return item.id!;
}
cambiarVista() {
if (this.reportsGeneral) {
this.reportsGeneral = false;
this.reportForUsers = true;
} else if (this.reportForUsers) {
this.reportsGeneral = true;
this.reportForUsers = false;
}
}
loadAll() {
this.cargarGananciasTotales();
this.cargarUsers();
}
cargarGananciasTotales() {
this.facturaService.query().subscribe(res => {
const tempFacturas = res.body;
tempFacturas?.forEach(f => {
if (f.costo != undefined) {
this.gananciasTotales += f.costo;
}
});
});
}
cargarUsers() {
this.usuarioExtraService
.retrieveAllPublicUsers()
.pipe(finalize(() => this.cargarCantidadUsuarios()))
.subscribe(res => {
res.forEach(user => {
let rolList: string[] | undefined;
rolList = user.authorities;
let a = rolList?.pop();
if (a == 'ROLE_ADMIN') {
user.authorities = ['Admin'];
} else if (a == 'ROLE_USER') {
user.authorities = ['Usuario'];
}
});
this.usuariosGenerales = res;
});
}
cargarCantidadUsuarios() {
this.usuarioExtraService
.query()
.pipe(finalize(() => this.cargarEncuestas()))
.subscribe(res => {
const tmpUsuarios = res.body;
if (tmpUsuarios) {
tmpUsuarios.forEach(u => {
u.user = this.usuariosGenerales?.find(g => g.id == u.user?.id);
});
}
this.usuarios = tmpUsuarios?.filter(u => u.user?.authorities && u.user?.authorities[0] === 'Usuario');
this.cantUsuarioActivos = tmpUsuarios?.filter(u => u.estado === 'ACTIVE').length;
this.cantUsuarioBloqueados = tmpUsuarios?.filter(u => u.estado === 'SUSPENDED').length;
});
}
cargarEncuestas() {
this.encuestaService
.query()
.pipe(finalize(() => this.cargarCategorias()))
.subscribe(res => {
const tmpEncuestas = res.body;
this.encuestas = tmpEncuestas?.filter(e => e.estado === 'ACTIVE' || e.estado === 'FINISHED' || e.estado === 'DRAFT');
if (tmpEncuestas) {
this.encuestasPublicadas = tmpEncuestas.filter(e => e.estado === 'ACTIVE').length;
this.encuestasFinalizadas = tmpEncuestas.filter(e => e.estado === 'FINISHED').length;
this.encuestasBorrador = tmpEncuestas.filter(e => e.estado === 'DRAFT').length;
let cantidadCompletadas: number = 0;
tmpEncuestas
.filter(e => e.estado === 'ACTIVE')
.forEach(e => {
const _contadorCompletadas = e.calificacion;
cantidadCompletadas = cantidadCompletadas + (Number(_contadorCompletadas?.toString().split('.')[1]) - 1);
});
this.encuestasCompletadas = cantidadCompletadas;
//reportes generales de todos los usuarios
const publicadasUser: number[] | null = [];
const finalizadasUser: number[] | null = [];
const borradoresUser: number[] | null = [];
const encuestasUser: number[] | null = [];
const encuestasCompletadasUser: number[] | null = [];
if (this.usuarios) {
this.usuarios.forEach(u => {
let cantEncuestas = 0;
let cantPublicadas = 0;
let cantFinalizadas = 0;
let cantBorradores = 0;
cantEncuestas = tmpEncuestas.filter(e => e.estado !== 'DELETED' && e.usuarioExtra?.id === u.id).length;
cantPublicadas = tmpEncuestas.filter(e => e.estado === 'ACTIVE' && e.usuarioExtra?.id === u.id).length;
cantFinalizadas = tmpEncuestas.filter(e => e.estado === 'FINISHED' && e.usuarioExtra?.id === u.id).length;
cantBorradores = tmpEncuestas.filter(e => e.estado === 'DRAFT' && e.usuarioExtra?.id === u.id).length;
encuestasUser.push(cantEncuestas);
borradoresUser.push(cantBorradores);
publicadasUser.push(cantPublicadas);
finalizadasUser.push(cantFinalizadas);
let cantidadCompletadasUser: number = 0;
tmpEncuestas
.filter(e => e.estado === 'ACTIVE' && e.usuarioExtra?.id === u.id)
.forEach(e => {
const _contadorCompletadas = e.calificacion;
cantidadCompletadasUser = cantidadCompletadasUser + (Number(_contadorCompletadas?.toString().split('.')[1]) - 1);
});
encuestasCompletadasUser.push(cantidadCompletadasUser);
});
this.encuestasUsuarioCompletadas = encuestasCompletadasUser;
this.encuestasUsuario = encuestasUser;
this.encuestasUsuarioBorrador = borradoresUser;
this.encuestasUsuarioPublicadas = publicadasUser;
this.encuestasUsuarioFinalizadas = finalizadasUser;
}
}
});
}
cargarCategorias() {
this.categoriaService
.query()
.pipe(finalize(() => this.acomodarMesesYAnnos()))
.subscribe(res => {
const tmpCategorias = res.body;
this.categorias = tmpCategorias?.filter(c => c.estado === 'ACTIVE');
const publicadas: number[] | null = [];
const finalizadas: number[] | null = [];
this.categorias?.forEach(c => {
let cantPublicadas = 0;
let cantFinalizadas = 0;
this.encuestas?.forEach(e => {
if (e.categoria?.id === c.id && e.estado === 'ACTIVE') {
cantPublicadas = cantPublicadas + 1;
}
if (e.categoria?.id === c.id && e.estado === 'FINISHED') {
cantFinalizadas = cantFinalizadas + 1;
}
});
publicadas.push(cantPublicadas);
finalizadas.push(cantFinalizadas);
});
this.encuestasPublicadasCategoria = publicadas;
this.encuestasFinalzadasCategoria = finalizadas;
});
}
acomodarMesesYAnnos() {
const fechas: string[] | null = [];
const cantEncuestasFechas: number[] | null = [];
var encuestasPublicadas = this.encuestas?.filter(e => e.estado === 'ACTIVE');
if (encuestasPublicadas) {
encuestasPublicadas = this.ordenarFechas(encuestasPublicadas);
encuestasPublicadas.forEach(e => {
if (e.fechaPublicacion) {
let fecha = this.formatoFecha(e.fechaPublicacion);
if (!fechas.includes(fecha)) {
fechas.push(fecha);
}
}
});
this.listaMesesAnnos = fechas;
this.listaMesesAnnos.forEach(f => {
let contEncuestaDeFecha = 0;
if (encuestasPublicadas) {
encuestasPublicadas.forEach(e => {
if (e.fechaPublicacion) {
let fecha = this.formatoFecha(e.fechaPublicacion);
if (f === fecha) {
contEncuestaDeFecha++;
}
}
});
}
cantEncuestasFechas.push(contEncuestaDeFecha);
});
this.encuestasPublicadasMesAnno = cantEncuestasFechas;
}
this.llenarGraficoEncuestasXFechas();
}
llenarGraficoEncuestasXFechas() {
if (this.listaMesesAnnos && this.encuestasPublicadasMesAnno) {
var data = {
// A labels array that can contain any sort of values
labels: this.listaMesesAnnos,
// Our series array that contains series objects or in this case series data arrays
series: [this.encuestasPublicadasMesAnno],
};
var options = {
low: 0,
showArea: true,
showLabel: true,
axisY: {
onlyInteger: true,
},
};
new Chartist.Line('.ct-chart', data, options);
}
}
formatoFecha(fecha: any): string {
return fecha.month() + 1 + '/' + fecha.year();
}
ordenarFechas(encuestasPublicadas: IEncuesta[]): IEncuesta[] {
if (encuestasPublicadas) {
encuestasPublicadas.sort((e1, e2) => {
if (e1.fechaPublicacion && e2.fechaPublicacion) {
return e1.fechaPublicacion < e2.fechaPublicacion ? -1 : e1.fechaPublicacion > e2.fechaPublicacion ? 1 : 0;
}
return 0;
});
}
return encuestasPublicadas;
}
exportReportesGeneralesAdministradorExcel(): void {
/*
Cantidad de usuarios activos
Cantidad de usuarios bloqueados
Cantidad de encuestas publicadas por categoría
Cantidad de encuestas finalizadas por categoría
Cantidad de encuestas publicadas por mes y año
Cantidad de encuestas
Cantidad de personas que han completado sus encuestas
Cantidad de encuestas activas
Cantidad de encuestas finalizadas
Cantidad de comentarios de retroalimentación
*/
const _sheets = [
'usuarios generales',
'enc. publicadas',
'enc. publicadas categoría',
'enc. finalizadas categoría',
'encuestas generales',
'reporte de usuarios',
];
const _reporteUsuarios = [
{
ganancias_plantillas: this.gananciasTotales,
usuarios_activos: this.cantUsuarioActivos,
usuarios_bloqueados: this.cantUsuarioBloqueados,
},
];
// listaMesesAnnos
// encuestasPublicadasMesAnno
const _reporteEncuestasPublicadas: any[] = [];
this.listaMesesAnnos.forEach((date: any, index) => {
let _report: any = {};
_report['fecha'] = date;
_report['cantidad'] = this.encuestasPublicadasMesAnno[index];
_reporteEncuestasPublicadas.push(_report);
});
// this.categorias
// this.encuestasPublicadasCategoria
const _reporteCantidadEncuestasPublicadasCategoria: any[] = [];
this.categorias!.forEach((categoria: any, index) => {
let _report: any = {};
_report['categoria'] = categoria.nombre;
_report['cantidad'] = this.encuestasPublicadasCategoria[index];
_reporteCantidadEncuestasPublicadasCategoria.push(_report);
});
// this.categorias
// this.encuestasFinalzadasCategoria
const _reporteCantidadEncuestasFinalizadasCategoria: any[] = [];
this.categorias!.forEach((categoria: any, index) => {
let _report: any = {};
_report['categoria'] = categoria.nombre;
_report['cantidad'] = this.encuestasFinalzadasCategoria[index];
_reporteCantidadEncuestasFinalizadasCategoria.push(_report);
});
// this.encuestasPublicadas
// this.encuestasFinalizadas
// this.encuestasBorrador
// this.encuestasCompletadas
const _reporteEncuestasReportesGenerales = [
{
encuestas_borrador: this.encuestasBorrador,
encuestas_publicadas: this.encuestasPublicadas,
encuestas_finalizadas: this.encuestasFinalizadas,
encuestas_completadas: this.encuestasCompletadas,
},
];
// this.encuestasUsuario;
// this.encuestasUsuarioPublicadas;
// this.encuestasUsuarioFinalizadas;
// this.encuestasUsuarioBorrador;
// this.encuestasUsuarioCompletadas;
// this.usuarios;
const _reporteEncuestasUsuarios: any[] = [];
this.usuarios!.forEach((user, index) => {
let _report: any = {};
_report['usuario_nombre'] = user.nombre;
_report['usuario_encuestas'] = this.encuestasUsuario[index];
_report['encuestas_borrador'] = this.encuestasUsuarioBorrador[index];
_report['encuestas_publicadas'] = this.encuestasUsuarioPublicadas[index];
_report['encuestas_finalizadas'] = this.encuestasUsuarioFinalizadas[index];
_report['encuestas_completadas_usuarios'] = this.encuestasUsuarioCompletadas[index];
_reporteEncuestasUsuarios.push(_report);
});
const _excelFinalData = [
_reporteUsuarios,
_reporteEncuestasPublicadas,
_reporteCantidadEncuestasPublicadasCategoria,
_reporteCantidadEncuestasFinalizadasCategoria,
_reporteEncuestasReportesGenerales,
_reporteEncuestasUsuarios,
];
const _fileName = 'reportes_datasurvey';
exportAsExcelFile(_sheets, _excelFinalData, _fileName);
}
exportReportesGeneralesAdministradorPDF(): void {
/*
Cantidad de usuarios activos
Cantidad de usuarios bloqueados
Cantidad de encuestas publicadas por categoría
Cantidad de encuestas finalizadas por categoría
Cantidad de encuestas publicadas por mes y año
Cantidad de encuestas
Cantidad de personas que han completado sus encuestas
Cantidad de encuestas activas
Cantidad de encuestas finalizadas
Cantidad de comentarios de retroalimentación
*/
const doc = new jsPDF();
const _fileName = 'reportes_datasurvey';
let _docData, _headers, _docHeaders, _docTitle;
// Usuarios Generales
const _reporteUsuarios = [
{
ganancias_plantillas: this.gananciasTotales!.toString(),
usuarios_activos: this.cantUsuarioActivos!.toString(),
usuarios_bloqueados: this.cantUsuarioBloqueados!.toString(),
},
];
_docData = generatePDFTableData(_reporteUsuarios);
_headers = ['ganancias_plantillas', 'usuarios_activos', 'usuarios_bloqueados'];
_docHeaders = createPDFTableHeaders(_headers);
_docTitle = 'Reporte Usuarios Generales';
generatePDFTable(doc, _docData, _docHeaders, _docTitle);
doc.addPage('p');
// Encuestas Publicadas
const _reporteEncuestasPublicadas: any[] = [];
this.listaMesesAnnos.forEach((date: any, index) => {
let _report: any = {};
_report['fecha'] = date;
_report['cantidad'] = this.encuestasPublicadasMesAnno[index].toString();
_reporteEncuestasPublicadas.push(_report);
});
_docData = generatePDFTableData(_reporteEncuestasPublicadas);
_headers = ['fecha', 'cantidad'];
_docHeaders = createPDFTableHeaders(_headers);
_docTitle = 'Reporte Encuestas Publicadas';
generatePDFTable(doc, _docData, _docHeaders, _docTitle);
doc.addPage('p');
// Encuestas Publicadas
const _reporteCantidadEncuestasPublicadasCategoria: any[] = [];
this.categorias!.forEach((categoria: any, index) => {
let _report: any = {};
_report['categoria'] = categoria.nombre;
_report['cantidad'] = this.encuestasPublicadasCategoria[index].toString();
_reporteCantidadEncuestasPublicadasCategoria.push(_report);
});
_docData = generatePDFTableData(_reporteCantidadEncuestasPublicadasCategoria);
_headers = ['categoria', 'cantidad'];
_docHeaders = createPDFTableHeaders(_headers);
_docTitle = 'Reporte Encuestas Publicadas por Categoría';
generatePDFTable(doc, _docData, _docHeaders, _docTitle);
doc.addPage('p');
// Encuestas Publicadas
const _reporteCantidadEncuestasFinalizadasCategoria: any[] = [];
this.categorias!.forEach((categoria: any, index) => {
let _report: any = {};
_report['categoria'] = categoria.nombre;
_report['cantidad'] = this.encuestasFinalzadasCategoria[index].toString();
_reporteCantidadEncuestasFinalizadasCategoria.push(_report);
});
_docData = generatePDFTableData(_reporteCantidadEncuestasFinalizadasCategoria);
_headers = ['categoria', 'cantidad'];
_docHeaders = createPDFTableHeaders(_headers);
_docTitle = 'Reporte Encuestas Finalizadas por Categoría';
generatePDFTable(doc, _docData, _docHeaders, _docTitle);
doc.addPage('', 'l');
// Encuestas Generales
const _reporteEncuestasReportesGenerales = [
{
encuestas_borrador: this.encuestasBorrador.toString(),
encuestas_publicadas: this.encuestasPublicadas.toString(),
encuestas_finalizadas: this.encuestasFinalizadas.toString(),
encuestas_completadas: this.encuestasCompletadas.toString(),
},
];
_docData = generatePDFTableData(_reporteEncuestasReportesGenerales);
_headers = ['encuestas_borrador', 'encuestas_publicadas', 'encuestas_finalizadas', 'encuestas_completadas'];
_docHeaders = createPDFTableHeaders(_headers);
_docTitle = 'Reporte Encuestas Generales';
generatePDFTable(doc, _docData, _docHeaders, _docTitle);
doc.addPage('', 'l');
// Usuarios
const _reporteEncuestasUsuarios: any[] = [];
this.usuarios!.forEach((user, index) => {
let _report: any = {};
_report['usuario_nombre'] = user.nombre;
_report['usuario_encuestas'] = this.encuestasUsuario[index].toString();
_report['encuestas_borrador'] = this.encuestasUsuarioBorrador[index].toString();
_report['encuestas_publicadas'] = this.encuestasUsuarioPublicadas[index].toString();
_report['encuestas_finalizadas'] = this.encuestasUsuarioFinalizadas[index].toString();
_report['encuestas_completadas_usuarios'] = this.encuestasUsuarioCompletadas[index].toString();
_reporteEncuestasUsuarios.push(_report);
});
_docData = generatePDFTableData(_reporteEncuestasUsuarios);
_headers = [
'usuario_nombre',
'usuario_encuestas',
'encuestas_borrador',
'encuestas_publicadas',
'encuestas_finalizadas',
'encuestas_completadas_usuarios',
];
_docHeaders = createPDFTableHeaders(_headers);
_docTitle = 'Reporte de Usuarios';
generatePDFTable(doc, _docData, _docHeaders, _docTitle);
saveGeneratedPDF(doc, _fileName);
}
}

View File

@ -0,0 +1,266 @@
<div class="content">
<div class="py-2">
<!--<button type="button" class="ds-btn ds-btn&#45;&#45;primary" (click)="exportReportesGeneralesUserExcel()">Exportar como Excel</button>
<button type="button" class="ds-btn ds-btn&#45;&#45;primary" (click)="exportReportesGeneralesUserPDF()">Exportar como PDF</button>-->
<button
type="button"
[hidden]="!reportsGeneral || reportForEncuestas"
class="ds-btn ds-btn--primary"
style="float: right"
(click)="cambiarVista()"
>
Ver reportes generales
</button>
<button
type="button"
[hidden]="!reportForEncuestas || reportsGeneral"
class="ds-btn ds-btn--primary"
style="float: right"
(click)="cambiarVista()"
>
Ver reportes por encuestas
</button>
<button type="button" [hidden]="reportPreguntas" class="ds-btn ds-btn--primary" style="float: right" (click)="cambiarVista()">
Volver
</button>
</div>
<div class="container-fluid">
<div class="py-2" [hidden]="reportsGeneral">
<h1>Reportes generales</h1>
<h2>En esta sección encontrará los reportes generales de todas sus encuestas</h2>
</div>
<div class="py-2" [hidden]="reportForEncuestas">
<h1>Reportes por encuesta</h1>
<h2>En esta sección encontrará los reportes de cada una de sus encuestas</h2>
</div>
<div class="py-2" [hidden]="reportPreguntas">
<h1>Detalles de la encuesta</h1>
<h2>En esta sección encontrará los reportes con respecto al contenido de las preguntas de su encuesta</h2>
</div>
<hr />
<!--REPORTES GENERALES-->
<div class="container-fluid py-5" [hidden]="reportsGeneral">
<div class="">
<div class="row justify-content-around">
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-content">
<div class="row">
<div class="col-xs-5 w-25 px-1">
<div class="icon-big icon-success text-center">
<fa-icon [icon]="faListAlt"></fa-icon>
</div>
</div>
<div class="col-xs-7 w-50">
<div class="numbers">
<p class="ds-title--small">Cantidad de encuestas creadas</p>
{{ cantEncuestas }}
</div>
</div>
</div>
</div>
<div class="card-footer">
<hr />
<br />
</div>
</div>
</div>
<div class="col-lg-3 col-sm-6">
<div class="card">
<div class="card-content">
<div class="row">
<div class="col-xs-5 w-25 px-1">
<div class="icon-big icon-users-active text-center">
<fa-icon [icon]="faUser"></fa-icon>
</div>
</div>
<div class="col-xs-7 w-50">
<div class="numbers">
<p class="ds-title--small">Cantidad de usuario que han completado las encuestas</p>
{{ cantPersonas }}
</div>
</div>
</div>
</div>
<div class="card-footer">
<hr />
<br />
</div>
</div>
</div>
</div>
<div class="row justify-content-around por-categoria">
<div class="col-md-5">
<div class="grafico-encuestas-fecha">
<div class="card" height="300" width="300">
<h1 class="ds-title">Cantidad de encuestas por estado</h1>
<div id="chartEstado" class="ct-chart ct-major-tenth"></div>
</div>
</div>
</div>
<div class="col-md-5">
<div class="grafico-encuestas-fecha">
<div class="card" height="300" width="300">
<h1 class="ds-title">Cantidad de encuestas por acceso</h1>
<div id="chartAcceso" class="ct-chart ct-major-tenth"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--REPORTE POR ENCUESTA-->
<div class="container-fluid" [hidden]="reportForEncuestas">
<div class="row gx-5" *ngIf="encuestas && encuestas.length > 0">
<div class="col-xl-4 col-lg-4 col-md-6 mb-5" *ngFor="let encuesta of encuestas">
<div class="card-encuesta lift h-100" [attr.data-id]="encuesta.id">
<div class="card-body p-3">
<div class="card-title mb-0">{{ encuesta.nombre }}</div>
<div class="entity-body--row m-2">
<span class="tag mt-2">{{ encuesta.categoria?.nombre | lowercase }}</span>
</div>
<div class="entity-body--row m-2">
<span class="subtitle mt-2">{{ encuesta.descripcion | titlecase }}</span>
</div>
<div class="text-xs text-gray-500">
<div class="entity-body">
<div class="entity-body--row m-2">
<span class="mt-2" *ngIf="duracion! > 0"
><fa-icon class="entity-icon--access" [icon]="faCalendarAlt"></fa-icon> Duración: &nbsp;&nbsp;&nbsp;&nbsp;{{
duracion
}}</span
>
<span class="mt-2" *ngIf="duracion! == 0"
><fa-icon class="entity-icon--access" [icon]="faCalendarAlt"></fa-icon> Duración: &nbsp;&nbsp;&nbsp;&nbsp;Un día o
menos</span
>
<span class="mt-2" *ngIf="duracion! == -1"
><fa-icon class="entity-icon--access" [icon]="faCalendarAlt"></fa-icon> Duración: &nbsp;&nbsp;&nbsp;&nbsp;No ha
finalizado</span
>
</div>
<div class="entity-body--row m-2">
<p>Calificación:</p>
<fa-icon *ngFor="let i of [].constructor(encuesta.calificacion)" class="entity-icon--star" [icon]="faStar"></fa-icon>
<fa-icon
*ngFor="let i of [].constructor(5 - encuesta.calificacion!)"
class="entity-icon--star--off"
[icon]="faStar"
></fa-icon>
</div>
<div class="entity-body--row m-2">
<button (click)="detallesPreguntas(encuesta)" class="ds-btn btn-card ds-btn--primary">
<fa-icon [icon]="faEye"></fa-icon>&nbsp;&nbsp;Detalle
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--REPORTES DE LAS PREGUNTAS-->
<div class="container-fluid" *ngIf="encuesta" [hidden]="reportPreguntas">
<div>
<div class="alert alert-warning" id="no-result" *ngIf="ePreguntas?.length === 0">
<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--question-wrapper card-encuesta" *ngFor="let ePregunta of ePreguntas; let i = index">
<div
[attr.data-index]="ePregunta.id"
[attr.data-tipo]="ePregunta.tipo"
[attr.data-opcional]="ePregunta.opcional"
class="ds-survey--question"
>
<div class="ds-survey--titulo">
<span class="ds-survey--titulo--name">{{ i + 1 }}. {{ ePregunta.nombre }}</span>
</div>
<div>
<span *ngIf="ePregunta.tipo === 'SINGLE'" class="ds-subtitle"
>Pregunta de respuesta {{ 'dataSurveyApp.PreguntaCerradaTipo.SINGLE' | translate | lowercase }}
{{ ePregunta.opcional ? '(opcional)' : '' }}</span
>
<span *ngIf="ePregunta.tipo === 'MULTIPLE'" class="ds-subtitle"
>Pregunta de respuesta {{ 'dataSurveyApp.PreguntaCerradaTipo.MULTIPLE' | translate | lowercase }}
{{ ePregunta.opcional ? '(opcional)' : '' }}</span
>
<span *ngIf="!ePregunta.tipo" class="ds-subtitle"
>Pregunta de respuesta abierta {{ ePregunta.opcional ? '(opcional)' : '' }}</span
>
</div>
<ng-container *ngIf="ePregunta.tipo">
<ng-container *ngFor="let ePreguntaOpcion of ePreguntasOpciones; let j = index">
<ng-container *ngFor="let ePreguntaOpcionFinal of ePreguntaOpcion">
<ng-container *ngIf="ePregunta.id === ePreguntaOpcionFinal.epreguntaCerrada.id">
<div
class="ds-survey--option ds-survey--option--base ds-survey--closed-option can-delete"
[attr.data-id]="ePreguntaOpcionFinal.id"
>
<div class="radio" *ngIf="ePregunta.tipo === 'SINGLE'">
<!--<input
type="text"
readonly
style="border-radius: 3px"
name="{{ 'radio' + ePregunta.id }}"
id="'radio'"
/>-->
<label>{{
ePreguntaOpcionFinal.nombre + ' / Cantidad de veces seleccionada: ' + ePreguntaOpcionFinal.cantidad
}}</label>
</div>
<div class="checkbox" *ngIf="ePregunta.tipo === 'MULTIPLE'">
<!--<input
type="checkbox"
style="border-radius: 3px"
id="{{ 'checkbox' + ePreguntaOpcionFinal.id }}"
/>-->
<label>{{
ePreguntaOpcionFinal.nombre + ' / Cantidad de veces seleccionada: ' + ePreguntaOpcionFinal.cantidad
}}</label>
</div>
</div>
</ng-container>
</ng-container>
</ng-container>
</ng-container>
<div *ngIf="!ePregunta.tipo">
<div *ngFor="let res of respuestaAbierta">
<!-- <ul>
<li *ngIf="res.epreguntaAbierta?.id == preguntaId"> {{ res.respuesta }}</li>
</ul>-->
<!-- <textarea readonly class="ds-survey&#45;&#45;textarea" cols="33" rows="10" *ngIf="res.epreguntaAbierta?.id == preguntaId" > {{ res.respuesta }} </textarea>-->
<div *ngIf="res.epreguntaAbierta?.id == preguntaId">
<label> {{ '- ' + res.respuesta }}</label> <br />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

View File

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

View File

@ -0,0 +1,218 @@
import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { IEncuesta } from '../../encuesta/encuesta.model';
import { EstadoEncuesta } from '../../enumerations/estado-encuesta.model';
import { EncuestaService } from '../../encuesta/service/encuesta.service';
import { UsuarioExtra } from '../../usuario-extra/usuario-extra.model';
import { Account } from '../../../core/auth/account.model';
import { AccountService } from '../../../core/auth/account.service';
import { UsuarioExtraService } from '../../usuario-extra/service/usuario-extra.service';
import { faListAlt, faUser, faEye, faStar, faCalendarAlt } from '@fortawesome/free-solid-svg-icons';
import * as Chartist from 'chartist';
import { finalize } from 'rxjs/operators';
import { EPreguntaAbiertaRespuestaService } from '../../e-pregunta-abierta-respuesta/service/e-pregunta-abierta-respuesta.service';
import { each } from 'chart.js/helpers';
import { IEPreguntaAbiertaRespuesta } from '../../e-pregunta-abierta-respuesta/e-pregunta-abierta-respuesta.model';
@Component({
selector: 'jhi-dashboard-user',
templateUrl: './dashboard-user.component.html',
styleUrls: ['./dashboard-user.component.scss'],
})
export class DashboardUserComponent implements OnInit {
cantEncuestas: number = 0;
cantPersonas: number = 0;
cantActivas: number = 0;
cantFinalizadas: number = 0;
cantDraft: number = 0;
cantPublicas: number = 0;
cantPrivadas: number = 0;
faListAlt = faListAlt;
faUser = faUser;
faEye = faEye;
faStar = faStar;
faCalendarAlt = faCalendarAlt;
reportsGeneral = false;
reportForEncuestas = true;
reportPreguntas = true;
duracion?: number = 0;
ePreguntas?: any[];
ePreguntasOpciones?: any[];
respuestaAbierta?: IEPreguntaAbiertaRespuesta[];
isLoading = false;
encuestas?: IEncuesta[];
usuarioExtra: UsuarioExtra | null = null;
account: Account | null = null;
encuesta: IEncuesta | null = null;
preguntaId?: number = 0;
constructor(
protected encuestaService: EncuestaService,
protected accountService: AccountService,
protected usuarioExtraService: UsuarioExtraService,
protected resAbierta: EPreguntaAbiertaRespuestaService
) {}
ngOnInit(): void {
this.loadUser();
}
cambiarVista() {
if (this.reportsGeneral) {
this.reportsGeneral = false;
this.reportForEncuestas = true;
this.reportPreguntas = true;
} else if (this.reportForEncuestas) {
this.reportsGeneral = true;
this.reportForEncuestas = false;
this.reportPreguntas = true;
} else if (this.reportPreguntas) {
this.reportForEncuestas = false;
this.reportPreguntas = true;
this.reportsGeneral = true;
}
}
loadEncuestas() {
this.encuestaService.query().subscribe(
(res: HttpResponse<IEncuesta[]>) => {
this.isLoading = false;
const tmpEncuestas = res.body ?? [];
this.encuestas = tmpEncuestas.filter(e => e.usuarioExtra?.id === this.usuarioExtra?.id);
this.cantEncuestas = this.encuestas.length;
this.cantActivas = tmpEncuestas.filter(e => e.estado === 'ACTIVE' && e.usuarioExtra?.id === this.usuarioExtra?.id).length;
this.cantDraft = tmpEncuestas.filter(e => e.estado === 'DRAFT' && e.usuarioExtra?.id === this.usuarioExtra?.id).length;
this.cantFinalizadas = tmpEncuestas.filter(e => e.estado === 'FINISHED' && e.usuarioExtra?.id === this.usuarioExtra?.id).length;
this.cantPublicas = tmpEncuestas.filter(e => e.acceso === 'PUBLIC' && e.usuarioExtra?.id === this.usuarioExtra?.id).length;
this.cantPrivadas = tmpEncuestas.filter(e => e.acceso === 'PRIVATE' && e.usuarioExtra?.id === this.usuarioExtra?.id).length;
tmpEncuestas.forEach(encuesta => {
const _calificacion = encuesta.calificacion;
encuesta.calificacion = Number(_calificacion?.toString().split('.')[0]);
if (encuesta.fechaFinalizada == null) {
this.duracion = -1;
} else {
this.duracion = encuesta.fechaPublicacion?.diff(encuesta.fechaFinalizada!, 'days');
}
});
this.cantPersonas = tmpEncuestas.filter(e => e.calificacion && e.usuarioExtra?.id === this.usuarioExtra?.id).length;
//cantidad de personas que han completado la encuesta
this.loadFirstChart();
this.loadSecondChart();
},
() => {
this.isLoading = false;
}
);
}
loadUser(): void {
this.accountService.getAuthenticationState().subscribe(account => {
if (account !== null) {
this.usuarioExtraService.find(account.id).subscribe(usuarioExtra => {
this.usuarioExtra = usuarioExtra.body;
});
}
});
this.loadEncuestas();
}
loadFirstChart(): void {
var dataEstado = {
labels: ['ACTIVOS', 'BORRADOR', 'FINALIZADOS'],
series: [this.cantActivas, this.cantDraft, this.cantFinalizadas],
};
new Chartist.Pie('#chartEstado', dataEstado);
}
loadSecondChart(): void {
var dataAcceso = {
labels: ['PÚBLICA', 'PRIVADA'],
series: [this.cantPublicas, this.cantPrivadas],
};
new Chartist.Pie('#chartAcceso', dataAcceso);
}
detallesPreguntas(encuesta: IEncuesta): void {
if (!this.reportForEncuestas) {
this.reportPreguntas = false;
this.reportForEncuestas = true;
this.reportsGeneral = true;
}
this.encuesta = encuesta;
debugger;
this.isLoading = true;
this.encuestaService
.findQuestions(encuesta?.id!)
.pipe(
finalize(() =>
this.encuestaService.findQuestionsOptions(encuesta?.id!).subscribe(
(res: any) => {
this.isLoading = false;
this.ePreguntasOpciones = res.body ?? [];
debugger;
this.getOpenQuestionAnswers();
},
() => {
this.isLoading = false;
}
)
)
)
.subscribe(
(res: any) => {
this.isLoading = false;
this.ePreguntas = res.body ?? [];
},
() => {
this.isLoading = false;
}
);
if (this.ePreguntas!.length == 0) {
this.previousState();
}
}
previousState(): void {
window.history.back();
}
getOpenQuestionAnswers() {
this.ePreguntas!.forEach(pregunta => {
debugger;
if (!pregunta.tipo) {
this.resAbierta.query().subscribe(res => {
debugger;
this.preguntaId = pregunta.id;
this.respuestaAbierta = res.body ?? [];
/* const respuesta = res.body ?? [];
respuesta.forEach( e => {
debugger
if (e.epreguntaAbierta?.id == pregunta.id){
this.respuestaAbierta?.push(e);
}
/!*debugger
this.eRespuestaAbierta?.push(respuesta.filter(e.ePreguntaAbierta?.id == pregunta.id));*!/
})
*/
console.log(this.respuestaAbierta);
});
}
});
}
}

View File

@ -0,0 +1,14 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardUserComponent } from './dashboard-user/dashboard-user.component';
import { DashboardAdminComponent } from './dashboard-admin/dashboard-admin.component';
import { SharedModule } from '../../shared/shared.module';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { DashboardRoutingModule } from './route/dashboard-routing.module';
@NgModule({
declarations: [DashboardUserComponent, DashboardAdminComponent],
imports: [CommonModule, SharedModule, DashboardRoutingModule, FontAwesomeModule],
})
export class DashboardModule {}

View File

@ -0,0 +1,10 @@
export const generateFileName = (fileName: string, extension: string): string => {
return (
fileName +
'_' +
new Date().toLocaleDateString().substr(0, 10).split('/').join('-') +
'_' +
Math.random().toString().substring(2) +
extension
);
};

View File

@ -0,0 +1,37 @@
import * as XLSX from 'xlsx';
import * as FileSaver from 'file-saver';
import { generateFileName } from './export_common';
const EXCEL_TYPE: string = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION: string = '.xlsx';
export const exportAsExcelFile = (sheetNames: string[], arrayOfData: any[], excelFileName: any) => {
const workbook = XLSX.utils.book_new();
arrayOfData.forEach((data, index) => {
let sheetName = sheetNames[index];
let worksheet = XLSX.utils.json_to_sheet(data);
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
});
const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
saveAsExcelFile(excelBuffer, excelFileName);
};
const saveAsExcelFile = (buffer: any, fileName: any) => {
const data = new Blob([buffer], { type: EXCEL_EXTENSION });
const generatedFileName = generateFileName(fileName, EXCEL_EXTENSION);
FileSaver.saveAs(data, generatedFileName);
};
export const exportAsExcelTable = () => {
const workbook = XLSX.utils.book_new();
let worksheet = XLSX.utils.json_to_sheet([{ test: 1 }, { test: 2 }]);
XLSX.utils.book_append_sheet(workbook, worksheet, 'test');
const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
saveAsExcelFile(excelBuffer, 'test');
};

View File

@ -0,0 +1,42 @@
import { jsPDF } from 'jspdf';
import { generateFileName } from './export_common';
const PDF_EXTENSION: string = '.pdf';
export const generatePDFTableData = (data: any): any => {
const result: any = [];
data.forEach((item: any) => {
result.push(Object.assign({}, item));
});
return result;
};
export const createPDFTableHeaders = (keys: any): any[] => {
let result = [];
for (let i = 0; i < keys.length; i += 1) {
result.push({
id: keys[i],
name: keys[i],
prompt: keys[i],
align: 'left',
padding: 0,
});
}
return result;
};
export const generatePDFTable = (doc: jsPDF, _docData: any, _docHeaders: string[], _docTitle: string): void => {
doc.setFontSize(20);
doc.setFont('helvetica', 'bold');
doc.text(_docTitle, 20, 20);
doc.setFont('helvetica');
doc.table(20, 30, _docData, _docHeaders, { fontSize: 10, autoSize: true });
};
export const saveGeneratedPDF = (doc: jsPDF, _fileName: string) => {
const generatedFileName = generateFileName(_fileName, PDF_EXTENSION);
doc.save(generatedFileName);
};

View File

@ -0,0 +1,25 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardUserComponent } from '../dashboard-user/dashboard-user.component';
import { DashboardAdminComponent } from '../dashboard-admin/dashboard-admin.component';
import { UserRouteAccessService } from '../../../core/auth/user-route-access.service';
const dashboardRoute: Routes = [
{
path: 'admin',
component: DashboardAdminComponent,
canActivate: [UserRouteAccessService],
},
{
path: 'user',
component: DashboardUserComponent,
canActivate: [UserRouteAccessService],
},
];
@NgModule({
imports: [RouterModule.forChild(dashboardRoute)],
exports: [RouterModule],
})
export class DashboardRoutingModule {}

View File

@ -22,9 +22,9 @@
</dd>
<dt><span jhiTranslate="dataSurveyApp.ePreguntaAbiertaRespuesta.ePreguntaAbierta">E Pregunta Abierta</span></dt>
<dd>
<div *ngIf="ePreguntaAbiertaRespuesta.ePreguntaAbierta">
<a [routerLink]="['/e-pregunta-abierta', ePreguntaAbiertaRespuesta.ePreguntaAbierta?.id, 'view']">{{
ePreguntaAbiertaRespuesta.ePreguntaAbierta?.id
<div *ngIf="ePreguntaAbiertaRespuesta.epreguntaAbierta">
<a [routerLink]="['/e-pregunta-abierta', ePreguntaAbiertaRespuesta.epreguntaAbierta?.id, 'view']">{{
ePreguntaAbiertaRespuesta.epreguntaAbierta?.id
}}</a>
</div>
</dd>

View File

@ -3,11 +3,11 @@ import { IEPreguntaAbierta } from 'app/entities/e-pregunta-abierta/e-pregunta-ab
export interface IEPreguntaAbiertaRespuesta {
id?: number;
respuesta?: string;
ePreguntaAbierta?: IEPreguntaAbierta | null;
epreguntaAbierta?: IEPreguntaAbierta | null;
}
export class EPreguntaAbiertaRespuesta implements IEPreguntaAbiertaRespuesta {
constructor(public id?: number, public respuesta?: string, public ePreguntaAbierta?: IEPreguntaAbierta | null) {}
constructor(public id?: number, public respuesta?: string, public epreguntaAbierta?: IEPreguntaAbierta | null) {}
}
export function getEPreguntaAbiertaRespuestaIdentifier(ePreguntaAbiertaRespuesta: IEPreguntaAbiertaRespuesta): number | undefined {

View File

@ -45,9 +45,9 @@
</td>
<td>{{ ePreguntaAbiertaRespuesta.respuesta }}</td>
<td>
<div *ngIf="ePreguntaAbiertaRespuesta.ePreguntaAbierta">
<a [routerLink]="['/e-pregunta-abierta', ePreguntaAbiertaRespuesta.ePreguntaAbierta?.id, 'view']">{{
ePreguntaAbiertaRespuesta.ePreguntaAbierta?.id
<div *ngIf="ePreguntaAbiertaRespuesta.epreguntaAbierta">
<a [routerLink]="['/e-pregunta-abierta', ePreguntaAbiertaRespuesta.epreguntaAbierta?.id, 'view']">{{
ePreguntaAbiertaRespuesta.epreguntaAbierta?.id
}}</a>
</div>
</td>

View File

@ -43,7 +43,7 @@ describe('Component Tests', () => {
it('Should call EPreguntaAbierta query and add missing value', () => {
const ePreguntaAbiertaRespuesta: IEPreguntaAbiertaRespuesta = { id: 456 };
const ePreguntaAbierta: IEPreguntaAbierta = { id: 35011 };
ePreguntaAbiertaRespuesta.ePreguntaAbierta = ePreguntaAbierta;
ePreguntaAbiertaRespuesta.epreguntaAbierta = ePreguntaAbierta;
const ePreguntaAbiertaCollection: IEPreguntaAbierta[] = [{ id: 58318 }];
jest.spyOn(ePreguntaAbiertaService, 'query').mockReturnValue(of(new HttpResponse({ body: ePreguntaAbiertaCollection })));
@ -65,7 +65,7 @@ describe('Component Tests', () => {
it('Should update editForm', () => {
const ePreguntaAbiertaRespuesta: IEPreguntaAbiertaRespuesta = { id: 456 };
const ePreguntaAbierta: IEPreguntaAbierta = { id: 40814 };
ePreguntaAbiertaRespuesta.ePreguntaAbierta = ePreguntaAbierta;
ePreguntaAbiertaRespuesta.epreguntaAbierta = ePreguntaAbierta;
activatedRoute.data = of({ ePreguntaAbiertaRespuesta });
comp.ngOnInit();

View File

@ -81,12 +81,12 @@ export class EPreguntaAbiertaRespuestaUpdateComponent implements OnInit {
this.editForm.patchValue({
id: ePreguntaAbiertaRespuesta.id,
respuesta: ePreguntaAbiertaRespuesta.respuesta,
ePreguntaAbierta: ePreguntaAbiertaRespuesta.ePreguntaAbierta,
ePreguntaAbierta: ePreguntaAbiertaRespuesta.epreguntaAbierta,
});
this.ePreguntaAbiertasSharedCollection = this.ePreguntaAbiertaService.addEPreguntaAbiertaToCollectionIfMissing(
this.ePreguntaAbiertasSharedCollection,
ePreguntaAbiertaRespuesta.ePreguntaAbierta
ePreguntaAbiertaRespuesta.epreguntaAbierta
);
}
@ -110,7 +110,7 @@ export class EPreguntaAbiertaRespuestaUpdateComponent implements OnInit {
...new EPreguntaAbiertaRespuesta(),
id: this.editForm.get(['id'])!.value,
respuesta: this.editForm.get(['respuesta'])!.value,
ePreguntaAbierta: this.editForm.get(['ePreguntaAbierta'])!.value,
epreguntaAbierta: this.editForm.get(['ePreguntaAbierta'])!.value,
};
}
}

View File

@ -16,6 +16,10 @@ export class EPreguntaCerradaOpcionService {
constructor(protected http: HttpClient, protected applicationConfigService: ApplicationConfigService) {}
updateCount(id: any) {
return this.http.post(`${this.resourceUrl}/count/${id}`, id, { observe: 'response' });
}
create(ePreguntaCerradaOpcion: IEPreguntaCerradaOpcion, preguntaId?: number): Observable<EntityResponseType> {
return this.http.post<IEPreguntaCerradaOpcion>(`${this.resourceUrl}/${preguntaId}`, ePreguntaCerradaOpcion, { observe: 'response' });
}

View File

@ -0,0 +1,193 @@
<div class="container-fluid" *ngIf="encuesta">
<div>
<h2 id="page-heading" data-cy="EPreguntaCerradaHeading">
<div class="d-flex align-items-center">
<p class="ds-title">Vista previa de {{ encuesta!.nombre }}</p>
&nbsp;&nbsp;<fa-icon class="ds-info--icon" [icon]="faQuestion" data-toggle="modal" data-target="#verParametros"></fa-icon>
</div>
<p class="ds-subtitle">Creada el día {{ encuesta!.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>
<div class="alert alert-warning" id="no-result" *ngIf="ePreguntas?.length === 0">
<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--question-wrapper card-encuesta" *ngFor="let ePregunta of ePreguntas; let i = index; trackBy: trackId">
<div
[attr.data-index]="ePregunta.id"
[attr.data-tipo]="ePregunta.tipo"
[attr.data-opcional]="ePregunta.opcional"
class="ds-survey--question"
>
<div class="ds-survey--titulo">
<span class="ds-survey--titulo--name">{{ i + 1 }}. {{ ePregunta.nombre }}</span>
</div>
<div>
<span *ngIf="ePregunta.tipo === 'SINGLE'" class="ds-subtitle"
>Pregunta de respuesta {{ 'dataSurveyApp.PreguntaCerradaTipo.SINGLE' | translate | lowercase }}
{{ ePregunta.opcional ? '(opcional)' : '' }}</span
>
<span *ngIf="ePregunta.tipo === 'MULTIPLE'" class="ds-subtitle"
>Pregunta de respuesta {{ 'dataSurveyApp.PreguntaCerradaTipo.MULTIPLE' | translate | lowercase }}
{{ ePregunta.opcional ? '(opcional)' : '' }}</span
>
<span *ngIf="!ePregunta.tipo" class="ds-subtitle"
>Pregunta de respuesta abierta {{ ePregunta.opcional ? '(opcional)' : '' }}</span
>
</div>
<ng-container *ngIf="ePregunta.tipo">
<ng-container *ngFor="let ePreguntaOpcion of ePreguntasOpciones; let j = index; trackBy: trackId">
<ng-container *ngFor="let ePreguntaOpcionFinal of ePreguntaOpcion">
<ng-container *ngIf="ePregunta.id === ePreguntaOpcionFinal.epreguntaCerrada.id">
<div
class="ds-survey--option ds-survey--option--base ds-survey--closed-option can-delete"
[attr.data-id]="ePreguntaOpcionFinal.id"
>
<div class="radio" *ngIf="ePregunta.tipo === 'SINGLE'">
<input
type="radio"
(change)="onCheck(ePreguntaOpcionFinal)"
[value]="ePreguntaOpcionFinal.id"
style="border-radius: 3px"
name="{{ 'radio' + ePregunta.id }}"
id="{{ 'radio' + ePreguntaOpcionFinal.id }}"
/>
<label for="{{ 'radio' + ePreguntaOpcionFinal.id }}">{{ ePreguntaOpcionFinal.nombre }}</label>
</div>
<div class="checkbox" *ngIf="ePregunta.tipo === 'MULTIPLE'">
<input
(change)="toggleOption(ePreguntaOpcionFinal)"
type="checkbox"
style="border-radius: 3px"
id="{{ 'checkbox' + ePreguntaOpcionFinal.id }}"
/>
<label for="{{ 'checkbox' + ePreguntaOpcionFinal.id }}">{{ ePreguntaOpcionFinal.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="!ePregunta.tipo">
<textarea class="ds-survey--textarea" id="{{ ePregunta.id }}" cols="33" rows="10"></textarea>
</div>
</div>
</div>
<div class="ds-survey--question-wrapper card-encuesta">
<div class="ds-survey--question">
<div class="ds-survey--rating">
<div class="ds-survey--titulo">
<span class="ds-survey--titulo--name">Calificación</span>
</div>
<div class="ds-survey--option ds-survey--option--base">
<fa-icon
*ngFor="let starNumber of this.stars"
id="{{ 'star-' + starNumber }}"
class="entity-icon--star--off"
[icon]="faStar"
(click)="updateRating(starNumber)"
></fa-icon>
</div>
</div>
</div>
</div>
<button class="ds-btn ds-btn--primary" (click)="finish()">Finalizar</button>
</div>
<div
class="modal fade ds-modal"
id="verParametros"
tabindex="-1"
role="dialog"
aria-labelledby="exampleModalCenterTitle"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title" id="exampleModalLongTitle">Información de encuesta</h1>
</div>
<div class="modal-body">
<div>
<div class="mb-5">
<p style="font-size: 1.2em" class="ds-subtitle">Cantidad de preguntas</p>
<p>{{ ePreguntas?.length }}</p>
</div>
<div class="mb-5">
<p class="ds-subtitle" jhiTranslate="dataSurveyApp.encuesta.acceso">Acceso</p>
<p jhiTranslate="{{ 'dataSurveyApp.AccesoEncuesta.' + encuesta.acceso }}">{{ encuesta.acceso }}</p>
</div>
<div *ngIf="encuesta.acceso === 'PRIVATE'" class="mb-5">
<p class="ds-subtitle">Contraseña</p>
<p>{{ encuesta.contrasenna }}</p>
</div>
<div class="mb-5">
<p class="ds-subtitle">Estado:</p>
<p jhiTranslate="{{ 'dataSurveyApp.EstadoEncuesta.' + encuesta.estado }}">{{ encuesta.estado }}</p>
</div>
<div *ngIf="encuesta.categoria" class="mb-5">
<p class="ds-subtitle">Categoría</p>
<P> </P> {{ encuesta.categoria?.nombre }}
</div>
<div class="mb-5">
<p class="ds-subtitle">Fecha de publicación</p>
<P
>{{
encuesta.fechaPublicacion === undefined
? 'Sin publicar'
: (encuesta.fechaPublicacion | formatShortDatetime | lowercase)
}}
</P>
</div>
<div class="mb-5">
<p class="ds-subtitle">Fecha de finalización</p>
<p>
{{
encuesta.fechaFinalizada === undefined
? 'Sin finalizar'
: (encuesta.fechaFinalizada | formatShortDatetime | lowercase)
}}
</p>
</div>
<div class="mb-5">
<p class="ds-subtitle">Calificación</p>
<div>
<fa-icon *ngFor="let i of [].constructor(this.avgCalificacion)" class="entity-icon--star" [icon]="faStar"></fa-icon
><fa-icon
*ngFor="let i of [].constructor(5 - this.avgCalificacion)"
class="entity-icon--star--off"
[icon]="faStar"
></fa-icon>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button id="cancelBtnVerParametros" type="button" class="ds-btn ds-btn--secondary" data-dismiss="modal">
<fa-icon icon="arrow-left"></fa-icon>&nbsp;&nbsp;<span>Volver</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

View File

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

View File

@ -0,0 +1,269 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { finalize } from 'rxjs/operators';
import { IEncuesta } from '../encuesta.model';
import { EncuestaService } from '../service/encuesta.service';
import { ICategoria } from 'app/entities/categoria/categoria.model';
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 { IEPreguntaCerrada } from 'app/entities/e-pregunta-cerrada/e-pregunta-cerrada.model';
import { EPreguntaCerradaService } from 'app/entities/e-pregunta-cerrada/service/e-pregunta-cerrada.service';
import { EPreguntaAbiertaService } from '../../e-pregunta-abierta/service/e-pregunta-abierta.service';
import { EPreguntaAbiertaRespuestaService } from '../../e-pregunta-abierta-respuesta/service/e-pregunta-abierta-respuesta.service';
import { EPreguntaCerradaOpcionService } from '../../e-pregunta-cerrada-opcion/service/e-pregunta-cerrada-opcion.service';
import { faStar, faQuestion } from '@fortawesome/free-solid-svg-icons';
import { AccesoEncuesta } from 'app/entities/enumerations/acceso-encuesta.model';
import { EncuestaPasswordDialogComponent } from '../encuesta-password-dialog/encuesta-password-dialog.component';
import { PreguntaCerradaTipo } from 'app/entities/enumerations/pregunta-cerrada-tipo.model';
import { EPreguntaAbiertaRespuesta } from 'app/entities/e-pregunta-abierta-respuesta/e-pregunta-abierta-respuesta.model';
import { Observable } from 'rxjs/internal/Observable';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
@Component({
selector: 'jhi-complete',
templateUrl: './complete.component.html',
})
export class EncuestaCompleteComponent implements OnInit {
categoriasSharedCollection: ICategoria[] = [];
usuarioExtrasSharedCollection: IUsuarioExtra[] = [];
faStar = faStar;
faQuestion = faQuestion;
encuesta?: IEncuesta;
isLoading = false;
ePreguntas?: any[];
ePreguntasOpciones?: any[];
isLocked?: boolean;
selectedOpenOptions: any;
selectedSingleOptions: any;
selectedMultiOptions: any;
error: boolean;
calificacion: number;
stars: number[] = [1, 2, 3, 4, 5];
cantidadCalificaciones: number = 0;
avgCalificacion: number = 0;
sumCalificacion: number = 0;
constructor(
protected activatedRoute: ActivatedRoute,
protected encuestaService: EncuestaService,
protected usuarioExtraService: UsuarioExtraService,
protected fb: FormBuilder,
protected modalService: NgbModal,
protected ePreguntaCerradaService: EPreguntaCerradaService,
protected ePreguntaCerradaOpcionService: EPreguntaCerradaOpcionService,
protected ePreguntaAbiertaService: EPreguntaAbiertaService,
protected ePreguntaAbiertaRespuestaService: EPreguntaAbiertaRespuestaService
) {
this.selectedOpenOptions = {};
this.selectedSingleOptions = {};
this.selectedMultiOptions = [];
this.error = false;
this.calificacion = 0;
}
ngOnInit(): void {
this.activatedRoute.data.subscribe(({ encuesta }) => {
if (encuesta) {
this.encuesta = encuesta;
this.avgCalificacion = parseInt(this.encuesta!.calificacion!.toString().split('.')[0]);
this.cantidadCalificaciones = parseInt(this.encuesta!.calificacion!.toString().split('.')[1]);
this.sumCalificacion = this.avgCalificacion * this.cantidadCalificaciones;
}
this.isLocked = this.verifyPassword();
if (this.isLocked) {
this.previousState();
} else {
this.loadAll();
}
});
for (let pregunta of this.ePreguntas!) {
if (pregunta.tipo && pregunta.tipo === PreguntaCerradaTipo.SINGLE) {
this.selectedSingleOptions[pregunta.id] = null;
}
}
}
verifyPassword(): boolean {
if (this.encuesta!.acceso === AccesoEncuesta.PUBLIC) {
return false;
} else {
const modalRef = this.modalService.open(EncuestaPasswordDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.componentInstance.encuesta = this.encuesta;
modalRef.closed.subscribe(reason => {
return reason === 'success';
});
}
return true;
}
ngAfterViewChecked(): void {
this.initListeners();
}
initListeners(): void {
const questions = document.getElementsByClassName('ds-survey--question-wrapper');
for (let i = 0; i < questions.length; i++) {
if (questions[i].classList.contains('ds-survey--closed-option')) {
questions[i].addEventListener('click', e => {
if ((e.target as HTMLInputElement).checked) {
(e.target as HTMLElement).offsetParent!.classList.add('ds-survey--closed-option--active');
(e.target as HTMLElement).id;
} else {
(e.target as HTMLElement).offsetParent!.classList.remove('ds-survey--closed-option--active');
}
});
}
}
}
trackId(_index: number, item: IEPreguntaCerrada): number {
return item.id!;
}
trackEPreguntaCerradaById(_index: number, item: IEPreguntaCerrada): number {
return item.id!;
}
trackCategoriaById(_index: number, item: ICategoria): number {
return item.id!;
}
trackUsuarioExtraById(_index: number, item: IUsuarioExtra): number {
return item.id!;
}
loadAll(): void {
this.isLoading = true;
this.encuestaService
.findQuestions(this.encuesta?.id!)
.pipe(
finalize(() =>
this.encuestaService.findQuestionsOptions(this.encuesta?.id!).subscribe(
(res: any) => {
this.isLoading = false;
this.ePreguntasOpciones = res.body ?? [];
},
() => {
this.isLoading = false;
}
)
)
)
.subscribe(
(res: any) => {
this.isLoading = false;
this.ePreguntas = res.body ?? [];
},
() => {
this.isLoading = false;
}
);
if (this.ePreguntas!.length == 0) {
this.previousState();
}
}
previousState(): void {
window.history.back();
}
onCheck(preguntaOpcion: { epreguntaCerrada: any; id: any }): void {
this.selectedSingleOptions[preguntaOpcion.epreguntaCerrada!.id!] = preguntaOpcion.id;
}
toggleOption(ePreguntaOpcionFinal: { id: any }): void {
if (this.selectedMultiOptions.includes(ePreguntaOpcionFinal.id)) {
for (let i = 0; i < this.selectedMultiOptions.length; i++) {
if (this.selectedMultiOptions[i] === ePreguntaOpcionFinal.id) {
this.selectedMultiOptions.splice(i, 1);
}
}
} else {
this.selectedMultiOptions.push(ePreguntaOpcionFinal.id);
}
}
finish(): void {
this.updateEncuestaRating();
this.getOpenQuestionAnswers();
this.registerOpenQuestionAnswers();
this.updateClosedOptionsCount();
}
updateEncuestaRating() {
if (this.calificacion !== 0) {
const newSumCalificacion = this.sumCalificacion + this.calificacion;
const newCantidadCalificacion = this.cantidadCalificaciones + 1;
const newAvgCalificacion = newSumCalificacion / newCantidadCalificacion;
const newRating = this.joinRatingValues(newAvgCalificacion, newCantidadCalificacion);
this.encuesta!.calificacion = Number(newRating);
this.encuestaService.updateSurvey(this.encuesta!);
}
}
updateClosedOptionsCount() {
for (let key in this.selectedSingleOptions) {
this.ePreguntaCerradaOpcionService.updateCount(this.selectedSingleOptions[key]);
}
this.selectedMultiOptions.forEach((option: any) => {
this.ePreguntaCerradaOpcionService.updateCount(option);
});
}
registerOpenQuestionAnswers() {
for (let id in this.selectedOpenOptions) {
let pregunta = this.ePreguntas!.find(p => {
return p.id == id;
});
let newRespuesta = new EPreguntaAbiertaRespuesta(0, this.selectedOpenOptions[id], pregunta);
this.ePreguntaAbiertaRespuestaService.create(newRespuesta);
}
}
protected onSaveFinalize(): void {
// this.isSaving = false;
}
processError(response: HttpErrorResponse): void {
if (response.status === 400) {
this.error = true;
}
}
protected subscribeToSaveResponse(result: Observable<HttpResponse<any>>): void {
result.pipe(finalize(() => this.onSaveFinalize())).subscribe(
() => this.previousState(),
response => this.processError(response)
);
}
getOpenQuestionAnswers() {
this.ePreguntas!.forEach(pregunta => {
if (!pregunta.tipo) {
let textValue = (document.getElementById(pregunta.id) as HTMLInputElement).value;
this.selectedOpenOptions[pregunta.id] = textValue;
}
});
}
joinRatingValues(totalValue: number, ratingCount: number): Number {
const result = totalValue.toString() + '.' + ratingCount.toString();
return parseFloat(result);
}
updateRating(value: number) {
this.calificacion = value;
this.stars.forEach(starNumber => {
let starElement = document.getElementById(`star-${starNumber}`);
if (starNumber > this.calificacion!) {
starElement!.classList.add('entity-icon--star--off');
starElement!.classList.remove('entity-icon--star');
} else {
starElement!.classList.add('entity-icon--star');
starElement!.classList.remove('entity-icon--star--off');
}
});
}
}

View File

@ -11,7 +11,7 @@
<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>
<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>
</ng-container>
</div>
@ -27,13 +27,14 @@
<!-- <jhi-alert></jhi-alert> -->
<div class="alert alert-warning" id="no-result" *ngIf="ePreguntas?.length === 0">
<span>No se encontraron preguntas</span>
</div>
<div class="ds-survey preview-survey" id="entities" *ngIf="ePreguntas && ePreguntas.length > 0">
<div class="ds-survey preview-survey" id="entities">
<div class="ds-survey--all-question-wrapper col-8">
<div class="ds-survey--question-wrapper card-encuesta lift" *ngFor="let ePregunta of ePreguntas; let i = index; trackBy: trackId">
<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" *ngFor="let ePregunta of ePreguntas; let i = index; trackBy: trackId">
<div
[attr.data-index]="ePregunta.id"
[attr.data-tipo]="ePregunta.tipo"
@ -141,7 +142,7 @@
>{{
encuesta.fechaPublicacion === undefined
? 'Sin publicar'
: (encuesta.fechaFinalizada | formatShortDatetime | lowercase)
: (encuesta.fechaPublicacion | formatShortDatetime | lowercase)
}}
</P>
</div>
@ -157,7 +158,7 @@
{{
encuesta.fechaFinalizar === undefined
? 'Sin fecha de finalización'
: (encuesta.fechaFinalizada | formatShortDatetime | lowercase)
: (encuesta.fechaFinalizar | formatShortDatetime | lowercase)
}}</span
>
</dd>

View File

@ -14,7 +14,7 @@ import { IEncuesta, Encuesta } from '../encuesta.model';
import { EncuestaService } from '../service/encuesta.service';
import { ICategoria } from 'app/entities/categoria/categoria.model';
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 { 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 { 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({
selector: 'jhi-encuesta-detail',
@ -47,6 +51,8 @@ export class EncuestaDetailComponent implements OnInit {
successPublished = false;
ePreguntas?: any[];
ePreguntasOpciones?: any[];
usuarioExtra: UsuarioExtra | null = null;
usuariosColaboradores: IUsuarioEncuesta[] = [];
constructor(
protected activatedRoute: ActivatedRoute,
@ -57,18 +63,34 @@ export class EncuestaDetailComponent implements OnInit {
protected modalService: NgbModal,
protected ePreguntaCerradaService: EPreguntaCerradaService,
protected ePreguntaCerradaOpcionService: EPreguntaCerradaOpcionService,
protected ePreguntaAbiertaService: EPreguntaAbiertaService
protected ePreguntaAbiertaService: EPreguntaAbiertaService,
protected accountService: AccountService,
protected usuarioEncuestaService: UsuarioEncuestaService
) {}
ngOnInit(): void {
this.activatedRoute.data.subscribe(({ encuesta }) => {
if (encuesta) {
this.encuesta = encuesta;
// Fix calificacion
const _calificacion = encuesta.calificacion;
this.encuesta!.calificacion = Number(_calificacion?.toString().split('.')[0]);
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 {
@ -145,6 +167,16 @@ export class EncuestaDetailComponent implements OnInit {
this.isLoading = false;
}
);*/
this.usuarioEncuestaService.findCollaborators(this.encuesta?.id!).subscribe(
(res: any) => {
this.isLoading = false;
this.usuariosColaboradores = res.body ?? [];
},
() => {
this.isLoading = false;
}
);
}
publishSurvey(): void {
const modalRef = this.modalService.open(EncuestaPublishDialogComponent, { size: 'lg', backdrop: 'static' });
@ -161,4 +193,20 @@ export class EncuestaDetailComponent implements OnInit {
previousState(): void {
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,39 @@
<form class="ds-form" name="deleteForm">
<div class="modal-header">
<h2 class="ds-title" data-cy="encuestaDeleteDialogHeading">Compartir encuesta</h2>
</div>
<div class="modal-body">
<p class="ds-subtitle" id="jhi-delete-encuesta-heading">Puede copiar el enlace o compartirlo en redes sociales</p>
<hr />
<input class="compartir" readonly type="url" id="inputCompartir" [value]="baseURL" /> <br /><br />
<share-buttons
[theme]="'material-dark'"
[include]="['facebook', 'twitter', 'email']"
[show]="5"
[showText]="true"
[size]="1"
[url]="baseURL"
[title]="'Encuesta DataSurvey'"
[image]="'../../../content/img_datasurvey/datasurvey-logo-text-white-PNG.png'"
[autoSetMeta]="false"
></share-buttons>
<!-- <share-buttons [theme]="'modern-dark'"
[include]="['facebook','twitter']"
[show]="5"
[showText]="true"
[size]="2"
[url]="baseURL"
[title]="'Encuesta DataSurvey'"
[autoSetMeta]="false"
></share-buttons>-->
</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>
</div>
</form>

View File

@ -0,0 +1,7 @@
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap');
@import '~ngx-sharebuttons/themes/default/default-theme';
.compartir {
width: 100% !important;
}

View File

@ -0,0 +1,28 @@
import { Component, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { IEncuesta } from '../encuesta.model';
@Component({
selector: 'jhi-encuesta-compartir-dialog',
templateUrl: './encuesta-compartir-dialog.component.html',
styleUrls: ['./encuesta-compartir-dialog.component.scss'],
})
export class EncuestaCompartirDialogComponent implements OnInit {
encuesta?: IEncuesta;
baseURL: string = '';
imagen: string = '';
mensaje: string = 'Encuesta en DatasSurvey';
name = 'ngx sharebuttons';
constructor(protected activeModal: NgbActiveModal) {}
ngOnInit(): void {
this.baseURL = location.origin + '/encuesta/' + this.encuesta?.id + '/complete';
}
compartir(): void {}
cancel(): void {
this.activeModal.dismiss();
}
}

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,18 @@
<form *ngIf="encuesta" name="deleteForm" (ngSubmit)="confirmFinalizar(encuesta!)">
<div class="modal-header"></div>
<div class="modal-body">
<p class="ds-title--small" data-cy="encuestaDeleteDialogHeading">Finalizar encuesta</p>
<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,35 @@
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 {
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

@ -0,0 +1,28 @@
<form class="ds-form" [formGroup]="passwordForm" name="deleteForm" (ngSubmit)="submitPassword()">
<div *ngIf="this.isWrong">
<p>Contraseña incorrecta</p>
</div>
<div class="modal-body">
<p class="ds-title--small" jhiTranslate="dataSurveyApp.encuesta.password.title">Enter password</p>
<p class="ds-subtitle" id="jhi-delete-encuesta-heading" jhiTranslate="dataSurveyApp.encuesta.password.text">
This survey is marked as private, please enter the password
</p>
<input [(ngModel)]="passwordInput" type="password" name="passwordInput" id="passwordInput" placeholder="qwerty..." />
</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="submit"
type="submit"
class="ds-btn ds-btn--primary"
[disabled]="passwordForm.get('password')!.invalid"
>
<span jhiTranslate="entity.action.submit">Submit</span>
</button>
</div>
</form>

View File

@ -0,0 +1,4 @@
input {
margin: 2%;
width: 100%;
}

View File

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

View File

@ -0,0 +1,36 @@
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { IEncuesta } from '../encuesta.model';
@Component({
selector: 'jhi-encuesta-password-dialog',
templateUrl: './encuesta-password-dialog.component.html',
styleUrls: ['./encuesta-password-dialog.component.scss'],
})
export class EncuestaPasswordDialogComponent implements OnInit {
passwordForm = this.fb.group({
password: [null, [Validators.required]],
});
encuesta?: IEncuesta;
isWrong?: boolean;
passwordInput?: string;
constructor(protected activeModal: NgbActiveModal, protected fb: FormBuilder) {}
ngOnInit(): void {}
submitPassword() {
const password = this.passwordForm.get(['password'])!.value;
if (this.passwordForm.valid && password === this.encuesta!.contrasenna) {
this.activeModal.close('success');
} else {
this.isWrong = true;
}
}
cancel(): void {
this.activeModal.close('cancel');
}
}

View File

@ -1,6 +1,6 @@
<form *ngIf="encuesta" name="deleteForm" (ngSubmit)="confirmPublish(encuesta!)">
<div class="modal-header">
<!-- <h4 class="modal-title" data-cy="encuestaDeleteDialogHeading" jhiTranslate="entity.publish.title">Confirm delete operation</h4>-->
<h4 class="modal-title" data-cy="encuestaDeleteDialogHeading">Publique su encuesta</h4>
</div>
<div class="modal-body">
@ -48,13 +48,7 @@
<fa-icon icon="arrow-left"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<button
[disabled]="fechaForm.invalid"
id="jhi-confirm-delete-encuesta"
data-cy="entityConfirmDeleteButton"
type="submit"
class="ds-btn ds-btn--primary"
>
<button id="jhi-confirm-delete-encuesta" data-cy="entityConfirmDeleteButton" type="submit" class="ds-btn ds-btn--primary">
&nbsp;<span jhiTranslate="entity.action.publish">Delete</span>
</button>
</div>

View File

@ -107,7 +107,6 @@ export class EncuestaPublishDialogComponent implements OnInit {
fechaFinalizacionIsInvalid(fechaFinalizar: dayjs.Dayjs, fechaPublicacion: dayjs.Dayjs): boolean {
let numberDays: number;
debugger;
numberDays = fechaFinalizar?.diff(fechaPublicacion, 'days');

View File

@ -9,9 +9,15 @@ import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { EncuestaPublishDialogComponent } from './encuesta-publish-dialog/encuesta-publish-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 { EncuestaCompartirDialogComponent } from './encuesta-compartir-dialog/encuesta-compartir-dialog.component';
import { ShareButtonsModule } from 'ngx-sharebuttons/buttons';
import { EncuestaCompleteComponent } from './complete/complete.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({
imports: [SharedModule, EncuestaRoutingModule, FontAwesomeModule],
imports: [SharedModule, EncuestaRoutingModule, FontAwesomeModule, ShareButtonsModule],
declarations: [
EncuestaComponent,
EncuestaDetailComponent,
@ -20,6 +26,11 @@ import { EncuestaDeleteOptionDialogComponent } from './encuesta-delete-option-di
EncuestaPublishDialogComponent,
EncuestaDeleteQuestionDialogComponent,
EncuestaDeleteOptionDialogComponent,
EncuestaCompartirDialogComponent,
EncuestaCompleteComponent,
EncuestaPasswordDialogComponent,
EncuestaFinalizarDialogComponent,
EncuestaDeleteColaboratorDialogComponent,
],
entryComponents: [EncuestaDeleteDialogComponent],
})

View File

@ -40,10 +40,6 @@
</button>
</div>
<div class="alert alert-warning" id="no-result" *ngIf="encuestas?.length === 0">
<span jhiTranslate="dataSurveyApp.encuesta.home.notFound">No surveys found</span>
</div>
<form class="ds-form">
<div class="input-group">
<div class="ds-filter">
@ -83,8 +79,17 @@
</div>
</form>
<div class="ds-survey" id="entities" *ngIf="encuestas?.length === 0">
<div class="ds-survey--all-question-wrapper">
<ng-container class="">
<p class="ds-title text-center">No posee encuestas</p>
<p class="ds-subtitle text-center">Incie a explorar, colaborar y adquirir datos al crear encuestas mundialmente</p>
</ng-container>
</div>
</div>
<!-- Lista de Encuestas del Usuario -->
<div class="ds-list" (contextmenu)="openContextMenu($event)" *ngIf="!isAdmin()">
<div class="ds-list" (contextmenu)="openContextMenu($event)" *ngIf="!isAdmin() && encuestas?.length !== 0">
<!-- Context Menu -->
<div class="ds-contextmenu ds-contextmenu--closed" id="contextmenu">
<ul id="ds-context-menu__list">
@ -97,7 +102,9 @@
</div>
<div class="ds-contextmenu__divider ds-contextmenu__divider--separator-bottom" id="contextmenu-edit--separator">
<li class="d-justify justify-content-start" id="contextmenu-edit">
<button type="button" (click)="openSurvey(null)"><fa-icon class="contextmenu__icon" [icon]="faEdit"></fa-icon>Editar</button>
<button type="button" data-toggle="modal" data-target="#editarEncuesta">
<fa-icon class="contextmenu__icon" [icon]="faEdit"></fa-icon>Editar
</button>
</li>
<li id="contextmenu-preview">
<button type="button" (click)="openPreview()">
@ -113,9 +120,11 @@
<fa-icon class="contextmenu__icon" [icon]="faUpload"></fa-icon>Publicar
</button>
</li>
<!-- <li>
<button type="button" id="contextmenu-share"><fa-icon class="contextmenu__icon" [icon]="faShareAlt"></fa-icon>Compartir</button>
</li> -->
<li>
<button type="button" id="contextmenu-share" (click)="compartir()">
<fa-icon class="contextmenu__icon" [icon]="faShareAlt"></fa-icon>Compartir
</button>
</li>
</div>
<div class="ds-contextmenu__divider" id="contextmenu-delete--separator">
<li>
@ -168,9 +177,11 @@
style="animation-delay: 3s"
></div>
</div>
<div class="entity-share">
<span><fa-icon [icon]="faShareAlt"></fa-icon></span>
</div>
<!-- <div class="entity-share" *ngIf="encuesta.estado == 'ACTIVE'">
<button type="button" id="contextmenu-share" (click)="compartir()">
<fa-icon class="contextmenu__icon" [icon]="faShareAlt"></fa-icon>
</button>
</div>-->
</div>
<div class="entity-body">
@ -206,7 +217,7 @@
</div>
</div>
<div class="table-responsive" id="entities" *ngIf="isAdmin() && encuestas && encuestas.length > 0">
<table class="table table-striped" aria-describedby="page-heading">
<table class="ds-table table table-striped" aria-describedby="page-heading">
<thead>
<tr>
<th scope="col"><span jhiTranslate="dataSurveyApp.encuesta.nombre">Nombre</span></th>
@ -401,3 +412,150 @@
</div>
</div>
</div>
<!-- Modal -->
<div
class="modal fade ds-modal"
id="editarEncuesta"
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="surveyEditForm"
role="form"
novalidate
(ngSubmit)="editSurvey()"
[formGroup]="surveyEditForm"
>
<div class="modal-header">
<h1 class="modal-title" id="exampleModalLongTitle">Modificar Encuesta</h1>
</div>
<div class="modal-body">
<!-- Survey Modify 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="
surveyEditForm.get('nombre')!.invalid && (surveyEditForm.get('nombre')!.dirty || surveyEditForm.get('nombre')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="surveyEditForm.get('nombre')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
<small
class="form-text text-danger"
*ngIf="surveyEditForm.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="surveyEditForm.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.encuesta.acceso" for="field_acceso">Acceso</label>
<select class="form-control" name="acceso" formControlName="acceso" id="field_acceso" data-cy="acceso">
<option [ngValue]="null">{{ 'dataSurveyApp.AccesoEncuesta.null' | translate }}</option>
<option value="PUBLIC">{{ 'dataSurveyApp.AccesoEncuesta.PUBLIC' | translate }}</option>
<option value="PRIVATE">{{ 'dataSurveyApp.AccesoEncuesta.PRIVATE' | translate }}</option>
</select>
<div
*ngIf="
surveyEditForm.get('acceso')!.invalid && (surveyEditForm.get('acceso')!.dirty || surveyEditForm.get('acceso')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="surveyEditForm.get('acceso')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.encuesta.categoria" for="field_categoria">Categoría</label>
<select class="form-control" id="field_categoria" data-cy="categoria" name="categoria" formControlName="categoria">
<option [ngValue]="null" selected></option>
<option
[ngValue]="
categoriaOption.id === surveyEditForm.get('categoria')!.value?.id
? surveyEditForm.get('categoria')!.value
: categoriaOption
"
*ngFor="let categoriaOption of categoriasSharedCollection; trackBy: trackCategoriaById"
>
{{ categoriaOption.nombre }}
</option>
</select>
<div
*ngIf="
surveyEditForm.get('categoria')!.invalid &&
(surveyEditForm.get('categoria')!.dirty || surveyEditForm.get('categoria')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="surveyEditForm.get('categoria')?.errors?.required"
jhiTranslate="entity.validation.required"
>
This field is required.
</small>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button id="cancelEditSurveyBtn" 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]="surveyEditForm.invalid || isSaving"
>
<span jhiTranslate="entity.action.edit">Edit</span>
</button>
</div>
</form>
</div>
</div>
</div>

View File

@ -41,6 +41,7 @@ import {
} from '@fortawesome/free-solid-svg-icons';
import * as $ from 'jquery';
import { EncuestaCompartirDialogComponent } from '../encuesta-compartir-dialog/encuesta-compartir-dialog.component';
@Component({
selector: 'jhi-encuesta',
@ -99,6 +100,14 @@ export class EncuestaComponent implements OnInit, AfterViewInit {
// usuarioExtra: [],
});
surveyEditForm = this.fb.group({
id: [],
nombre: [null, [Validators.required, Validators.minLength(1), Validators.maxLength(50)]],
descripcion: [],
acceso: [null, [Validators.required]],
categoria: [null, [Validators.required]],
});
createAnother: Boolean = false;
selectedSurveyId: number | null = null;
@ -124,12 +133,16 @@ export class EncuestaComponent implements OnInit, AfterViewInit {
loadAll(): void {
this.isLoading = true;
this.usuarioExtraService
.retrieveAllPublicUsers()
.pipe(finalize(() => this.loadPublicUser()))
.subscribe(res => {
this.userSharedCollection = res;
});
if (this.isAdmin()) {
this.usuarioExtraService
.retrieveAllPublicUsers()
.pipe(finalize(() => this.loadPublicUser()))
.subscribe(res => {
this.userSharedCollection = res;
});
} else {
this.loadEncuestas();
}
}
loadPublicUser(): void {
@ -144,30 +157,7 @@ export class EncuestaComponent implements OnInit, AfterViewInit {
loadUserExtras() {
this.usuarioExtraService
.query()
.pipe(
finalize(() =>
this.encuestaService.query().subscribe(
(res: HttpResponse<IEncuesta[]>) => {
this.isLoading = false;
const tmpEncuestas = res.body ?? [];
if (this.isAdmin()) {
this.encuestas = tmpEncuestas.filter(e => e.estado !== EstadoEncuesta.DELETED);
this.encuestas.forEach(e => {
e.usuarioExtra = this.usuarioExtrasSharedCollection?.find(pU => pU.id == e.usuarioExtra?.id);
});
} else {
this.encuestas = tmpEncuestas
.filter(e => e.usuarioExtra?.id === this.usuarioExtra?.id)
.filter(e => e.estado !== EstadoEncuesta.DELETED);
}
},
() => {
this.isLoading = false;
}
)
)
)
.pipe(finalize(() => this.loadEncuestas()))
.subscribe(
(res: HttpResponse<IUsuarioExtra[]>) => {
this.isLoading = false;
@ -182,6 +172,36 @@ export class EncuestaComponent implements OnInit, AfterViewInit {
);
}
loadEncuestas() {
this.encuestaService.query().subscribe(
(res: HttpResponse<IEncuesta[]>) => {
this.isLoading = false;
const tmpEncuestas = res.body ?? [];
// Fix calificacion
tmpEncuestas.forEach(encuesta => {
const _calificacion = encuesta.calificacion;
encuesta.calificacion = Number(_calificacion?.toString().split('.')[0]);
});
if (this.isAdmin()) {
this.encuestas = tmpEncuestas.filter(e => e.estado !== EstadoEncuesta.DELETED);
this.encuestas.forEach(e => {
e.usuarioExtra = this.usuarioExtrasSharedCollection?.find(pU => pU.id == e.usuarioExtra?.id);
});
} else {
this.encuestas = tmpEncuestas
.filter(e => e.usuarioExtra?.id === this.usuarioExtra?.id)
.filter(e => e.estado !== EstadoEncuesta.DELETED);
}
},
() => {
this.isLoading = false;
}
);
}
ngOnInit(): void {
this.searchString = '';
this.accesoEncuesta = '';
@ -405,7 +425,7 @@ export class EncuestaComponent implements OnInit, AfterViewInit {
nombre: this.editForm.get(['nombre'])!.value,
descripcion: this.editForm.get(['descripcion'])!.value,
fechaCreacion: dayjs(now, DATE_TIME_FORMAT),
calificacion: 5,
calificacion: 5.1,
acceso: this.editForm.get(['acceso'])!.value,
contrasenna: undefined,
estado: EstadoEncuesta.DRAFT,
@ -465,22 +485,32 @@ export class EncuestaComponent implements OnInit, AfterViewInit {
let res = await this.encuestaService.find(this.selectedSurveyId).toPromise();
this.selectedSurvey = res.body;
// Fill in the edit survey
this.fillSurveyEditForm();
this.isPublished = this.selectedSurvey!.estado === 'ACTIVE' || this.selectedSurvey!.estado === 'FINISHED'; // QUE SE LE MUESTRE CUANDO ESTE EN DRAFT
document.getElementById('contextmenu-create--separator')!.style.display = 'none';
document.getElementById('contextmenu-edit--separator')!.style.display = 'block';
document.getElementById('contextmenu-delete--separator')!.style.display = 'block';
document.getElementById('contextmenu-edit')!.style.display = 'block';
document.getElementById('contextmenu-edit--separator')!.style.display = 'block';
document.getElementById('contextmenu-preview')!.style.display = 'block';
if (!this.isPublished) {
document.getElementById('contextmenu-edit--separator')!.style.display = 'block';
document.getElementById('contextmenu-edit')!.style.display = 'block';
document.getElementById('contextmenu-publish')!.style.display = 'block';
document.getElementById('contextmenu-duplicate')!.style.display = 'block';
document.getElementById('contextmenu-share')!.style.display = 'none';
} else {
document.getElementById('contextmenu-edit')!.style.display = 'none';
document.getElementById('contextmenu-publish')!.style.display = 'none';
document.getElementById('contextmenu-duplicate')!.style.display = 'none';
document.getElementById('contextmenu-share')!.style.display = 'block';
}
// document.getElementById('contextmenu-share')!.style.display = 'block';
if (this.selectedSurvey!.estado === 'FINISHED') {
document.getElementById('contextmenu-share')!.style.display = 'none';
}
document.getElementById('contextmenu-create--separator')!.style.display = 'none';
}
@ -508,4 +538,40 @@ export class EncuestaComponent implements OnInit, AfterViewInit {
const res = await this.encuestaService.duplicate(this.selectedSurveyId!).toPromise();
this.loadAll();
}
editSurvey(): void {
const survey = { ...this.selectedSurvey };
survey.nombre = this.surveyEditForm.get(['nombre'])!.value;
survey.descripcion = this.surveyEditForm.get(['descripcion'])!.value;
survey.acceso = this.surveyEditForm.get(['acceso'])!.value;
survey.categoria = this.surveyEditForm.get(['categoria'])!.value;
// Prevent user update by setting to null
survey.usuarioExtra!.user = null;
this.encuestaService.updateSurvey(survey).subscribe(res => {
this.loadAll();
$('#cancelEditSurveyBtn').click();
});
}
fillSurveyEditForm(): void {
this.surveyEditForm.patchValue({
nombre: this.selectedSurvey!.nombre,
descripcion: this.selectedSurvey!.descripcion,
acceso: this.selectedSurvey!.acceso,
categoria: this.selectedSurvey!.categoria,
});
}
compartir(): void {
const modalRef = this.modalService.open(EncuestaCompartirDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.componentInstance.encuesta = this.selectedSurvey;
// unsubscribe not needed because closed completes on modal close
modalRef.closed.subscribe(reason => {
if (reason === 'published') {
this.successPublished = true;
this.loadAll();
}
});
}
}

View File

@ -6,6 +6,7 @@ import { EncuestaComponent } from '../list/encuesta.component';
import { EncuestaDetailComponent } from '../detail/encuesta-detail.component';
import { EncuestaUpdateComponent } from '../update/encuesta-update.component';
import { EncuestaRoutingResolveService } from './encuesta-routing-resolve.service';
import { EncuestaCompleteComponent } from '../complete/complete.component';
const encuestaRoute: Routes = [
{
@ -37,6 +38,14 @@ const encuestaRoute: Routes = [
},
canActivate: [UserRouteAccessService],
},
{
path: ':id/complete',
component: EncuestaCompleteComponent,
resolve: {
encuesta: EncuestaRoutingResolveService,
},
canActivate: [UserRouteAccessService],
},
];
@NgModule({

View File

@ -26,6 +26,14 @@ export class EncuestaService {
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}
createFromTemplate(encuesta: IEncuesta, plantillaId: Number): Observable<EntityResponseType> {
const copy = this.convertDateFromClient(encuesta);
return this.http
.post<IEncuesta>(`${this.resourceUrl}/${plantillaId}`, copy, { observe: 'response' })
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}
//update para publicar
update(encuesta: IEncuesta): Observable<EntityResponseType> {
const copy = this.convertDateFromClient(encuesta);
return this.http
@ -33,6 +41,14 @@ export class EncuestaService {
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}
//update normal
updateSurvey(encuesta: IEncuesta): Observable<EntityResponseType> {
const copy = this.convertDateFromClient(encuesta);
return this.http
.put<IEncuesta>(`${this.resourceUrl}/update/${getEncuestaIdentifier(encuesta) as number}`, copy, { observe: 'response' })
.pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));
}
partialUpdate(encuesta: IEncuesta): Observable<EntityResponseType> {
const copy = this.convertDateFromClient(encuesta);
return this.http
@ -93,6 +109,10 @@ export class EncuestaService {
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[] {
const encuestas: IEncuesta[] = encuestasToCheck.filter(isPresent);
if (encuestas.length > 0) {

View File

@ -1,7 +1,9 @@
<div>
<h2 id="page-heading" data-cy="EPreguntaCerradaHeading">
<div class="d-flex align-items-center">
<p class="ds-title">{{ encuesta!.nombre }}</p>
<p class="ds-title ds-contenteditable" contenteditable="true" spellcheck="false" (blur)="updateSurveyName($event)">
{{ encuesta!.nombre }}
</p>
&nbsp;&nbsp;<fa-icon
class="ds-info--icon"
[icon]="faQuestion"
@ -10,6 +12,33 @@
(click)="loadAplicationParameters()"
></fa-icon>
&nbsp;&nbsp;<fa-icon class="ds-info--icon" [icon]="faEye" (click)="openPreview()"></fa-icon>
<div class="d-flex px-4">
<div class="col-12 ds-list-collabs">
<div class="row" style="flex-direction: row-reverse">
<div class="col-mb-2 iconos-colab">
<div class="add-collab" data-toggle="modal" data-target="#modalAddColaborators">
<fa-icon icon="sync" [icon]="faPlus"></fa-icon>
</div>
</div>
<div
class="col-mb-2 iconos-colab"
*ngFor="let colaborador of usuariosColaboradores"
(click)="selectColaborator(colaborador)"
data-toggle="modal"
data-target="#modalUpdateColaborators"
>
<img
class="photo-collab"
*ngIf="colaborador.usuarioExtra"
src="../../../../content/profile_icons/C{{ colaborador.usuarioExtra.iconoPerfil }}.png"
alt="{{ colaborador.usuarioExtra.nombre }}"
[attr.data-id]="colaborador.id"
/>
</div>
</div>
</div>
</div>
</div>
<p class="ds-subtitle">Creada el día {{ encuesta!.fechaCreacion | formatShortDatetime | lowercase }}</p>
@ -29,9 +58,14 @@
[disabled]="isLoading"
data-toggle="modal"
data-target="#crearPregunta"
*ngIf="encuesta!.estado !== 'FINISHED' && (isAutor() || isEscritor())"
>
<fa-icon icon="sync" [icon]="faPlus"></fa-icon>&nbsp;&nbsp;<span>Crear pregunta</span>
</button>
<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>
</h2>
@ -66,9 +100,20 @@
class="ds-survey--question"
>
<div class="ds-survey--titulo">
<span class="ds-survey--titulo--name">{{ i + 1 }}. {{ ePregunta.nombre }}</span>
<span class="ds-survey--titulo--name">
<span>{{ i + 1 }}.</span>&nbsp;
<span
class="ds-contenteditable"
[attr.data-id]="ePregunta.id"
[attr.data-tipo]="ePregunta.tipo"
contenteditable="true"
spellcheck="false"
(blur)="updateQuestionName($event)"
>{{ ePregunta.nombre }}</span
>
</span>
<fa-icon
*ngIf="encuesta!.estado === 'DRAFT'"
*ngIf="encuesta!.estado === 'DRAFT' && (isAutor() || isEscritor())"
class="ds-survey--titulo--icon"
[icon]="faTimes"
(click)="deleteQuestion($event)"
@ -100,7 +145,7 @@
<!-- <input class="ds-survey--checkbox" id="{{ ePregunta.id }}-{{ ePreguntaOpcionFinal.id }}" type="checkbox" disabled /> -->
<label for="{{ ePregunta.id }}-{{ ePreguntaOpcionFinal.id }}">{{ ePreguntaOpcionFinal.nombre }}</label>
<fa-icon
*ngIf="encuesta!.estado === 'DRAFT'"
*ngIf="encuesta!.estado === 'DRAFT' && (isAutor() || isEscritor())"
class="ds-survey--titulo--icon ds-survey--titulo--icon--small"
[icon]="faTimes"
(click)="deleteOption($event)"
@ -116,6 +161,7 @@
data-toggle="modal"
data-target="#crearOpcion"
[attr.data-id]="ePregunta.id"
*ngIf="isAutor() || isEscritor()"
>
<fa-icon
class="ds-survey--add-option--icon"
@ -224,7 +270,7 @@
[formGroup]="editFormQuestion"
>
<div class="modal-header">
<h1 class="modal-title" id="exampleModalLongTitle2">Crear Pregunta</h1>
<h1 class="modal-title" id="exampleModalLongTitle1">Crear Pregunta</h1>
</div>
<div class="modal-body">
<!-- Survey Create Question Modal -->
@ -367,7 +413,7 @@
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title" id="exampleModalLongTitle">Información de Encuesta</h1>
<h1 class="modal-title" id="exampleModalLongTitle2">Información de Encuesta</h1>
</div>
<!-- {
@ -400,3 +446,163 @@
</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 { 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 { 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 { EPreguntaCerradaOpcionService } from './../../e-pregunta-cerrada-opcion/service/e-pregunta-cerrada-opcion.service';
import { AfterViewChecked, Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { finalize, map } from 'rxjs/operators';
import { finalize } from 'rxjs/operators';
import * as dayjs from 'dayjs';
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 { ICategoria } from 'app/entities/categoria/categoria.model';
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 { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@ -25,14 +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 { 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 { EncuestaDeleteQuestionDialogComponent } from '../encuesta-delete-question-dialog/encuesta-delete-question-dialog.component';
import { EncuestaDeleteOptionDialogComponent } from '../encuesta-delete-option-dialog/encuesta-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 { UsuarioEncuestaService } from 'app/entities/usuario-encuesta/service/usuario-encuesta.service';
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({
selector: 'jhi-encuesta-update',
@ -47,9 +59,17 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
isSaving = false;
isSavingQuestion = false;
isSavingCollab = false;
isSavingAddCollab = false;
finalizada = false;
public rolSeleccionado: RolColaborador | undefined = undefined;
categoriasSharedCollection: ICategoria[] = [];
usuarioExtrasSharedCollection: IUsuarioExtra[] = [];
usuariosColaboradores: IUsuarioEncuesta[] = [];
colaborador: IUsuarioEncuesta | null = null;
account: Account | null = null;
usuarioExtra: UsuarioExtra | null = null;
// editForm = this.fb.group({
// id: [],
@ -83,6 +103,15 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
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[];
ePreguntasOpciones?: any[];
encuesta: Encuesta | null = null;
@ -94,6 +123,11 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
createAnotherQuestion: Boolean = false;
selectedQuestionToCreateOption: IEPreguntaCerrada | null = null;
userPublicCollab: IUser | null = null;
usuarioExtraCollab: UsuarioExtra | null = null;
userCollabNotExist: boolean = false;
userCollabIsCollab: boolean = false;
userCollabIsAutor: boolean = false;
constructor(
protected encuestaService: EncuestaService,
protected categoriaService: CategoriaService,
@ -105,7 +139,10 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
protected ePreguntaCerradaOpcionService: EPreguntaCerradaOpcionService,
protected parametroAplicacionService: ParametroAplicacionService,
protected ePreguntaAbiertaService: EPreguntaAbiertaService,
protected router: Router
protected usuarioEncuestaService: UsuarioEncuestaService,
protected router: Router,
protected accountService: AccountService,
protected userService: UserService
) {}
loadAll(): void {
@ -115,7 +152,6 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
(res: any) => {
this.isLoading = false;
this.ePreguntas = res.body ?? [];
console.log(this.ePreguntas);
},
() => {
this.isLoading = false;
@ -131,12 +167,21 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
this.isLoading = false;
}
);
this.usuarioEncuestaService.findCollaborators(this.encuesta?.id!).subscribe(
(res: any) => {
this.isLoading = false;
this.usuariosColaboradores = res.body ?? [];
},
() => {
this.isLoading = false;
}
);
}
async loadAplicationParameters(): Promise<void> {
const params = await this.parametroAplicacionService.find(1).toPromise();
this.parametrosAplicacion = params.body;
//console.log(this.parametrosAplicacion);
}
ngOnInit(): void {
@ -157,10 +202,19 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
// 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 {
this.initListeners();
// this.initListeners();
}
trackId(index: number, item: IEPreguntaCerrada): number {
@ -178,18 +232,18 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
});
}
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');
}
});
}
}
// 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 {
window.history.back();
@ -332,7 +386,6 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
createQuestion(): void {
const surveyId = this.encuesta?.id;
console.log(surveyId);
}
protected createFromFormClosedQuestion(): IEPreguntaCerrada {
@ -416,6 +469,57 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
this.isSavingQuestion = false;
}
updateSurveyName(event: any) {
const updatedSurveyName = event.target.innerText;
if (updatedSurveyName !== this.encuesta?.nombre) {
const survey = { ...this.encuesta };
survey.nombre = updatedSurveyName;
// Prevent user update by setting to null
survey.usuarioExtra!.user = null;
this.encuestaService.updateSurvey(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.ePreguntaCerradaService.find(questionId).subscribe(res => {
const ePreguntaCerrada: EPreguntaCerrada | null = res.body ?? null;
const updatedEPreguntaCerrada = { ...ePreguntaCerrada };
if (questionName !== ePreguntaCerrada?.nombre && ePreguntaCerrada !== null) {
updatedEPreguntaCerrada.nombre = questionName;
this.ePreguntaCerradaService.update(updatedEPreguntaCerrada).subscribe(updatedQuestion => {
console.log(updatedQuestion);
});
}
});
} else {
// Open question
// Closed question
this.ePreguntaAbiertaService.find(questionId).subscribe(res => {
const ePreguntaAbierta: EPreguntaAbierta | null = res.body ?? null;
const updatedEPreguntaAbierta = { ...ePreguntaAbierta };
if (questionName !== ePreguntaAbierta?.nombre && ePreguntaAbierta !== null) {
updatedEPreguntaAbierta.nombre = questionName;
this.ePreguntaAbiertaService.update(updatedEPreguntaAbierta).subscribe(updatedQuestion => {
console.log(updatedQuestion);
});
}
});
}
// const questionId = event.target.dataset.id;
// const survey = { ...this.encuesta };
// survey.nombre = updatedQuestionName;
// // Prevent user update by setting to null
// survey.usuarioExtra!.user = null;
// this.encuestaService.updateSurvey(survey).subscribe(res => {});
}
// previousState(): void {
// window.history.back();
// }
@ -532,4 +636,187 @@ export class EncuestaUpdateComponent implements OnInit, AfterViewChecked {
// 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),
},
{
path: 'usuario-encuesta',
path: 'colaboraciones',
data: { pageTitle: 'dataSurveyApp.usuarioEncuesta.home.title' },
loadChildren: () => import('./usuario-encuesta/usuario-encuesta.module').then(m => m.UsuarioEncuestaModule),
},
@ -77,6 +77,21 @@ import { RouterModule } from '@angular/router';
loadChildren: () =>
import('./p-pregunta-cerrada-opcion/p-pregunta-cerrada-opcion.module').then(m => m.PPreguntaCerradaOpcionModule),
},
{
path: 'mis-plantillas',
data: { pageTitle: 'dataSurveyApp.usuarioExtra.plantillas.title' },
loadChildren: () => import('./usuario-plantillas/usuario-plantillas.module').then(m => m.UsuarioPlantillasModule),
},
{
path: 'dashboard',
data: { pageTitle: 'dataSurveyApp.Dashboard.title' },
loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule),
},
{
path: 'dashboard',
data: { pageTitle: 'dataSurveyApp.Dashboard.title' },
loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule),
},
/* jhipster-needle-add-entity-route - JHipster will add entity modules routes here */
]),
],

View File

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

View File

@ -1,24 +1,23 @@
<form *ngIf="plantilla" name="deleteForm" (ngSubmit)="confirmDelete(plantilla.id!)">
<div class="modal-header">
<h4 class="modal-title" data-cy="plantillaDeleteDialogHeading" jhiTranslate="entity.delete.title">Confirm delete operation</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" (click)="cancel()">&times;</button>
</div>
<form class="ds-form" *ngIf="plantilla" name="deleteForm" (ngSubmit)="confirmDelete(plantilla)">
<div class="modal-body">
<jhi-alert-error></jhi-alert-error>
<p id="jhi-delete-plantilla-heading" jhiTranslate="dataSurveyApp.plantilla.delete.question" [translateValues]="{ id: plantilla.id }">
<p class="ds-title--small">Eliminar plantilla</p>
<p
class="ds-subtitle"
id="jhi-delete-plantilla-heading"
jhiTranslate="dataSurveyApp.plantilla.delete.question"
[translateValues]="{ id: plantilla.id }"
>
Are you sure you want to delete this Plantilla?
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" (click)="cancel()">
<fa-icon icon="ban"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
<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-plantilla" data-cy="entityConfirmDeleteButton" type="submit" class="btn btn-danger">
<button id="jhi-confirm-delete-plantilla" 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>

View File

@ -1,65 +0,0 @@
jest.mock('@ng-bootstrap/ng-bootstrap');
import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing';
import { HttpResponse } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { of } from 'rxjs';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { PlantillaService } from '../service/plantilla.service';
import { PlantillaDeleteDialogComponent } from './plantilla-delete-dialog.component';
describe('Component Tests', () => {
describe('Plantilla Management Delete Component', () => {
let comp: PlantillaDeleteDialogComponent;
let fixture: ComponentFixture<PlantillaDeleteDialogComponent>;
let service: PlantillaService;
let mockActiveModal: NgbActiveModal;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [PlantillaDeleteDialogComponent],
providers: [NgbActiveModal],
})
.overrideTemplate(PlantillaDeleteDialogComponent, '')
.compileComponents();
fixture = TestBed.createComponent(PlantillaDeleteDialogComponent);
comp = fixture.componentInstance;
service = TestBed.inject(PlantillaService);
mockActiveModal = TestBed.inject(NgbActiveModal);
});
describe('confirmDelete', () => {
it('Should call delete service on confirmDelete', inject(
[],
fakeAsync(() => {
// GIVEN
jest.spyOn(service, 'delete').mockReturnValue(of(new HttpResponse({})));
// WHEN
comp.confirmDelete(123);
tick();
// THEN
expect(service.delete).toHaveBeenCalledWith(123);
expect(mockActiveModal.close).toHaveBeenCalledWith('deleted');
})
));
it('Should not call delete service on clear', () => {
// GIVEN
jest.spyOn(service, 'delete');
// WHEN
comp.cancel();
// THEN
expect(service.delete).not.toHaveBeenCalled();
expect(mockActiveModal.close).not.toHaveBeenCalled();
expect(mockActiveModal.dismiss).toHaveBeenCalled();
});
});
});
});

View File

@ -3,6 +3,7 @@ import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { IPlantilla } from '../plantilla.model';
import { PlantillaService } from '../service/plantilla.service';
import { EstadoPlantilla } from '../../enumerations/estado-plantilla.model';
@Component({
templateUrl: './plantilla-delete-dialog.component.html',
@ -16,8 +17,9 @@ export class PlantillaDeleteDialogComponent {
this.activeModal.dismiss();
}
confirmDelete(id: number): void {
this.plantillaService.delete(id).subscribe(() => {
confirmDelete(pPlantilla: IPlantilla): void {
pPlantilla.estado = EstadoPlantilla.DELETED;
this.plantillaService.update(pPlantilla).subscribe(() => {
this.activeModal.close('deleted');
});
}

View File

@ -1,58 +1,86 @@
<div class="row justify-content-center">
<div class="col-8">
<div *ngIf="plantilla">
<h2 data-cy="plantillaDetailsHeading"><span jhiTranslate="dataSurveyApp.plantilla.detail.title">Plantilla</span></h2>
<div class="container-fluid" *ngIf="plantilla">
<div>
<h2 id="page-heading" data-cy="PPreguntaCerradaHeading">
<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">
<dt><span jhiTranslate="global.field.id">ID</span></dt>
<dd>
<span>{{ plantilla.id }}</span>
</dd>
<dt><span jhiTranslate="dataSurveyApp.plantilla.nombre">Nombre</span></dt>
<dd>
<span>{{ plantilla.nombre }}</span>
</dd>
<dt><span jhiTranslate="dataSurveyApp.plantilla.descripcion">Descripcion</span></dt>
<dd>
<span>{{ plantilla.descripcion }}</span>
</dd>
<dt><span jhiTranslate="dataSurveyApp.plantilla.fechaCreacion">Fecha Creacion</span></dt>
<dd>
<span>{{ plantilla.fechaCreacion | formatMediumDatetime }}</span>
</dd>
<dt><span jhiTranslate="dataSurveyApp.plantilla.fechaPublicacionTienda">Fecha Publicacion Tienda</span></dt>
<dd>
<span>{{ plantilla.fechaPublicacionTienda | formatMediumDatetime }}</span>
</dd>
<dt><span jhiTranslate="dataSurveyApp.plantilla.estado">Estado</span></dt>
<dd>
<span jhiTranslate="{{ 'dataSurveyApp.EstadoPlantilla.' + plantilla.estado }}">{{ plantilla.estado }}</span>
</dd>
<dt><span jhiTranslate="dataSurveyApp.plantilla.precio">Precio</span></dt>
<dd>
<span>{{ plantilla.precio }}</span>
</dd>
<dt><span jhiTranslate="dataSurveyApp.plantilla.categoria">Categoria</span></dt>
<dd>
<div *ngIf="plantilla.categoria">
<a [routerLink]="['/categoria', plantilla.categoria?.id, 'view']">{{ plantilla.categoria?.nombre }}</a>
<div class="ds-survey preview-survey" id="entities">
<div class="ds-survey--all-question-wrapper col-8">
<ng-container *ngIf="pPreguntas && pPreguntas.length === 0">
<p class="ds-title text-center">Plantilla vacía</p>
<p class="ds-subtitle text-center">Inicie creando preguntas y opciones para su plantilla.</p>
</ng-container>
<div class="ds-survey--question-wrapper card-plantilla" *ngFor="let pPregunta of pPreguntas; let i = index; trackBy: trackId">
<div
[attr.data-index]="pPregunta.id"
[attr.data-tipo]="pPregunta.tipo"
[attr.data-opcional]="pPregunta.opcional"
class="ds-survey--question"
>
<div class="ds-survey--titulo">
<span class="ds-survey--titulo--name">{{ i + 1 }}. {{ pPregunta.nombre }}</span>
</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"
>
<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 class="ds-survey--textarea" cols="30" rows="10" disabled></textarea>
</div>
</div>
</dd>
</dl>
<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>

View File

@ -1,21 +1,152 @@
import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms';
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({
selector: 'jhi-plantilla-detail',
templateUrl: './plantilla-detail.component.html',
})
export class PlantillaDetailComponent implements OnInit {
categoriasSharedCollection: ICategoria[] = [];
usuarioExtrasSharedCollection: IUsuarioExtra[] = [];
faTimes = faTimes;
faPlus = faPlus;
faStar = faStar;
faQuestion = faQuestion;
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 {
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 {

View File

@ -1,41 +1,74 @@
<div>
<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">
<button class="btn btn-info mr-2" (click)="loadAll()" [disabled]="isLoading">
<fa-icon icon="sync" [spin]="isLoading"></fa-icon>
<span jhiTranslate="dataSurveyApp.plantilla.home.refreshListLabel">Refresh List</span>
</button>
<div>
<button class="ds-btn ds-btn--secondary" (click)="loadAll()" [disabled]="isLoading">
<fa-icon icon="sync" [spin]="isLoading"></fa-icon>
<span jhiTranslate="dataSurveyApp.plantilla.home.refreshListLabel">Refresh List</span>
</button>
<button
id="jh-create-entity"
data-cy="entityCreateButton"
class="btn btn-primary jh-create-entity create-plantilla"
[routerLink]="['/plantilla/new']"
>
<fa-icon icon="plus"></fa-icon>
<span jhiTranslate="dataSurveyApp.plantilla.home.createLabel"> Create a new Plantilla </span>
</button>
<button
*ngIf="isAdmin() && isAuthenticated()"
type="button"
class="ds-btn ds-btn--primary"
(click)="resetCreateTemplateForm()"
data-toggle="modal"
data-target="#crearPlantilla"
>
Crear plantilla
</button>
</div>
</div>
</h2>
<form class="ds-form" *ngIf="isAdmin() && isAuthenticated()">
<div class="input-group">
<div class="ds-filter">
<div class="input-group-addon"><i class="glyphicon glyphicon-search"></i></div>
<input type="text" name="searchString" placeholder="Buscar por nombre..." [(ngModel)]="searchString" />
</div>
<div class="ds-filter">
<div class="input-group-addon"><i class="glyphicon glyphicon-search"></i></div>
<select name="estadoPlantilla" id="estadoPlantilla" [(ngModel)]="estadoPlantilla" style="width: 200px">
<option value="" selected="selected" disabled="disabled">Filtrar por estado</option>
<option value="">Todos Estados</option>
<option value="Draft">Borradores</option>
<option value="Active">En tienda</option>
<option value="Disabled">Desactivadas</option>
</select>
</div>
<jhi-alert-error></jhi-alert-error>
<!--<div class="col-3">
<div class="input-group-addon "><i class="glyphicon glyphicon-search"></i></div>
<select id="categoriaEncuesta" name="categoriaEncuesta" [(ngModel)]="categoriaEncuesta">
<option [ngValue]="null" selected>Filtre por categoría</option>
<option
*ngFor="let categoriaOption of categoriasSharedCollection; trackBy: trackCategoriaById"
[ngValue]="categoriaOption.nombre" >
{{ categoriaOption.nombre }}
</option>
</select>
</div>-->
</div>
</form>
<!-- <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">
<span jhiTranslate="dataSurveyApp.plantilla.home.notFound">No plantillas found</span>
<span jhiTranslate="dataSurveyApp.plantilla.home.notFound">No templates found</span>
</div>
<div class="table-responsive" id="entities" *ngIf="plantillas && plantillas.length > 0">
<table class="table table-striped" aria-describedby="page-heading">
<table class="ds-table table table-striped" aria-describedby="page-heading">
<thead>
<tr>
<th scope="col"><span jhiTranslate="global.field.id">ID</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.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.estado">Estado</span></th>
<th scope="col"><span jhiTranslate="dataSurveyApp.plantilla.precio">Precio</span></th>
@ -44,44 +77,42 @@
</tr>
</thead>
<tbody>
<tr *ngFor="let plantilla of plantillas; trackBy: trackId" data-cy="entityTable">
<td>
<a [routerLink]="['/plantilla', plantilla.id, 'view']">{{ plantilla.id }}</a>
</td>
<tr
*ngFor="let plantilla of plantillas | filter: 'nombre':searchString | filter: 'estado':estadoPlantilla; trackBy: trackId"
data-cy="entityTable"
>
<td>{{ plantilla.nombre }}</td>
<td>{{ plantilla.descripcion }}</td>
<td>{{ plantilla.fechaCreacion | formatMediumDatetime }}</td>
<td>{{ plantilla.fechaPublicacionTienda | formatMediumDatetime }}</td>
<!-- <td>{{ plantilla.fechaCreacion | 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>{{ plantilla.precio }}</td>
<td>
<div *ngIf="plantilla.categoria">
<a [routerLink]="['/categoria', plantilla.categoria?.id, 'view']">{{ plantilla.categoria?.nombre }}</a>
</div>
</td>
<td *ngIf="plantilla.precio! > 0">${{ plantilla.precio | number: '1.2' }}</td>
<td *ngIf="plantilla.precio! === 0">Gratis</td>
<td>{{ plantilla.categoria?.nombre }}</td>
<td class="text-right">
<div class="btn-group">
<button
<!-- <button
type="submit"
[routerLink]="['/plantilla', plantilla.id, 'view']"
class="btn btn-info btn-sm"
class="ds-btn ds-btn--secondary btn-sm"
data-cy="entityDetailsButton"
>
<fa-icon icon="eye"></fa-icon>
<span class="d-none d-md-inline" jhiTranslate="entity.action.view">View</span>
</button>
<span class="d-none d-md-inline">Vista previa</span>
</button> -->
<button
type="submit"
[routerLink]="['/plantilla', plantilla.id, 'edit']"
class="btn btn-primary btn-sm"
class="ds-btn ds-btn--primary btn-sm"
data-cy="entityEditButton"
>
<fa-icon icon="pencil-alt"></fa-icon>
<span class="d-none d-md-inline" jhiTranslate="entity.action.edit">Edit</span>
</button>
<button type="submit" (click)="delete(plantilla)" class="btn btn-danger btn-sm" data-cy="entityDeleteButton">
<button type="submit" (click)="cambiarEstado(plantilla)" class="ds-btn btn-warning btn-sm" data-cy="entityDeleteButton">
<fa-icon [icon]="faExchangeAlt"></fa-icon>
<span class="d-none d-md-inline" jhiTranslate="dataSurveyApp.plantilla.updated.buttonChangeEstado">Change status</span>
</button>
<button type="submit" (click)="delete(plantilla)" 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="entity.action.delete">Delete</span>
</button>
@ -92,3 +123,164 @@
</table>
</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,26 @@
import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
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 { 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';
import { PlantillaChangeStatusDialogComponent } from '../plantilla-change-status-dialog/plantilla-change-status-dialog.component';
import { faExchangeAlt } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'jhi-plantilla',
templateUrl: './plantilla.component.html',
@ -13,16 +28,45 @@ import { PlantillaDeleteDialogComponent } from '../delete/plantilla-delete-dialo
export class PlantillaComponent implements OnInit {
plantillas?: IPlantilla[];
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]],
});
faExchangeAlt = faExchangeAlt;
public searchString: string;
public estadoPlantilla: string;
constructor(
protected plantillaService: PlantillaService,
protected modalService: NgbModal,
protected accountService: AccountService,
protected fb: FormBuilder,
protected categoriaService: CategoriaService
) {
this.searchString = '';
this.estadoPlantilla = '';
}
loadAll(): void {
this.isLoading = true;
this.searchString = '';
this.estadoPlantilla = '';
this.plantillaService.query().subscribe(
(res: HttpResponse<IPlantilla[]>) => {
this.isLoading = false;
this.plantillas = res.body ?? [];
const tempPlantillas = res.body ?? [];
this.plantillas = tempPlantillas.filter(p => p.estado !== EstadoPlantilla.DELETED);
},
() => {
this.isLoading = false;
@ -32,9 +76,10 @@ export class PlantillaComponent implements OnInit {
ngOnInit(): void {
this.loadAll();
this.loadRelationshipsOptions();
}
trackId(index: number, item: IPlantilla): number {
trackId(_index: number, item: IPlantilla): number {
return item.id!;
}
@ -48,4 +93,101 @@ export class PlantillaComponent implements OnInit {
}
});
}
cambiarEstado(plantilla: IPlantilla): void {
const modalRef = this.modalService.open(PlantillaChangeStatusDialogComponent, { size: 'lg', backdrop: 'static' });
modalRef.componentInstance.plantilla = plantilla;
// unsubscribe not needed because closed completes on modal close
modalRef.closed.subscribe(reason => {
if (reason === 'updated') {
this.loadAll();
}
});
}
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,32 @@
<form *ngIf="plantilla" class="ds-form" name="changeStatusForm" (ngSubmit)="confirmChangeStatus(plantilla)">
<div class="modal-body">
<p class="ds-title--small">Cambiar estado</p>
<p
*ngIf="plantilla.estado != 'DISABLED'"
class="ds-subtitle"
id="jhi-inactive-plantilla-heading"
jhiTranslate="dataSurveyApp.plantilla.desactivar.question"
>
Are you sure you want to delete this option?
</p>
<p
*ngIf="plantilla.estado == 'DISABLED'"
class="ds-subtitle"
id="jhi-active-plantilla-heading"
jhiTranslate="dataSurveyApp.plantilla.activar.question"
>
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-change-status-option" data-cy="entityConfirmChangeButton" type="submit" class="ds-btn btn-warning">
<fa-icon [icon]="faExchangeAlt"></fa-icon>
<span class="d-none d-md-inline" jhiTranslate="dataSurveyApp.plantilla.updated.buttonChangeEstado">Cambiar estado</span>
</button>
</div>
</form>

View File

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

View File

@ -0,0 +1,36 @@
import { Component } from '@angular/core';
import { PlantillaService } from '../service/plantilla.service';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { EstadoPlantilla } from '../../enumerations/estado-plantilla.model';
import { IPlantilla } from '../plantilla.model';
import { faExchangeAlt } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'jhi-plantilla-change-status-dialog',
templateUrl: './plantilla-change-status-dialog.component.html',
styleUrls: ['./plantilla-change-status-dialog.component.scss'],
})
export class PlantillaChangeStatusDialogComponent {
plantilla?: IPlantilla;
faExchangeAlt = faExchangeAlt;
constructor(protected plantillaService: PlantillaService, protected activeModal: NgbActiveModal) {}
cancel(): void {
this.activeModal.dismiss();
}
confirmChangeStatus(pPlantilla: IPlantilla) {
if (this.plantilla) {
if (pPlantilla.estado === EstadoPlantilla.DISABLED) {
this.plantilla.estado = EstadoPlantilla.DRAFT;
} else {
this.plantilla.estado = EstadoPlantilla.DISABLED;
}
this.plantillaService.update(this.plantilla).subscribe(() => {
this.activeModal.close('updated');
});
}
}
}

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>

Some files were not shown because too many files have changed in this diff Show More