diff --git a/src/main/java/org/datasurvey/web/rest/PPreguntaCerradaOpcionResource.java b/src/main/java/org/datasurvey/web/rest/PPreguntaCerradaOpcionResource.java index 3dcc603..24a5b1b 100644 --- a/src/main/java/org/datasurvey/web/rest/PPreguntaCerradaOpcionResource.java +++ b/src/main/java/org/datasurvey/web/rest/PPreguntaCerradaOpcionResource.java @@ -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 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 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(); + } } diff --git a/src/main/java/org/datasurvey/web/rest/PlantillaResource.java b/src/main/java/org/datasurvey/web/rest/PlantillaResource.java index 1b94fc2..c3b3114 100644 --- a/src/main/java/org/datasurvey/web/rest/PlantillaResource.java +++ b/src/main/java/org/datasurvey/web/rest/PlantillaResource.java @@ -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> getPreguntasByIdPlantilla(@PathVariable Long id) { + List preguntasCerradas = pPreguntaCerradaService.findAll(); + List preguntasAbiertas = pPreguntaAbiertaService.findAll(); + List preguntas = Stream.concat(preguntasCerradas.stream(), preguntasAbiertas.stream()).collect(Collectors.toList()); + List 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>> getPreguntaCerradaOpcionByIdPlantilla(@PathVariable Long id) { + List> res = new ArrayList<>(); + List preguntasCerradas = pPreguntaCerradaService.findAll(); + List preguntasCerradasFiltered = preguntasCerradas + .stream() + .filter(p -> Objects.nonNull(p.getPlantilla())) + .filter(p -> p.getPlantilla().getId().equals(id)) + .collect(Collectors.toList()); + List opciones = pPreguntaCerradaOpcionService.findAll(); + + for (PPreguntaCerrada pPreguntaCerrada : preguntasCerradasFiltered) { + long preguntaCerradaId = pPreguntaCerrada.getId(); + List 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. * diff --git a/src/main/webapp/app/entities/p-pregunta-cerrada-opcion/service/p-pregunta-cerrada-opcion.service.ts b/src/main/webapp/app/entities/p-pregunta-cerrada-opcion/service/p-pregunta-cerrada-opcion.service.ts index 0edd78f..6b5593b 100644 --- a/src/main/webapp/app/entities/p-pregunta-cerrada-opcion/service/p-pregunta-cerrada-opcion.service.ts +++ b/src/main/webapp/app/entities/p-pregunta-cerrada-opcion/service/p-pregunta-cerrada-opcion.service.ts @@ -16,8 +16,8 @@ export class PPreguntaCerradaOpcionService { constructor(protected http: HttpClient, protected applicationConfigService: ApplicationConfigService) {} - create(pPreguntaCerradaOpcion: IPPreguntaCerradaOpcion): Observable { - return this.http.post(this.resourceUrl, pPreguntaCerradaOpcion, { observe: 'response' }); + create(pPreguntaCerradaOpcion: IPPreguntaCerradaOpcion, preguntaId?: number): Observable { + return this.http.post(`${this.resourceUrl}/${preguntaId}`, pPreguntaCerradaOpcion, { observe: 'response' }); } update(pPreguntaCerradaOpcion: IPPreguntaCerradaOpcion): Observable { @@ -49,6 +49,10 @@ export class PPreguntaCerradaOpcionService { return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' }); } + deleteMany(ids: number[]): Observable { + return this.http.post(`${this.resourceUrl}/deleteMany`, ids, { observe: 'response' }); + } + addPPreguntaCerradaOpcionToCollectionIfMissing( pPreguntaCerradaOpcionCollection: IPPreguntaCerradaOpcion[], ...pPreguntaCerradaOpcionsToCheck: (IPPreguntaCerradaOpcion | null | undefined)[] diff --git a/src/main/webapp/app/entities/plantilla/list/plantilla.component.html b/src/main/webapp/app/entities/plantilla/list/plantilla.component.html index ba8d9d5..400e2c0 100644 --- a/src/main/webapp/app/entities/plantilla/list/plantilla.component.html +++ b/src/main/webapp/app/entities/plantilla/list/plantilla.component.html @@ -1,22 +1,28 @@

- Plantillas +
+
+ Encuestas +

Administre las plantillas comprables de la tienda

+
-
- +
+ - + +

@@ -34,7 +40,7 @@ Nombre Descripcion - Fecha Creacion + Fecha Publicacion Tienda Estado Precio @@ -46,25 +52,22 @@ {{ plantilla.nombre }} {{ plantilla.descripcion }} - {{ plantilla.fechaCreacion | formatMediumDatetime }} - {{ plantilla.fechaPublicacionTienda | formatMediumDatetime }} + + {{ plantilla.fechaPublicacionTienda | formatShortDatetime | titlecase }} + No establecida {{ plantilla.estado }} - {{ plantilla.precio }} - - - + {{ plantilla.precio | currency: 'USD':'symbol-narrow' }} + {{ plantilla.categoria?.nombre }}
@@ -88,3 +90,143 @@
+ + + diff --git a/src/main/webapp/app/entities/plantilla/list/plantilla.component.spec.ts b/src/main/webapp/app/entities/plantilla/list/plantilla.component.tmpSpec.ts similarity index 100% rename from src/main/webapp/app/entities/plantilla/list/plantilla.component.spec.ts rename to src/main/webapp/app/entities/plantilla/list/plantilla.component.tmpSpec.ts diff --git a/src/main/webapp/app/entities/plantilla/list/plantilla.component.ts b/src/main/webapp/app/entities/plantilla/list/plantilla.component.ts index 1c1e111..dc1f19f 100644 --- a/src/main/webapp/app/entities/plantilla/list/plantilla.component.ts +++ b/src/main/webapp/app/entities/plantilla/list/plantilla.component.ts @@ -1,11 +1,23 @@ 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'; + @Component({ selector: 'jhi-plantilla', templateUrl: './plantilla.component.html', @@ -13,8 +25,27 @@ 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.minLength(1), Validators.maxLength(50)]], + descripcion: [], + precio: [null, [Validators.required]], + categoria: [], + }); + + constructor( + protected plantillaService: PlantillaService, + protected modalService: NgbModal, + protected accountService: AccountService, + protected fb: FormBuilder, + protected categoriaService: CategoriaService + ) {} loadAll(): void { this.isLoading = true; @@ -32,6 +63,7 @@ export class PlantillaComponent implements OnInit { ngOnInit(): void { this.loadAll(); + this.loadRelationshipsOptions(); } trackId(_index: number, item: IPlantilla): number { @@ -48,4 +80,90 @@ export class PlantillaComponent implements OnInit { } }); } + + isAdmin(): boolean { + return this.accountService.hasAnyAuthority('ROLE_ADMIN'); + } + + isAuthenticated(): boolean { + return this.accountService.isAuthenticated(); + } + + resetCreateTemplateForm(): void { + this.templateCreateForm.reset(); + } + + createAnotherTemplateChange(event: any): void { + // ID: #crearPlantilla + this.createAnotherTemplate = event.target.checked; + } + + previousState(): void { + window.history.back(); + } + + save(): void { + this.isSaving = true; + const plantilla = this.createFromForm(); + if (plantilla.id !== undefined) { + this.subscribeToSaveResponse(this.plantillaService.update(plantilla)); + } else { + this.subscribeToSaveResponse(this.plantillaService.create(plantilla)); + } + } + + trackCategoriaById(index: number, item: ICategoria): number { + return item.id!; + } + + protected subscribeToSaveResponse(result: Observable>): 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) => 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, + }; + } } diff --git a/src/main/webapp/app/entities/plantilla/plantilla-delete-option-dialog/plantilla-delete-option-dialog.component.html b/src/main/webapp/app/entities/plantilla/plantilla-delete-option-dialog/plantilla-delete-option-dialog.component.html new file mode 100644 index 0000000..2845052 --- /dev/null +++ b/src/main/webapp/app/entities/plantilla/plantilla-delete-option-dialog/plantilla-delete-option-dialog.component.html @@ -0,0 +1,24 @@ +
+ + + + + +
diff --git a/src/main/webapp/app/entities/plantilla/plantilla-delete-option-dialog/plantilla-delete-option-dialog.component.ts b/src/main/webapp/app/entities/plantilla/plantilla-delete-option-dialog/plantilla-delete-option-dialog.component.ts new file mode 100644 index 0000000..94cde43 --- /dev/null +++ b/src/main/webapp/app/entities/plantilla/plantilla-delete-option-dialog/plantilla-delete-option-dialog.component.ts @@ -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'); + } +} diff --git a/src/main/webapp/app/entities/plantilla/plantilla-delete-question-dialog/plantilla-delete-question-dialog.component.html b/src/main/webapp/app/entities/plantilla/plantilla-delete-question-dialog/plantilla-delete-question-dialog.component.html new file mode 100644 index 0000000..d6eb620 --- /dev/null +++ b/src/main/webapp/app/entities/plantilla/plantilla-delete-question-dialog/plantilla-delete-question-dialog.component.html @@ -0,0 +1,24 @@ +
+ + + + + +
diff --git a/src/main/webapp/app/entities/plantilla/plantilla-delete-question-dialog/plantilla-delete-question-dialog.component.ts b/src/main/webapp/app/entities/plantilla/plantilla-delete-question-dialog/plantilla-delete-question-dialog.component.ts new file mode 100644 index 0000000..ceb0585 --- /dev/null +++ b/src/main/webapp/app/entities/plantilla/plantilla-delete-question-dialog/plantilla-delete-question-dialog.component.ts @@ -0,0 +1,17 @@ +import { Component } from '@angular/core'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; + +@Component({ + templateUrl: './plantilla-delete-question-dialog.component.html', +}) +export class PlantillaDeleteQuestionDialogComponent { + constructor(protected activeModal: NgbActiveModal) {} + + cancel(): void { + this.activeModal.dismiss(); + } + + confirmDelete(): void { + this.activeModal.close('confirm'); + } +} diff --git a/src/main/webapp/app/entities/plantilla/plantilla.module.ts b/src/main/webapp/app/entities/plantilla/plantilla.module.ts index 2284714..f4d2e54 100644 --- a/src/main/webapp/app/entities/plantilla/plantilla.module.ts +++ b/src/main/webapp/app/entities/plantilla/plantilla.module.ts @@ -5,10 +5,20 @@ import { PlantillaDetailComponent } from './detail/plantilla-detail.component'; import { PlantillaUpdateComponent } from './update/plantilla-update.component'; import { PlantillaDeleteDialogComponent } from './delete/plantilla-delete-dialog.component'; import { PlantillaRoutingModule } from './route/plantilla-routing.module'; +import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; +import { PlantillaDeleteQuestionDialogComponent } from './plantilla-delete-question-dialog/plantilla-delete-question-dialog.component'; +import { PlantillaDeleteOptionDialogComponent } from './plantilla-delete-option-dialog/plantilla-delete-option-dialog.component'; @NgModule({ - imports: [SharedModule, PlantillaRoutingModule], - declarations: [PlantillaComponent, PlantillaDetailComponent, PlantillaUpdateComponent, PlantillaDeleteDialogComponent], + imports: [SharedModule, PlantillaRoutingModule, FontAwesomeModule], + declarations: [ + PlantillaComponent, + PlantillaDetailComponent, + PlantillaUpdateComponent, + PlantillaDeleteDialogComponent, + PlantillaDeleteQuestionDialogComponent, + PlantillaDeleteOptionDialogComponent, + ], entryComponents: [PlantillaDeleteDialogComponent], }) export class PlantillaModule {} diff --git a/src/main/webapp/app/entities/plantilla/service/plantilla.service.ts b/src/main/webapp/app/entities/plantilla/service/plantilla.service.ts index 6402f49..dbaa0ac 100644 --- a/src/main/webapp/app/entities/plantilla/service/plantilla.service.ts +++ b/src/main/webapp/app/entities/plantilla/service/plantilla.service.ts @@ -45,6 +45,22 @@ export class PlantillaService { .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } + findPlantilla(id: number): Observable { + return this.http.get(`${this.resourceUrl}/${id}`); + } + + findQuestions(id: number): Observable { + return this.http + .get(`${this.resourceUrl}/preguntas/${id}`, { observe: 'response' }) + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); + } + + findQuestionsOptions(id: number): Observable { + return this.http + .get(`${this.resourceUrl}/preguntas-opciones/${id}`, { observe: 'response' }) + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); + } + query(req?: any): Observable { const options = createRequestOption(req); return this.http diff --git a/src/main/webapp/app/entities/plantilla/update/plantilla-update.component.html b/src/main/webapp/app/entities/plantilla/update/plantilla-update.component.html index 59cd6ea..117d224 100644 --- a/src/main/webapp/app/entities/plantilla/update/plantilla-update.component.html +++ b/src/main/webapp/app/entities/plantilla/update/plantilla-update.component.html @@ -1,165 +1,355 @@ -
-
-
-

- Create or edit a Plantilla -

+
+

+
+

+ {{ plantilla!.nombre }} +

+
-
- +

Creada el día {{ plantilla!.fechaCreacion | formatShortDatetime | lowercase }}

-
- - -
+
+ + -
- - -
- - This field is required to be at least 1 characters. - - - This field cannot be longer than 50 characters. - -
-
+ +
+

-
- - -
+ -
- -
- -
+ + + + +
+
+ +

Plantilla en tienda

+

No puede modificar la plantilla debido a que esta ya está en la tienda.

+
+ +

Plantilla vacía

+

Inicie creando preguntas y opciones para la plantilla.

+
+ +
- - This field is required. - - - This field should be a date and time. - +
+ + {{ i + 1 }}.  + {{ pPregunta.nombre }} + + +
+
+ Pregunta de respuesta {{ 'dataSurveyApp.PreguntaCerradaTipo.SINGLE' | translate | lowercase }} + {{ pPregunta.opcional ? '(opcional)' : '' }} + Pregunta de respuesta {{ 'dataSurveyApp.PreguntaCerradaTipo.MULTIPLE' | translate | lowercase }} + {{ pPregunta.opcional ? '(opcional)' : '' }} + Pregunta de respuesta abierta {{ pPregunta.opcional ? '(opcional)' : '' }} +
+ + + + +
+ + + +
+
+
+
+
+ + Añadir opción +
+
+
+ +
- -
- -
- -
-
- -
- - -
- - This field is required. - -
-
- -
- - -
- - This field is required. - - - This field should be a number. - -
-
- -
- - -
-
- -
- - - -
- + +
+
+
+ + + + + + + + diff --git a/src/main/webapp/app/entities/plantilla/update/plantilla-update.component.spec.ts b/src/main/webapp/app/entities/plantilla/update/plantilla-update.component.tmpSpec.ts similarity index 100% rename from src/main/webapp/app/entities/plantilla/update/plantilla-update.component.spec.ts rename to src/main/webapp/app/entities/plantilla/update/plantilla-update.component.tmpSpec.ts diff --git a/src/main/webapp/app/entities/plantilla/update/plantilla-update.component.ts b/src/main/webapp/app/entities/plantilla/update/plantilla-update.component.ts index 21f1465..6a380e8 100644 --- a/src/main/webapp/app/entities/plantilla/update/plantilla-update.component.ts +++ b/src/main/webapp/app/entities/plantilla/update/plantilla-update.component.ts @@ -1,4 +1,9 @@ -import { Component, OnInit } from '@angular/core'; +import { PPreguntaAbierta, IPPreguntaAbierta } from './../../p-pregunta-abierta/p-pregunta-abierta.model'; +import { PPreguntaCerrada } from './../../p-pregunta-cerrada/p-pregunta-cerrada.model'; +import { PPreguntaCerradaOpcion, IPPreguntaCerradaOpcion } from './../../p-pregunta-cerrada-opcion/p-pregunta-cerrada-opcion.model'; +import { PPreguntaAbiertaService } from './../../p-pregunta-abierta/service/p-pregunta-abierta.service'; +import { PPreguntaCerradaOpcionService } from './../../p-pregunta-cerrada-opcion/service/p-pregunta-cerrada-opcion.service'; +import { AfterViewChecked, Component, OnInit } from '@angular/core'; import { HttpResponse } from '@angular/common/http'; import { FormBuilder, Validators } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; @@ -12,67 +17,258 @@ 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 } from 'app/entities/usuario-extra/usuario-extra.model'; +import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service'; + +import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; +import { IPPreguntaCerrada } from 'app/entities/p-pregunta-cerrada/p-pregunta-cerrada.model'; +import { PPreguntaCerradaService } from 'app/entities/p-pregunta-cerrada/service/p-pregunta-cerrada.service'; +import { PPreguntaCerradaDeleteDialogComponent } from 'app/entities/p-pregunta-cerrada/delete/p-pregunta-cerrada-delete-dialog.component'; + +import { faTimes, faPlus, faQuestion, faPollH, faEye } from '@fortawesome/free-solid-svg-icons'; +import { PreguntaCerradaTipo } from 'app/entities/enumerations/pregunta-cerrada-tipo.model'; +import { PlantillaDeleteQuestionDialogComponent } from '../plantilla-delete-question-dialog/plantilla-delete-question-dialog.component'; +import { PlantillaDeleteOptionDialogComponent } from '../plantilla-delete-option-dialog/plantilla-delete-option-dialog.component'; + +import { ParametroAplicacionService } from './../../parametro-aplicacion/service/parametro-aplicacion.service'; +import { IParametroAplicacion } from './../../parametro-aplicacion/parametro-aplicacion.model'; +import { Router } from '@angular/router'; @Component({ selector: 'jhi-plantilla-update', templateUrl: './plantilla-update.component.html', }) -export class PlantillaUpdateComponent implements OnInit { +export class PlantillaUpdateComponent implements OnInit, AfterViewChecked { + faTimes = faTimes; + faPlus = faPlus; + faPollH = faPollH; + faQuestion = faQuestion; + faEye = faEye; + isSaving = false; + isSavingQuestion = false; categoriasSharedCollection: ICategoria[] = []; + usuarioExtrasSharedCollection: IUsuarioExtra[] = []; editForm = this.fb.group({ id: [], - nombre: [null, [Validators.minLength(1), Validators.maxLength(50)]], - descripcion: [], - fechaCreacion: [null, [Validators.required]], - fechaPublicacionTienda: [], - estado: [null, [Validators.required]], - precio: [null, [Validators.required]], - categoria: [], + nombre: [null, [Validators.required, Validators.minLength(1), Validators.maxLength(500)]], }); + editFormQuestion = this.fb.group({ + id: [], + nombre: [null, [Validators.required, Validators.minLength(1), Validators.maxLength(500)]], + tipo: [PreguntaCerradaTipo.SINGLE], + opcional: [false], + tipopregunta: ['CLOSED'], + }); + + pPreguntas?: any[]; + pPreguntasOpciones?: any[]; + plantilla: Plantilla | null = null; + parametrosAplicacion?: IParametroAplicacion | null = null; + + isLoading = false; + + createAnother: Boolean = false; + createAnotherQuestion: Boolean = false; + selectedQuestionToCreateOption: IPPreguntaCerrada | null = null; + constructor( protected plantillaService: PlantillaService, protected categoriaService: CategoriaService, + protected usuarioExtraService: UsuarioExtraService, protected activatedRoute: ActivatedRoute, - protected fb: FormBuilder + protected fb: FormBuilder, + protected modalService: NgbModal, + protected pPreguntaCerradaService: PPreguntaCerradaService, + protected pPreguntaCerradaOpcionService: PPreguntaCerradaOpcionService, + protected parametroAplicacionService: ParametroAplicacionService, + protected pPreguntaAbiertaService: PPreguntaAbiertaService, + protected router: Router ) {} + loadAll(): void { + this.isLoading = true; + + this.plantillaService.findQuestions(this.plantilla?.id!).subscribe( + (res: any) => { + this.isLoading = false; + this.pPreguntas = res.body ?? []; + }, + () => { + this.isLoading = false; + } + ); + + this.plantillaService.findQuestionsOptions(this.plantilla?.id!).subscribe( + (res: any) => { + this.isLoading = false; + this.pPreguntasOpciones = res.body ?? []; + }, + () => { + this.isLoading = false; + } + ); + } + + async loadAplicationParameters(): Promise { + const params = await this.parametroAplicacionService.find(1).toPromise(); + this.parametrosAplicacion = params.body; + } + ngOnInit(): void { this.activatedRoute.data.subscribe(({ plantilla }) => { if (plantilla.id === undefined) { const today = dayjs().startOf('day'); plantilla.fechaCreacion = today; - plantilla.fechaPublicacionTienda = today; + plantilla.fechaPublicacion = today; + plantilla.fechaFinalizar = today; + plantilla.fechaFinalizada = today; + } else { + this.plantilla = plantilla; + this.loadAll(); + this.loadAplicationParameters(); } - this.updateForm(plantilla); + // this.updateForm(plantilla); - this.loadRelationshipsOptions(); + // this.loadRelationshipsOptions(); }); } + ngAfterViewChecked(): void { + // this.initListeners(); + } + + trackId(index: number, item: IPPreguntaCerrada): number { + return item.id!; + } + + delete(pPreguntaCerrada: IPPreguntaCerrada): void { + const modalRef = this.modalService.open(PPreguntaCerradaDeleteDialogComponent, { size: 'lg', backdrop: 'static' }); + modalRef.componentInstance.pPreguntaCerrada = pPreguntaCerrada; + // unsubscribe not needed because closed completes on modal close + modalRef.closed.subscribe(reason => { + if (reason === 'deleted') { + this.loadAll(); + } + }); + } + + // initListeners(): void { + // const checkboxes = document.getElementsByClassName('ds-survey--checkbox'); + // for (let i = 0; i < checkboxes.length; i++) { + // checkboxes[i].addEventListener('click', e => { + // if ((e.target as HTMLInputElement).checked) { + // (e.target as HTMLElement).offsetParent!.classList.add('ds-survey--closed-option--active'); + // } else { + // (e.target as HTMLElement).offsetParent!.classList.remove('ds-survey--closed-option--active'); + // } + // }); + // } + // } + previousState(): void { 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)); + publishSurvey(): void {} + + finishSurvey(): void {} + + addOption(event: any): void {} + + openPreview() { + const surveyId = this.plantilla?.id; + this.router.navigate(['/plantilla', surveyId, 'preview']); + } + + resetForm(event: any): void { + this.editForm.reset(); + if (event !== null) { + const id = event.target.dataset.id; + this.pPreguntaCerradaService.find(id).subscribe(e => { + this.selectedQuestionToCreateOption = e.body; + }); } } - trackCategoriaById(index: number, item: ICategoria): number { + deleteQuestion(event: any) { + const modalRef = this.modalService.open(PlantillaDeleteQuestionDialogComponent, { size: 'lg', backdrop: 'static' }); + modalRef.closed.subscribe(reason => { + if (reason === 'confirm') { + const id = event.target.dataset.id; + if (event.target.dataset.type) { + // Delete closed question + const questionElement = (event.target as HTMLElement).parentElement?.parentElement; + const optionIdsToDelete: number[] = []; + + // Get options IDs + questionElement?.childNodes.forEach((e, i) => { + if (e.nodeName !== 'DIV') return; + if (i === 0) return; + if ((e as HTMLElement).dataset.id === undefined) return; + if (!(e as HTMLElement).classList.contains('can-delete')) return; + let optionId = (e as HTMLElement).dataset.id; + optionIdsToDelete.push(+optionId!); + }); + + if (optionIdsToDelete.length === 0) { + this.pPreguntaCerradaService.delete(id).subscribe(e => { + this.loadAll(); + }); + } else { + // Delete question options + this.pPreguntaCerradaOpcionService.deleteMany(optionIdsToDelete).subscribe(e => { + // Delete question + this.pPreguntaCerradaService.delete(id).subscribe(e => { + this.loadAll(); + }); + }); + } + } else { + // Delete open question + this.pPreguntaAbiertaService.delete(id).subscribe(e => { + this.loadAll(); + }); + } + } + }); + } + + deleteOption(event: any): void { + const modalRef = this.modalService.open(PlantillaDeleteOptionDialogComponent, { size: 'lg', backdrop: 'static' }); + modalRef.closed.subscribe(reason => { + if (reason === 'confirm') { + const id = event.target.dataset.optionid; + this.pPreguntaCerradaOpcionService.delete(id).subscribe(e => { + this.pPreguntas = []; + this.pPreguntasOpciones = []; + this.loadAll(); + }); + } + }); + } + + save(): void { + this.isSaving = true; + const pPreguntaCerradaOpcion = this.createFromForm(); + if (pPreguntaCerradaOpcion.id !== undefined) { + this.subscribeToSaveResponse(this.pPreguntaCerradaOpcionService.update(pPreguntaCerradaOpcion)); + } else { + this.subscribeToSaveResponse( + this.pPreguntaCerradaOpcionService.create(pPreguntaCerradaOpcion, this.selectedQuestionToCreateOption?.id!) + ); + } + } + + trackPPreguntaCerradaById(index: number, item: IPPreguntaCerrada): number { return item.id!; } - protected subscribeToSaveResponse(result: Observable>): void { + protected subscribeToSaveResponse(result: Observable>): void { result.pipe(finalize(() => this.onSaveFinalize())).subscribe( () => this.onSaveSuccess(), () => this.onSaveError() @@ -80,7 +276,14 @@ export class PlantillaUpdateComponent implements OnInit { } protected onSaveSuccess(): void { - this.previousState(); + // this.previousState(); + this.resetForm(null); + this.pPreguntas = []; + this.pPreguntasOpciones = []; + this.loadAll(); + if (!this.createAnother) { + $('#cancelBtn').click(); + } } protected onSaveError(): void { @@ -91,51 +294,159 @@ export class PlantillaUpdateComponent implements OnInit { this.isSaving = false; } - protected updateForm(plantilla: IPlantilla): void { - this.editForm.patchValue({ - id: plantilla.id, - nombre: plantilla.nombre, - descripcion: plantilla.descripcion, - fechaCreacion: plantilla.fechaCreacion ? plantilla.fechaCreacion.format(DATE_TIME_FORMAT) : null, - fechaPublicacionTienda: plantilla.fechaPublicacionTienda ? plantilla.fechaPublicacionTienda.format(DATE_TIME_FORMAT) : null, - estado: plantilla.estado, - precio: plantilla.precio, - categoria: plantilla.categoria, - }); + protected createFromForm(): IPPreguntaCerradaOpcion { + return { + ...new PPreguntaCerradaOpcion(), + id: undefined, + nombre: this.editForm.get(['nombre'])!.value, + orden: 10, + pPreguntaCerrada: this.selectedQuestionToCreateOption, + }; + } - this.categoriasSharedCollection = this.categoriaService.addCategoriaToCollectionIfMissing( - this.categoriasSharedCollection, - plantilla.categoria + createAnotherChange(event: any) { + this.createAnother = event.target.checked; + } + + createQuestion(): void { + const surveyId = this.plantilla?.id; + } + + protected createFromFormClosedQuestion(): IPPreguntaCerrada { + return { + // ...new PPreguntaCerrada(), + id: undefined, + nombre: this.editFormQuestion.get(['nombre'])!.value, + tipo: this.editFormQuestion.get(['tipo'])!.value, + opcional: this.editFormQuestion.get(['opcional'])!.value, + orden: 10, + plantilla: this.plantilla, + }; + } + + protected createFromFormOpenQuestion(): IPPreguntaAbierta { + return { + // ...new PPreguntaAbierta(), + id: undefined, + nombre: this.editFormQuestion.get(['nombre'])!.value, + opcional: this.editFormQuestion.get(['opcional'])!.value, + orden: 10, + plantilla: this.plantilla, + }; + } + + createAnotherQuestionChange(event: any) { + this.createAnotherQuestion = event.target.checked; + } + + saveQuestion(): void { + this.isSavingQuestion = true; + const tipoPregunta = this.editFormQuestion.get(['tipopregunta'])!.value; + + if (tipoPregunta === 'CLOSED') { + const pPreguntaCerrada = this.createFromFormClosedQuestion(); + if (pPreguntaCerrada.id !== undefined) { + this.subscribeToSaveResponseQuestionClosed(this.pPreguntaCerradaService.update(pPreguntaCerrada)); + } else { + this.subscribeToSaveResponseQuestionClosed(this.pPreguntaCerradaService.create(pPreguntaCerrada)); + } + } else if (tipoPregunta === 'OPEN') { + const pPreguntaAbierta = this.createFromFormOpenQuestion(); + if (pPreguntaAbierta.id !== undefined) { + this.subscribeToSaveResponseQuestionOpen(this.pPreguntaAbiertaService.update(pPreguntaAbierta)); + } else { + this.subscribeToSaveResponseQuestionOpen(this.pPreguntaAbiertaService.create(pPreguntaAbierta)); + } + } + } + + protected subscribeToSaveResponseQuestionClosed(result: Observable>): void { + result.pipe(finalize(() => this.onSaveFinalizeQuestion())).subscribe( + () => this.onSaveSuccessQuestion(), + () => this.onSaveErrorQuestion() ); } - protected loadRelationshipsOptions(): void { - this.categoriaService - .query() - .pipe(map((res: HttpResponse) => res.body ?? [])) - .pipe( - map((categorias: ICategoria[]) => - this.categoriaService.addCategoriaToCollectionIfMissing(categorias, this.editForm.get('categoria')!.value) - ) - ) - .subscribe((categorias: ICategoria[]) => (this.categoriasSharedCollection = categorias)); + protected subscribeToSaveResponseQuestionOpen(result: Observable>): void { + result.pipe(finalize(() => this.onSaveFinalizeQuestion())).subscribe( + () => this.onSaveSuccessQuestion(), + () => this.onSaveErrorQuestion() + ); } - protected createFromForm(): IPlantilla { - return { - ...new Plantilla(), - id: this.editForm.get(['id'])!.value, - nombre: this.editForm.get(['nombre'])!.value, - descripcion: this.editForm.get(['descripcion'])!.value, - fechaCreacion: this.editForm.get(['fechaCreacion'])!.value - ? dayjs(this.editForm.get(['fechaCreacion'])!.value, DATE_TIME_FORMAT) - : undefined, - fechaPublicacionTienda: this.editForm.get(['fechaPublicacionTienda'])!.value - ? dayjs(this.editForm.get(['fechaPublicacionTienda'])!.value, DATE_TIME_FORMAT) - : undefined, - estado: this.editForm.get(['estado'])!.value, - precio: this.editForm.get(['precio'])!.value, - categoria: this.editForm.get(['categoria'])!.value, - }; + protected onSaveSuccessQuestion(): void { + this.editFormQuestion.reset({ tipo: PreguntaCerradaTipo.SINGLE, tipopregunta: 'CLOSED', opcional: false }); + this.editForm.reset(); + this.pPreguntas = []; + this.pPreguntasOpciones = []; + this.loadAll(); + if (!this.createAnotherQuestion) { + $('#cancelBtnQuestion').click(); + } + } + + protected onSaveErrorQuestion(): void { + // Api for inheritance. + } + + protected onSaveFinalizeQuestion(): void { + this.isSavingQuestion = false; + } + + updateTemplateName(event: any) { + const updatedSurveyName = event.target.innerText; + if (updatedSurveyName !== this.plantilla?.nombre) { + const survey = { ...this.plantilla }; + survey.nombre = updatedSurveyName; + + this.plantillaService.update(survey).subscribe(res => {}); + } + } + + updateQuestionName(event: any): void { + const questionType = event.target.dataset.tipo; + const questionId = event.target.dataset.id; + const questionName = event.target.innerText; + if (questionType) { + // Closed question + this.pPreguntaCerradaService.find(questionId).subscribe(res => { + const pPreguntaCerrada: PPreguntaCerrada | null = res.body ?? null; + const updatedPPreguntaCerrada = { ...pPreguntaCerrada }; + if (questionName !== pPreguntaCerrada?.nombre && pPreguntaCerrada !== null) { + updatedPPreguntaCerrada.nombre = questionName; + this.pPreguntaCerradaService.update(updatedPPreguntaCerrada).subscribe(updatedQuestion => { + console.log(updatedQuestion); + }); + } + }); + } else { + // Open question + // Closed question + this.pPreguntaAbiertaService.find(questionId).subscribe(res => { + const pPreguntaAbierta: PPreguntaAbierta | null = res.body ?? null; + const updatedPPreguntaAbierta = { ...pPreguntaAbierta }; + if (questionName !== pPreguntaAbierta?.nombre && pPreguntaAbierta !== null) { + updatedPPreguntaAbierta.nombre = questionName; + this.pPreguntaAbiertaService.update(updatedPPreguntaAbierta).subscribe(updatedQuestion => { + console.log(updatedQuestion); + }); + } + }); + } + // const questionId = event.target.dataset.id; + // const survey = { ...this.plantilla }; + // survey.nombre = updatedQuestionName; + // // Prevent user update by setting to null + // survey.usuarioExtra!.user = null; + + // this.plantillaService.updateSurvey(survey).subscribe(res => {}); + } + + trackCategoriaById(index: number, item: ICategoria): number { + return item.id!; + } + + trackUsuarioExtraById(index: number, item: IUsuarioExtra): number { + return item.id!; } } diff --git a/src/main/webapp/app/login/login.component.ts b/src/main/webapp/app/login/login.component.ts index f85105d..1f46b74 100644 --- a/src/main/webapp/app/login/login.component.ts +++ b/src/main/webapp/app/login/login.component.ts @@ -94,7 +94,6 @@ export class LoginComponent implements OnInit, AfterViewInit { } }, response => { - debugger; if (response.status == 401 && response.error.detail == 'Bad credentials') { this.activateGoogle(); } else { @@ -109,7 +108,6 @@ export class LoginComponent implements OnInit, AfterViewInit { } processError(response: HttpErrorResponse): void { - debugger; if (response.status === 400 && response.error.type === LOGIN_ALREADY_USED_TYPE) { this.errorUserExists = true; } else if (response.status === 400 && response.error.type === EMAIL_ALREADY_USED_TYPE) { @@ -153,7 +151,6 @@ export class LoginComponent implements OnInit, AfterViewInit { login(): void { this.error = false; this.userSuspended = false; - debugger; this.loginService .login({ username: this.loginForm.get('username')!.value, @@ -162,9 +159,6 @@ export class LoginComponent implements OnInit, AfterViewInit { }) .subscribe( value => { - debugger; - console.log(value); - /*if (value?.activated == false){ this.userSuspended = true; @@ -178,7 +172,6 @@ export class LoginComponent implements OnInit, AfterViewInit { // } }, response => { - debugger; if (response.status == 401 && response.error.detail == 'Bad credentials') { this.error = true; } else { diff --git a/src/main/webapp/app/login/login.service.ts b/src/main/webapp/app/login/login.service.ts index 8e24e3d..bc97be6 100644 --- a/src/main/webapp/app/login/login.service.ts +++ b/src/main/webapp/app/login/login.service.ts @@ -12,7 +12,6 @@ export class LoginService { constructor(private accountService: AccountService, private authServerProvider: AuthServerProvider) {} login(credentials: Login): Observable { - debugger; return this.authServerProvider.login(credentials).pipe(mergeMap(() => this.accountService.identity(true))); }