Add registrar usuario administrador por medio de la plataforma

This commit is contained in:
Pablo Bonilla 2021-07-06 22:59:31 -06:00
parent 6395f3d8c8
commit 3f723189b4
No known key found for this signature in database
GPG Key ID: 46877262B8DE47E2
6 changed files with 452 additions and 435 deletions

View File

@ -12,7 +12,7 @@ import { RegisterService } from './register.service';
templateUrl: './register.component.html', templateUrl: './register.component.html',
styleUrls: ['./register.component.scss'], styleUrls: ['./register.component.scss'],
}) })
export class RegisterComponent implements OnInit, AfterViewInit { export class RegisterComponent implements AfterViewInit {
// @ViewChild('name', { static: false }) // @ViewChild('name', { static: false })
// name?: ElementRef; // name?: ElementRef;
@ -53,7 +53,6 @@ export class RegisterComponent implements OnInit, AfterViewInit {
errorEmailExists = false; errorEmailExists = false;
errorUserExists = false; errorUserExists = false;
success = false; success = false;
isAdmin: number = 0;
// Login will be used to store the email as well. // Login will be used to store the email as well.
// login: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(254), Validators.email]] // login: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(254), Validators.email]]
@ -66,10 +65,6 @@ export class RegisterComponent implements OnInit, AfterViewInit {
constructor(private translateService: TranslateService, private registerService: RegisterService, private fb: FormBuilder) {} constructor(private translateService: TranslateService, private registerService: RegisterService, private fb: FormBuilder) {}
ngOnInit(): void {
this.isAdmin = window.location.href.includes('/account/register') ? 0 : 1;
}
ngAfterViewInit(): void { ngAfterViewInit(): void {
// if (this.name) { // if (this.name) {
// this.name.nativeElement.focus(); // this.name.nativeElement.focus();
@ -99,7 +94,7 @@ export class RegisterComponent implements OnInit, AfterViewInit {
langKey: this.translateService.currentLang, langKey: this.translateService.currentLang,
name, name,
profileIcon: this.profileIcon, profileIcon: this.profileIcon,
isAdmin: this.isAdmin, isAdmin: 0,
}) })
.subscribe( .subscribe(
() => (this.success = true), () => (this.success = true),

View File

@ -1,118 +1,246 @@
<div class="container">
<div class="row justify-content-center"> <div class="row justify-content-center">
<div class="col-8"> <div class="col-xxl-4 col-lg-6">
<form name="editForm" role="form" novalidate (ngSubmit)="save()" [formGroup]="editForm"> <div class="card mt-1">
<h2 <!-- <div class="pl-4 pt-4 pr-4 pb-1 text-center">
id="jhi-usuario-extra-heading" <img src="../../content/img_datasurvey/datasurvey-logo-text-black.svg" alt="" />
data-cy="UsuarioExtraCreateUpdateHeading" </div> -->
jhiTranslate="dataSurveyApp.usuarioExtra.home.createOrEditLabel"
>
Create or edit a Usuario Extra
</h2>
<div> <div class="card-body p-4">
<jhi-alert-error></jhi-alert-error> <div class="text-center w-75 m-auto">
<h4 class="text-dark-50 text-center pb-0 fw-bold p-0 m-0" style="color: #727070; font-weight: 700; font-size: 1.3rem">
<div class="form-group" [hidden]="editForm.get('id')!.value == null"> REGISTRAR ADMIN
<label class="form-control-label" jhiTranslate="global.field.id" for="field_id">ID</label> </h4>
<input type="number" class="form-control" name="id" id="field_id" data-cy="id" formControlName="id" [readonly]="true" /> <p class="mb-4" style="color: rgba(146, 146, 146, 0.664)">Ingrese los datos para registrar a un admin.</p>
</div> </div>
<div class="alert alert-success" *ngIf="success" jhiTranslate="register.messages.adminsuccess">
<strong>Registration saved!</strong> Please check your email for confirmation.
</div>
<div class="alert alert-danger" *ngIf="error" jhiTranslate="register.messages.error.fail">
<strong>Registration failed!</strong> Please try again later.
</div>
<div class="alert alert-danger" *ngIf="errorEmailExists" jhiTranslate="register.messages.error.emailexists">
<strong>Email is already in use!</strong> Please choose another one.
</div>
<div class="alert alert-danger" *ngIf="doNotMatch" jhiTranslate="global.messages.error.dontmatch">
The password and its confirmation do not match!
</div>
<form name="form" role="form" class="form" (ngSubmit)="register()" [formGroup]="registerForm" *ngIf="!success" autocomplete="off">
<div class="mb-3">
<div class="form-group"> <div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.nombre" for="field_nombre">Nombre</label> <label for="name" class="form-label">Nombre</label>
<input type="text" class="form-control" name="nombre" id="field_nombre" data-cy="nombre" formControlName="nombre" />
<div *ngIf="editForm.get('nombre')!.invalid && (editForm.get('nombre')!.dirty || editForm.get('nombre')!.touched)">
<small class="form-text text-danger" *ngIf="editForm.get('nombre')?.errors?.required" jhiTranslate="entity.validation.required">
This field is required.
</small>
</div>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.iconoPerfil" for="field_iconoPerfil"
>Icono Perfil</label
>
<input <input
type="text" type="text"
class="form-control" class="form-control"
name="iconoPerfil" id="name"
id="field_iconoPerfil" name="name"
data-cy="iconoPerfil" placeholder="{{ 'global.form.name.placeholder' | translate }}"
formControlName="iconoPerfil" formControlName="name"
data-cy="name"
/> />
</div>
<div class="form-group"> <div *ngIf="registerForm.get('name')!.invalid && (registerForm.get('name')!.dirty || registerForm.get('name')!.touched)">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.fechaNacimiento" for="field_fechaNacimiento" <small
>Fecha Nacimiento</label class="form-text text-danger"
*ngIf="registerForm.get('name')?.errors?.required"
jhiTranslate="global.messages.validate.name.required"
> >
<div class="d-flex"> Your name is required.
<input </small>
id="field_fechaNacimiento"
data-cy="fechaNacimiento"
type="datetime-local"
class="form-control"
name="fechaNacimiento"
formControlName="fechaNacimiento"
placeholder="YYYY-MM-DD HH:mm"
/>
</div>
</div>
<div class="form-group"> <small
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.estado" for="field_estado">Estado</label> class="form-text text-danger"
<select class="form-control" name="estado" formControlName="estado" id="field_estado" data-cy="estado"> *ngIf="registerForm.get('name')?.errors?.invalid"
<option [ngValue]="null">{{ 'dataSurveyApp.EstadoUsuario.null' | translate }}</option> jhiTranslate="global.messages.validate.name.invalid"
<option value="ACTIVE">{{ 'dataSurveyApp.EstadoUsuario.ACTIVE' | translate }}</option> >
<option value="SUSPENDED">{{ 'dataSurveyApp.EstadoUsuario.SUSPENDED' | translate }}</option> Your name is invalid.
</select> </small>
<div *ngIf="editForm.get('estado')!.invalid && (editForm.get('estado')!.dirty || editForm.get('estado')!.touched)">
<small class="form-text text-danger" *ngIf="editForm.get('estado')?.errors?.required" jhiTranslate="entity.validation.required"> <small
This field is required. class="form-text text-danger"
*ngIf="registerForm.get('name')?.errors?.minlength"
jhiTranslate="global.messages.validate.name.minlength"
>
Your name is required to be at least 2 characters.
</small>
<small
class="form-text text-danger"
*ngIf="registerForm.get('name')?.errors?.maxlength"
jhiTranslate="global.messages.validate.name.maxlength"
>
Your name cannot be longer than 50 characters.
</small> </small>
</div> </div>
</div> </div>
</div>
<div class="mb-3">
<div class="form-group"> <div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.user" for="field_user">User</label> <label for="emailaddress" class="form-label">Correo electrónico</label>
<select class="form-control" id="field_user" data-cy="user" name="user" formControlName="user"> <input
<option [ngValue]="null"></option> type="email"
<option class="form-control"
[ngValue]="userOption.id === editForm.get('user')!.value?.id ? editForm.get('user')!.value : userOption" id="email"
*ngFor="let userOption of usersSharedCollection; trackBy: trackUserById" name="email"
placeholder="{{ 'global.form.email.placeholder' | translate }}"
formControlName="email"
data-cy="email"
/>
<div *ngIf="registerForm.get('email')!.invalid && (registerForm.get('email')!.dirty || registerForm.get('email')!.touched)">
<small
class="form-text text-danger"
*ngIf="registerForm.get('email')?.errors?.required"
jhiTranslate="global.messages.validate.email.required"
> >
{{ userOption.id }} Your email is required.
</option> </small>
</select>
<small
class="form-text text-danger"
*ngIf="registerForm.get('email')?.errors?.invalid"
jhiTranslate="global.messages.validate.email.invalid"
>
Your email is invalid.
</small>
<small
class="form-text text-danger"
*ngIf="registerForm.get('email')?.errors?.minlength"
jhiTranslate="global.messages.validate.email.minlength"
>
Your email is required to be at least 5 characters.
</small>
<small
class="form-text text-danger"
*ngIf="registerForm.get('email')?.errors?.maxlength"
jhiTranslate="global.messages.validate.email.maxlength"
>
Your email cannot be longer than 100 characters.
</small>
</div>
</div>
</div> </div>
<div class="mb-3">
<div class="form-group"> <div class="form-group">
<label jhiTranslate="dataSurveyApp.usuarioExtra.plantilla" for="field_plantillas">Plantilla</label> <label for="password" jhiTranslate="global.form.newpassword.label">Password</label>
<select class="form-control" id="field_plantillas" data-cy="plantilla" multiple name="plantillas" formControlName="plantillas"> <input
<option type="password"
[ngValue]="getSelectedPlantilla(plantillaOption, editForm.get('plantillas')!.value)" class="form-control"
*ngFor="let plantillaOption of plantillasSharedCollection; trackBy: trackPlantillaById" id="password"
name="password"
placeholder="{{ 'global.form.newpassword.placeholder' | translate }}"
formControlName="password"
data-cy="firstPassword"
/>
<div
*ngIf="
registerForm.get('password')!.invalid && (registerForm.get('password')!.dirty || registerForm.get('password')!.touched)
"
> >
{{ plantillaOption.id }} <small
</option> class="form-text text-danger"
</select> *ngIf="registerForm.get('password')?.errors?.required"
jhiTranslate="global.messages.validate.newpassword.required"
>
Your password is required.
</small>
<small
class="form-text text-danger"
*ngIf="registerForm.get('password')?.errors?.minlength"
jhiTranslate="global.messages.validate.newpassword.minlength"
>
Your password is required to be at least 4 characters.
</small>
<small
class="form-text text-danger"
*ngIf="registerForm.get('password')?.errors?.maxlength"
jhiTranslate="global.messages.validate.newpassword.maxlength"
>
Your password cannot be longer than 50 characters.
</small>
</div>
</div> </div>
</div> </div>
<div> <div class="mb-3">
<button type="button" id="cancel-save" data-cy="entityCreateCancelButton" class="btn btn-secondary" (click)="previousState()"> <div class="form-group">
<fa-icon icon="ban"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span> <label for="password" jhiTranslate="global.form.newpassword.label">Password</label>
</button> <input
type="password"
class="form-control"
id="confirmPassword"
name="confirmPassword"
placeholder="{{ 'global.form.confirmpassword.placeholder' | translate }}"
formControlName="confirmPassword"
data-cy="secondPassword"
/>
<div
*ngIf="
registerForm.get('confirmPassword')!.invalid &&
(registerForm.get('confirmPassword')!.dirty || registerForm.get('confirmPassword')!.touched)
"
>
<small
class="form-text text-danger"
*ngIf="registerForm.get('confirmPassword')?.errors?.required"
jhiTranslate="global.messages.validate.confirmpassword.required"
>
Your confirmation password is required.
</small>
<small
class="form-text text-danger"
*ngIf="registerForm.get('confirmPassword')?.errors?.minlength"
jhiTranslate="global.messages.validate.confirmpassword.minlength"
>
Your confirmation password is required to be at least 4 characters.
</small>
<small
class="form-text text-danger"
*ngIf="registerForm.get('confirmPassword')?.errors?.maxlength"
jhiTranslate="global.messages.validate.confirmpassword.maxlength"
>
Your confirmation password cannot be longer than 50 characters.
</small>
</div>
</div>
</div>
<div class="mb-3">
<div class="form-group">
<label for="password">Ícono de perfil</label>
<jhi-swiper [data]="profileIcons" (onSelectEvent)="selectIcon($event)"></jhi-swiper>
</div>
</div>
<div class="mb-3 mb-0 text-center">
<button <button
type="submit" type="submit"
id="save-entity" [disabled]="registerForm.invalid"
data-cy="entityCreateSaveButton" class="btn btn-primary w-100"
[disabled]="editForm.invalid || isSaving" jhiTranslate="register.form.button"
class="btn btn-primary" data-cy="submit"
> >
<fa-icon icon="save"></fa-icon>&nbsp;<span jhiTranslate="entity.action.save">Save</span> Register
</button> </button>
</div> </div>
</form> </form>
</div> </div>
</div> </div>
</div>
</div>
</div>

View File

@ -1,212 +1,144 @@
jest.mock('@angular/router'); jest.mock('@ngx-translate/core');
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed, waitForAsync, inject, tick, fakeAsync } from '@angular/core/testing';
import { HttpResponse } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { HttpClientTestingModule } from '@angular/common/http/testing';
import { FormBuilder } from '@angular/forms'; import { FormBuilder } from '@angular/forms';
import { ActivatedRoute } from '@angular/router'; import { of, throwError } from 'rxjs';
import { of, Subject } from 'rxjs'; import { TranslateService } from '@ngx-translate/core';
import { UsuarioExtraService } from '../service/usuario-extra.service'; import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from 'app/config/error.constants';
import { IUsuarioExtra, UsuarioExtra } from '../usuario-extra.model';
import { IUser } from 'app/entities/user/user.model';
import { UserService } from 'app/entities/user/user.service';
import { IPlantilla } from 'app/entities/plantilla/plantilla.model';
import { PlantillaService } from 'app/entities/plantilla/service/plantilla.service';
import { RegisterService } from 'app/account/register/register.service';
import { UsuarioExtraUpdateComponent } from './usuario-extra-update.component'; import { UsuarioExtraUpdateComponent } from './usuario-extra-update.component';
describe('Component Tests', () => { describe('Component Tests', () => {
describe('UsuarioExtra Management Update Component', () => { describe('RegisterComponent', () => {
let comp: UsuarioExtraUpdateComponent;
let fixture: ComponentFixture<UsuarioExtraUpdateComponent>; let fixture: ComponentFixture<UsuarioExtraUpdateComponent>;
let activatedRoute: ActivatedRoute; let comp: UsuarioExtraUpdateComponent;
let usuarioExtraService: UsuarioExtraService;
let userService: UserService;
let plantillaService: PlantillaService;
beforeEach(() => { beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [HttpClientTestingModule], imports: [HttpClientTestingModule],
declarations: [UsuarioExtraUpdateComponent], declarations: [UsuarioExtraUpdateComponent],
providers: [FormBuilder, ActivatedRoute], providers: [FormBuilder, TranslateService],
}) })
.overrideTemplate(UsuarioExtraUpdateComponent, '') .overrideTemplate(UsuarioExtraUpdateComponent, '')
.compileComponents(); .compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(UsuarioExtraUpdateComponent); fixture = TestBed.createComponent(UsuarioExtraUpdateComponent);
activatedRoute = TestBed.inject(ActivatedRoute);
usuarioExtraService = TestBed.inject(UsuarioExtraService);
userService = TestBed.inject(UserService);
plantillaService = TestBed.inject(PlantillaService);
comp = fixture.componentInstance; comp = fixture.componentInstance;
}); });
describe('ngOnInit', () => { it('should ensure the two passwords entered match', () => {
it('Should call User query and add missing value', () => { comp.registerForm.patchValue({
const usuarioExtra: IUsuarioExtra = { id: 456 }; password: 'password',
const user: IUser = { id: 58280 }; confirmPassword: 'non-matching',
usuarioExtra.user = user;
const userCollection: IUser[] = [{ id: 29686 }];
jest.spyOn(userService, 'query').mockReturnValue(of(new HttpResponse({ body: userCollection })));
const additionalUsers = [user];
const expectedCollection: IUser[] = [...additionalUsers, ...userCollection];
jest.spyOn(userService, 'addUserToCollectionIfMissing').mockReturnValue(expectedCollection);
activatedRoute.data = of({ usuarioExtra });
comp.ngOnInit();
expect(userService.query).toHaveBeenCalled();
expect(userService.addUserToCollectionIfMissing).toHaveBeenCalledWith(userCollection, ...additionalUsers);
expect(comp.usersSharedCollection).toEqual(expectedCollection);
}); });
it('Should call Plantilla query and add missing value', () => { comp.register();
const usuarioExtra: IUsuarioExtra = { id: 456 };
const plantillas: IPlantilla[] = [{ id: 54411 }];
usuarioExtra.plantillas = plantillas;
const plantillaCollection: IPlantilla[] = [{ id: 32212 }]; expect(comp.doNotMatch).toBe(true);
jest.spyOn(plantillaService, 'query').mockReturnValue(of(new HttpResponse({ body: plantillaCollection })));
const additionalPlantillas = [...plantillas];
const expectedCollection: IPlantilla[] = [...additionalPlantillas, ...plantillaCollection];
jest.spyOn(plantillaService, 'addPlantillaToCollectionIfMissing').mockReturnValue(expectedCollection);
activatedRoute.data = of({ usuarioExtra });
comp.ngOnInit();
expect(plantillaService.query).toHaveBeenCalled();
expect(plantillaService.addPlantillaToCollectionIfMissing).toHaveBeenCalledWith(plantillaCollection, ...additionalPlantillas);
expect(comp.plantillasSharedCollection).toEqual(expectedCollection);
}); });
it('Should update editForm', () => { it('should update success to true after creating an account', inject(
const usuarioExtra: IUsuarioExtra = { id: 456 }; [RegisterService, TranslateService],
const user: IUser = { id: 30429 }; fakeAsync((service: RegisterService, mockLanguageService: TranslateService) => {
usuarioExtra.user = user; jest.spyOn(service, 'save').mockReturnValue(of({}));
const plantillas: IPlantilla = { id: 61011 }; mockLanguageService.currentLang = 'es';
usuarioExtra.plantillas = [plantillas]; comp.registerForm.patchValue({
password: 'password',
activatedRoute.data = of({ usuarioExtra }); confirmPassword: 'password',
comp.ngOnInit();
expect(comp.editForm.value).toEqual(expect.objectContaining(usuarioExtra));
expect(comp.usersSharedCollection).toContain(user);
expect(comp.plantillasSharedCollection).toContain(plantillas);
});
}); });
describe('save', () => { comp.register();
it('Should call update service on save for existing entity', () => { tick();
// GIVEN
const saveSubject = new Subject<HttpResponse<UsuarioExtra>>();
const usuarioExtra = { id: 123 };
jest.spyOn(usuarioExtraService, 'update').mockReturnValue(saveSubject);
jest.spyOn(comp, 'previousState');
activatedRoute.data = of({ usuarioExtra });
comp.ngOnInit();
// WHEN expect(service.save).toHaveBeenCalledWith({
comp.save(); email: '',
expect(comp.isSaving).toEqual(true); password: 'password',
saveSubject.next(new HttpResponse({ body: usuarioExtra })); login: '',
saveSubject.complete(); langKey: 'es',
name: '',
profileIcon: 1,
isAdmin: 1,
});
expect(comp.success).toBe(true);
expect(comp.errorUserExists).toBe(false);
expect(comp.errorEmailExists).toBe(false);
expect(comp.error).toBe(false);
})
));
// THEN it('should notify of user existence upon 400/login already in use', inject(
expect(comp.previousState).toHaveBeenCalled(); [RegisterService],
expect(usuarioExtraService.update).toHaveBeenCalledWith(usuarioExtra); fakeAsync((service: RegisterService) => {
expect(comp.isSaving).toEqual(false); jest.spyOn(service, 'save').mockReturnValue(
throwError({
status: 400,
error: { type: LOGIN_ALREADY_USED_TYPE },
})
);
comp.registerForm.patchValue({
password: 'password',
confirmPassword: 'password',
}); });
it('Should call create service on save for new entity', () => { comp.register();
// GIVEN tick();
const saveSubject = new Subject<HttpResponse<UsuarioExtra>>();
const usuarioExtra = new UsuarioExtra();
jest.spyOn(usuarioExtraService, 'create').mockReturnValue(saveSubject);
jest.spyOn(comp, 'previousState');
activatedRoute.data = of({ usuarioExtra });
comp.ngOnInit();
// WHEN expect(comp.errorUserExists).toBe(true);
comp.save(); expect(comp.errorEmailExists).toBe(false);
expect(comp.isSaving).toEqual(true); expect(comp.error).toBe(false);
saveSubject.next(new HttpResponse({ body: usuarioExtra })); })
saveSubject.complete(); ));
// THEN it('should notify of email existence upon 400/email address already in use', inject(
expect(usuarioExtraService.create).toHaveBeenCalledWith(usuarioExtra); [RegisterService],
expect(comp.isSaving).toEqual(false); fakeAsync((service: RegisterService) => {
expect(comp.previousState).toHaveBeenCalled(); jest.spyOn(service, 'save').mockReturnValue(
throwError({
status: 400,
error: { type: EMAIL_ALREADY_USED_TYPE },
})
);
comp.registerForm.patchValue({
password: 'password',
confirmPassword: 'password',
}); });
it('Should set isSaving to false on error', () => { comp.register();
// GIVEN tick();
const saveSubject = new Subject<HttpResponse<UsuarioExtra>>();
const usuarioExtra = { id: 123 };
jest.spyOn(usuarioExtraService, 'update').mockReturnValue(saveSubject);
jest.spyOn(comp, 'previousState');
activatedRoute.data = of({ usuarioExtra });
comp.ngOnInit();
// WHEN expect(comp.errorEmailExists).toBe(true);
comp.save(); expect(comp.errorUserExists).toBe(false);
expect(comp.isSaving).toEqual(true); expect(comp.error).toBe(false);
saveSubject.error('This is an error!'); })
));
// THEN it('should notify of generic error', inject(
expect(usuarioExtraService.update).toHaveBeenCalledWith(usuarioExtra); [RegisterService],
expect(comp.isSaving).toEqual(false); fakeAsync((service: RegisterService) => {
expect(comp.previousState).not.toHaveBeenCalled(); jest.spyOn(service, 'save').mockReturnValue(
}); throwError({
status: 503,
})
);
comp.registerForm.patchValue({
password: 'password',
confirmPassword: 'password',
}); });
describe('Tracking relationships identifiers', () => { comp.register();
describe('trackUserById', () => { tick();
it('Should return tracked User primary key', () => {
const entity = { id: 123 };
const trackResult = comp.trackUserById(0, entity);
expect(trackResult).toEqual(entity.id);
});
});
describe('trackPlantillaById', () => { expect(comp.errorUserExists).toBe(false);
it('Should return tracked Plantilla primary key', () => { expect(comp.errorEmailExists).toBe(false);
const entity = { id: 123 }; expect(comp.error).toBe(true);
const trackResult = comp.trackPlantillaById(0, entity); })
expect(trackResult).toEqual(entity.id); ));
});
});
});
describe('Getting selected relationships', () => {
describe('getSelectedPlantilla', () => {
it('Should return option if no Plantilla is selected', () => {
const option = { id: 123 };
const result = comp.getSelectedPlantilla(option);
expect(result === option).toEqual(true);
});
it('Should return selected Plantilla for according option', () => {
const option = { id: 123 };
const selected = { id: 123 };
const selected2 = { id: 456 };
const result = comp.getSelectedPlantilla(option, [selected2, selected]);
expect(result === selected).toEqual(true);
expect(result === selected2).toEqual(false);
expect(result === option).toEqual(false);
});
it('Should return option if this Plantilla is not selected', () => {
const option = { id: 123 };
const selected = { id: 456 };
const result = comp.getSelectedPlantilla(option, [selected]);
expect(result === option).toEqual(true);
expect(result === selected).toEqual(false);
});
});
});
}); });
}); });

View File

@ -1,161 +1,121 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms'; import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router'; import { TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { finalize, map } from 'rxjs/operators';
import * as dayjs from 'dayjs'; import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from 'app/config/error.constants';
import { DATE_TIME_FORMAT } from 'app/config/input.constants'; import { RegisterService } from 'app/account/register/register.service';
import { IUsuarioExtra, UsuarioExtra } from '../usuario-extra.model';
import { UsuarioExtraService } from '../service/usuario-extra.service';
import { IUser } from 'app/entities/user/user.model';
import { UserService } from 'app/entities/user/user.service';
import { IPlantilla } from 'app/entities/plantilla/plantilla.model';
import { PlantillaService } from 'app/entities/plantilla/service/plantilla.service';
@Component({ @Component({
selector: 'jhi-usuario-extra-update', selector: 'jhi-usuario-extra-update',
templateUrl: './usuario-extra-update.component.html', templateUrl: './usuario-extra-update.component.html',
}) })
export class UsuarioExtraUpdateComponent implements OnInit { export class UsuarioExtraUpdateComponent {
isSaving = false; // @ViewChild('name', { static: false })
// name?: ElementRef;
usersSharedCollection: IUser[] = []; profileIcon: number = 1;
plantillasSharedCollection: IPlantilla[] = []; profileIcons: any[] = [
{ name: 'C1', class: 'active' },
{ name: 'C2' },
{ name: 'C3' },
{ name: 'C4' },
{ name: 'C5' },
{ name: 'C6' },
{ name: 'C7' },
{ name: 'C8' },
{ name: 'C9' },
{ name: 'C10' },
{ name: 'C11' },
{ name: 'C12' },
{ name: 'C13' },
{ name: 'C14' },
{ name: 'C15' },
{ name: 'C16' },
{ name: 'C17' },
{ name: 'C18' },
{ name: 'C19' },
{ name: 'C20' },
{ name: 'C21' },
{ name: 'C22' },
{ name: 'C23' },
{ name: 'C24' },
{ name: 'C25' },
{ name: 'C26' },
{ name: 'C27' },
{ name: 'C28' },
];
editForm = this.fb.group({ doNotMatch = false;
id: [], error = false;
nombre: [null, [Validators.required]], errorEmailExists = false;
iconoPerfil: [], errorUserExists = false;
fechaNacimiento: [], success = false;
estado: [null, [Validators.required]],
user: [], // Login will be used to store the email as well.
plantillas: [], // login: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(254), Validators.email]]
registerForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(254)]],
email: ['', [Validators.required, Validators.minLength(5), Validators.maxLength(254), Validators.email]],
password: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(50)]],
confirmPassword: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(50)]],
}); });
constructor( constructor(private translateService: TranslateService, private registerService: RegisterService, private fb: FormBuilder) {}
protected usuarioExtraService: UsuarioExtraService,
protected userService: UserService,
protected plantillaService: PlantillaService,
protected activatedRoute: ActivatedRoute,
protected fb: FormBuilder
) {}
ngOnInit(): void { ngAfterViewInit(): void {
this.activatedRoute.data.subscribe(({ usuarioExtra }) => { // if (this.name) {
if (usuarioExtra.id === undefined) { // this.name.nativeElement.focus();
const today = dayjs().startOf('day'); // }
usuarioExtra.fechaNacimiento = today;
} }
this.updateForm(usuarioExtra); register(): void {
this.doNotMatch = false;
this.error = false;
this.errorEmailExists = false;
this.errorUserExists = false;
this.loadRelationshipsOptions(); const password = this.registerForm.get(['password'])!.value;
}); if (password !== this.registerForm.get(['confirmPassword'])!.value) {
} this.doNotMatch = true;
previousState(): void {
window.history.back();
}
save(): void {
this.isSaving = true;
const usuarioExtra = this.createFromForm();
if (usuarioExtra.id !== undefined) {
this.subscribeToSaveResponse(this.usuarioExtraService.update(usuarioExtra));
} else { } else {
this.subscribeToSaveResponse(this.usuarioExtraService.create(usuarioExtra)); const login = this.registerForm.get(['email'])!.value;
} const email = this.registerForm.get(['email'])!.value;
} const name = this.registerForm.get(['name'])!.value;
console.log(name);
trackUserById(index: number, item: IUser): number { this.registerService
return item.id!; .save({
} login,
email,
trackPlantillaById(index: number, item: IPlantilla): number { password,
return item.id!; langKey: this.translateService.currentLang,
} name,
profileIcon: this.profileIcon,
getSelectedPlantilla(option: IPlantilla, selectedVals?: IPlantilla[]): IPlantilla { isAdmin: 1,
if (selectedVals) { })
for (const selectedVal of selectedVals) { .subscribe(
if (option.id === selectedVal.id) { () => (this.success = true),
return selectedVal; response => this.processError(response)
}
}
}
return option;
}
protected subscribeToSaveResponse(result: Observable<HttpResponse<IUsuarioExtra>>): void {
result.pipe(finalize(() => this.onSaveFinalize())).subscribe(
() => this.onSaveSuccess(),
() => this.onSaveError()
); );
} }
protected onSaveSuccess(): void {
this.previousState();
} }
protected onSaveError(): void { private processError(response: HttpErrorResponse): void {
// Api for inheritance. 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) {
protected onSaveFinalize(): void { this.errorEmailExists = true;
this.isSaving = false; } else {
} this.error = true;
}
protected updateForm(usuarioExtra: IUsuarioExtra): void { }
this.editForm.patchValue({
id: usuarioExtra.id, selectIcon(event: MouseEvent): void {
nombre: usuarioExtra.nombre, if (event.target instanceof Element) {
iconoPerfil: usuarioExtra.iconoPerfil, document.querySelectorAll('.active').forEach(e => e.classList.remove('active'));
fechaNacimiento: usuarioExtra.fechaNacimiento ? usuarioExtra.fechaNacimiento.format(DATE_TIME_FORMAT) : null, event.target.classList.add('active');
estado: usuarioExtra.estado, this.profileIcon = +event.target.getAttribute('id')! + 1;
user: usuarioExtra.user, }
plantillas: usuarioExtra.plantillas,
});
this.usersSharedCollection = this.userService.addUserToCollectionIfMissing(this.usersSharedCollection, usuarioExtra.user);
this.plantillasSharedCollection = this.plantillaService.addPlantillaToCollectionIfMissing(
this.plantillasSharedCollection,
...(usuarioExtra.plantillas ?? [])
);
}
protected loadRelationshipsOptions(): void {
this.userService
.query()
.pipe(map((res: HttpResponse<IUser[]>) => res.body ?? []))
.pipe(map((users: IUser[]) => this.userService.addUserToCollectionIfMissing(users, this.editForm.get('user')!.value)))
.subscribe((users: IUser[]) => (this.usersSharedCollection = users));
this.plantillaService
.query()
.pipe(map((res: HttpResponse<IPlantilla[]>) => res.body ?? []))
.pipe(
map((plantillas: IPlantilla[]) =>
this.plantillaService.addPlantillaToCollectionIfMissing(plantillas, ...(this.editForm.get('plantillas')!.value ?? []))
)
)
.subscribe((plantillas: IPlantilla[]) => (this.plantillasSharedCollection = plantillas));
}
protected createFromForm(): IUsuarioExtra {
return {
...new UsuarioExtra(),
id: this.editForm.get(['id'])!.value,
nombre: this.editForm.get(['nombre'])!.value,
iconoPerfil: this.editForm.get(['iconoPerfil'])!.value,
fechaNacimiento: this.editForm.get(['fechaNacimiento'])!.value
? dayjs(this.editForm.get(['fechaNacimiento'])!.value, DATE_TIME_FORMAT)
: undefined,
estado: this.editForm.get(['estado'])!.value,
user: this.editForm.get(['user'])!.value,
plantillas: this.editForm.get(['plantillas'])!.value,
};
} }
} }

View File

@ -5,9 +5,10 @@ import { UsuarioExtraDetailComponent } from './detail/usuario-extra-detail.compo
import { UsuarioExtraUpdateComponent } from './update/usuario-extra-update.component'; import { UsuarioExtraUpdateComponent } from './update/usuario-extra-update.component';
import { UsuarioExtraDeleteDialogComponent } from './delete/usuario-extra-delete-dialog.component'; import { UsuarioExtraDeleteDialogComponent } from './delete/usuario-extra-delete-dialog.component';
import { UsuarioExtraRoutingModule } from './route/usuario-extra-routing.module'; import { UsuarioExtraRoutingModule } from './route/usuario-extra-routing.module';
import { ComponentsModule } from 'app/components/components.module';
@NgModule({ @NgModule({
imports: [SharedModule, UsuarioExtraRoutingModule], imports: [SharedModule, UsuarioExtraRoutingModule, ComponentsModule],
declarations: [UsuarioExtraComponent, UsuarioExtraDetailComponent, UsuarioExtraUpdateComponent, UsuarioExtraDeleteDialogComponent], declarations: [UsuarioExtraComponent, UsuarioExtraDetailComponent, UsuarioExtraUpdateComponent, UsuarioExtraDeleteDialogComponent],
entryComponents: [UsuarioExtraDeleteDialogComponent], entryComponents: [UsuarioExtraDeleteDialogComponent],
}) })

View File

@ -14,6 +14,7 @@
} }
}, },
"success": "<strong>¡Registro guardado!</strong> Por favor, revise su correo electrónico para confirmar.", "success": "<strong>¡Registro guardado!</strong> Por favor, revise su correo electrónico para confirmar.",
"adminsuccess": "<strong>¡Registro guardado!</strong> Por favor, revise el correo electrónico para confirmar.",
"error": { "error": {
"fail": "<strong>¡El registro ha fallado!</strong> Por favor, inténtelo de nuevo más tarde.", "fail": "<strong>¡El registro ha fallado!</strong> Por favor, inténtelo de nuevo más tarde.",
"userexists": "<strong>¡El nombre de usuario ya está registrado!</strong> Por favor, escoja otro usuario.", "userexists": "<strong>¡El nombre de usuario ya está registrado!</strong> Por favor, escoja otro usuario.",