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',
styleUrls: ['./register.component.scss'],
})
export class RegisterComponent implements OnInit, AfterViewInit {
export class RegisterComponent implements AfterViewInit {
// @ViewChild('name', { static: false })
// name?: ElementRef;
@ -53,7 +53,6 @@ export class RegisterComponent implements OnInit, AfterViewInit {
errorEmailExists = false;
errorUserExists = false;
success = false;
isAdmin: number = 0;
// Login will be used to store the email as well.
// 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) {}
ngOnInit(): void {
this.isAdmin = window.location.href.includes('/account/register') ? 0 : 1;
}
ngAfterViewInit(): void {
// if (this.name) {
// this.name.nativeElement.focus();
@ -99,7 +94,7 @@ export class RegisterComponent implements OnInit, AfterViewInit {
langKey: this.translateService.currentLang,
name,
profileIcon: this.profileIcon,
isAdmin: this.isAdmin,
isAdmin: 0,
})
.subscribe(
() => (this.success = true),

View File

@ -1,118 +1,246 @@
<div class="container">
<div class="row justify-content-center">
<div class="col-8">
<form name="editForm" role="form" novalidate (ngSubmit)="save()" [formGroup]="editForm">
<h2
id="jhi-usuario-extra-heading"
data-cy="UsuarioExtraCreateUpdateHeading"
jhiTranslate="dataSurveyApp.usuarioExtra.home.createOrEditLabel"
>
Create or edit a Usuario Extra
</h2>
<div class="col-xxl-4 col-lg-6">
<div class="card mt-1">
<!-- <div class="pl-4 pt-4 pr-4 pb-1 text-center">
<img src="../../content/img_datasurvey/datasurvey-logo-text-black.svg" alt="" />
</div> -->
<div>
<jhi-alert-error></jhi-alert-error>
<div class="form-group" [hidden]="editForm.get('id')!.value == null">
<label class="form-control-label" jhiTranslate="global.field.id" for="field_id">ID</label>
<input type="number" class="form-control" name="id" id="field_id" data-cy="id" formControlName="id" [readonly]="true" />
<div class="card-body p-4">
<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">
REGISTRAR ADMIN
</h4>
<p class="mb-4" style="color: rgba(146, 146, 146, 0.664)">Ingrese los datos para registrar a un admin.</p>
</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">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.nombre" for="field_nombre">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
>
<label for="name" class="form-label">Nombre</label>
<input
type="text"
class="form-control"
name="iconoPerfil"
id="field_iconoPerfil"
data-cy="iconoPerfil"
formControlName="iconoPerfil"
id="name"
name="name"
placeholder="{{ 'global.form.name.placeholder' | translate }}"
formControlName="name"
data-cy="name"
/>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.fechaNacimiento" for="field_fechaNacimiento"
>Fecha Nacimiento</label
<div *ngIf="registerForm.get('name')!.invalid && (registerForm.get('name')!.dirty || registerForm.get('name')!.touched)">
<small
class="form-text text-danger"
*ngIf="registerForm.get('name')?.errors?.required"
jhiTranslate="global.messages.validate.name.required"
>
<div class="d-flex">
<input
id="field_fechaNacimiento"
data-cy="fechaNacimiento"
type="datetime-local"
class="form-control"
name="fechaNacimiento"
formControlName="fechaNacimiento"
placeholder="YYYY-MM-DD HH:mm"
/>
</div>
</div>
Your name is required.
</small>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.estado" for="field_estado">Estado</label>
<select class="form-control" name="estado" formControlName="estado" id="field_estado" data-cy="estado">
<option [ngValue]="null">{{ 'dataSurveyApp.EstadoUsuario.null' | translate }}</option>
<option value="ACTIVE">{{ 'dataSurveyApp.EstadoUsuario.ACTIVE' | translate }}</option>
<option value="SUSPENDED">{{ 'dataSurveyApp.EstadoUsuario.SUSPENDED' | translate }}</option>
</select>
<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">
This field is required.
<small
class="form-text text-danger"
*ngIf="registerForm.get('name')?.errors?.invalid"
jhiTranslate="global.messages.validate.name.invalid"
>
Your name is invalid.
</small>
<small
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>
</div>
</div>
</div>
<div class="mb-3">
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.user" for="field_user">User</label>
<select class="form-control" id="field_user" data-cy="user" name="user" formControlName="user">
<option [ngValue]="null"></option>
<option
[ngValue]="userOption.id === editForm.get('user')!.value?.id ? editForm.get('user')!.value : userOption"
*ngFor="let userOption of usersSharedCollection; trackBy: trackUserById"
<label for="emailaddress" class="form-label">Correo electrónico</label>
<input
type="email"
class="form-control"
id="email"
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 }}
</option>
</select>
Your email is required.
</small>
<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 class="mb-3">
<div class="form-group">
<label jhiTranslate="dataSurveyApp.usuarioExtra.plantilla" for="field_plantillas">Plantilla</label>
<select class="form-control" id="field_plantillas" data-cy="plantilla" multiple name="plantillas" formControlName="plantillas">
<option
[ngValue]="getSelectedPlantilla(plantillaOption, editForm.get('plantillas')!.value)"
*ngFor="let plantillaOption of plantillasSharedCollection; trackBy: trackPlantillaById"
<label for="password" jhiTranslate="global.form.newpassword.label">Password</label>
<input
type="password"
class="form-control"
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 }}
</option>
</select>
<small
class="form-text text-danger"
*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>
<button type="button" id="cancel-save" data-cy="entityCreateCancelButton" class="btn btn-secondary" (click)="previousState()">
<fa-icon icon="ban"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancel</span>
</button>
<div class="mb-3">
<div class="form-group">
<label for="password" jhiTranslate="global.form.newpassword.label">Password</label>
<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
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
[disabled]="editForm.invalid || isSaving"
class="btn btn-primary"
[disabled]="registerForm.invalid"
class="btn btn-primary w-100"
jhiTranslate="register.form.button"
data-cy="submit"
>
<fa-icon icon="save"></fa-icon>&nbsp;<span jhiTranslate="entity.action.save">Save</span>
Register
</button>
</div>
</form>
</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 { HttpResponse } from '@angular/common/http';
import { ComponentFixture, TestBed, waitForAsync, inject, tick, fakeAsync } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { FormBuilder } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { of, Subject } from 'rxjs';
import { of, throwError } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
import { UsuarioExtraService } from '../service/usuario-extra.service';
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 { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from 'app/config/error.constants';
import { RegisterService } from 'app/account/register/register.service';
import { UsuarioExtraUpdateComponent } from './usuario-extra-update.component';
describe('Component Tests', () => {
describe('UsuarioExtra Management Update Component', () => {
let comp: UsuarioExtraUpdateComponent;
describe('RegisterComponent', () => {
let fixture: ComponentFixture<UsuarioExtraUpdateComponent>;
let activatedRoute: ActivatedRoute;
let usuarioExtraService: UsuarioExtraService;
let userService: UserService;
let plantillaService: PlantillaService;
let comp: UsuarioExtraUpdateComponent;
beforeEach(() => {
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [UsuarioExtraUpdateComponent],
providers: [FormBuilder, ActivatedRoute],
providers: [FormBuilder, TranslateService],
})
.overrideTemplate(UsuarioExtraUpdateComponent, '')
.compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(UsuarioExtraUpdateComponent);
activatedRoute = TestBed.inject(ActivatedRoute);
usuarioExtraService = TestBed.inject(UsuarioExtraService);
userService = TestBed.inject(UserService);
plantillaService = TestBed.inject(PlantillaService);
comp = fixture.componentInstance;
});
describe('ngOnInit', () => {
it('Should call User query and add missing value', () => {
const usuarioExtra: IUsuarioExtra = { id: 456 };
const user: IUser = { id: 58280 };
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 ensure the two passwords entered match', () => {
comp.registerForm.patchValue({
password: 'password',
confirmPassword: 'non-matching',
});
it('Should call Plantilla query and add missing value', () => {
const usuarioExtra: IUsuarioExtra = { id: 456 };
const plantillas: IPlantilla[] = [{ id: 54411 }];
usuarioExtra.plantillas = plantillas;
comp.register();
const plantillaCollection: IPlantilla[] = [{ id: 32212 }];
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);
expect(comp.doNotMatch).toBe(true);
});
it('Should update editForm', () => {
const usuarioExtra: IUsuarioExtra = { id: 456 };
const user: IUser = { id: 30429 };
usuarioExtra.user = user;
const plantillas: IPlantilla = { id: 61011 };
usuarioExtra.plantillas = [plantillas];
activatedRoute.data = of({ usuarioExtra });
comp.ngOnInit();
expect(comp.editForm.value).toEqual(expect.objectContaining(usuarioExtra));
expect(comp.usersSharedCollection).toContain(user);
expect(comp.plantillasSharedCollection).toContain(plantillas);
});
it('should update success to true after creating an account', inject(
[RegisterService, TranslateService],
fakeAsync((service: RegisterService, mockLanguageService: TranslateService) => {
jest.spyOn(service, 'save').mockReturnValue(of({}));
mockLanguageService.currentLang = 'es';
comp.registerForm.patchValue({
password: 'password',
confirmPassword: 'password',
});
describe('save', () => {
it('Should call update service on save for existing entity', () => {
// 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();
comp.register();
tick();
// WHEN
comp.save();
expect(comp.isSaving).toEqual(true);
saveSubject.next(new HttpResponse({ body: usuarioExtra }));
saveSubject.complete();
expect(service.save).toHaveBeenCalledWith({
email: '',
password: 'password',
login: '',
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
expect(comp.previousState).toHaveBeenCalled();
expect(usuarioExtraService.update).toHaveBeenCalledWith(usuarioExtra);
expect(comp.isSaving).toEqual(false);
it('should notify of user existence upon 400/login already in use', inject(
[RegisterService],
fakeAsync((service: RegisterService) => {
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', () => {
// GIVEN
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();
comp.register();
tick();
// WHEN
comp.save();
expect(comp.isSaving).toEqual(true);
saveSubject.next(new HttpResponse({ body: usuarioExtra }));
saveSubject.complete();
expect(comp.errorUserExists).toBe(true);
expect(comp.errorEmailExists).toBe(false);
expect(comp.error).toBe(false);
})
));
// THEN
expect(usuarioExtraService.create).toHaveBeenCalledWith(usuarioExtra);
expect(comp.isSaving).toEqual(false);
expect(comp.previousState).toHaveBeenCalled();
it('should notify of email existence upon 400/email address already in use', inject(
[RegisterService],
fakeAsync((service: RegisterService) => {
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', () => {
// 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();
comp.register();
tick();
// WHEN
comp.save();
expect(comp.isSaving).toEqual(true);
saveSubject.error('This is an error!');
expect(comp.errorEmailExists).toBe(true);
expect(comp.errorUserExists).toBe(false);
expect(comp.error).toBe(false);
})
));
// THEN
expect(usuarioExtraService.update).toHaveBeenCalledWith(usuarioExtra);
expect(comp.isSaving).toEqual(false);
expect(comp.previousState).not.toHaveBeenCalled();
});
it('should notify of generic error', inject(
[RegisterService],
fakeAsync((service: RegisterService) => {
jest.spyOn(service, 'save').mockReturnValue(
throwError({
status: 503,
})
);
comp.registerForm.patchValue({
password: 'password',
confirmPassword: 'password',
});
describe('Tracking relationships identifiers', () => {
describe('trackUserById', () => {
it('Should return tracked User primary key', () => {
const entity = { id: 123 };
const trackResult = comp.trackUserById(0, entity);
expect(trackResult).toEqual(entity.id);
});
});
comp.register();
tick();
describe('trackPlantillaById', () => {
it('Should return tracked Plantilla primary key', () => {
const entity = { id: 123 };
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);
});
});
});
expect(comp.errorUserExists).toBe(false);
expect(comp.errorEmailExists).toBe(false);
expect(comp.error).toBe(true);
})
));
});
});

View File

@ -1,161 +1,121 @@
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 { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
import { finalize, map } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import * as dayjs from 'dayjs';
import { DATE_TIME_FORMAT } from 'app/config/input.constants';
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';
import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from 'app/config/error.constants';
import { RegisterService } from 'app/account/register/register.service';
@Component({
selector: 'jhi-usuario-extra-update',
templateUrl: './usuario-extra-update.component.html',
})
export class UsuarioExtraUpdateComponent implements OnInit {
isSaving = false;
export class UsuarioExtraUpdateComponent {
// @ViewChild('name', { static: false })
// name?: ElementRef;
usersSharedCollection: IUser[] = [];
plantillasSharedCollection: IPlantilla[] = [];
profileIcon: number = 1;
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({
id: [],
nombre: [null, [Validators.required]],
iconoPerfil: [],
fechaNacimiento: [],
estado: [null, [Validators.required]],
user: [],
plantillas: [],
doNotMatch = false;
error = false;
errorEmailExists = false;
errorUserExists = false;
success = false;
// Login will be used to store the email as well.
// 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(
protected usuarioExtraService: UsuarioExtraService,
protected userService: UserService,
protected plantillaService: PlantillaService,
protected activatedRoute: ActivatedRoute,
protected fb: FormBuilder
) {}
constructor(private translateService: TranslateService, private registerService: RegisterService, private fb: FormBuilder) {}
ngOnInit(): void {
this.activatedRoute.data.subscribe(({ usuarioExtra }) => {
if (usuarioExtra.id === undefined) {
const today = dayjs().startOf('day');
usuarioExtra.fechaNacimiento = today;
ngAfterViewInit(): void {
// if (this.name) {
// this.name.nativeElement.focus();
// }
}
this.updateForm(usuarioExtra);
register(): void {
this.doNotMatch = false;
this.error = false;
this.errorEmailExists = false;
this.errorUserExists = false;
this.loadRelationshipsOptions();
});
}
previousState(): void {
window.history.back();
}
save(): void {
this.isSaving = true;
const usuarioExtra = this.createFromForm();
if (usuarioExtra.id !== undefined) {
this.subscribeToSaveResponse(this.usuarioExtraService.update(usuarioExtra));
const password = this.registerForm.get(['password'])!.value;
if (password !== this.registerForm.get(['confirmPassword'])!.value) {
this.doNotMatch = true;
} 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 {
return item.id!;
}
trackPlantillaById(index: number, item: IPlantilla): number {
return item.id!;
}
getSelectedPlantilla(option: IPlantilla, selectedVals?: IPlantilla[]): IPlantilla {
if (selectedVals) {
for (const selectedVal of selectedVals) {
if (option.id === selectedVal.id) {
return selectedVal;
}
}
}
return option;
}
protected subscribeToSaveResponse(result: Observable<HttpResponse<IUsuarioExtra>>): void {
result.pipe(finalize(() => this.onSaveFinalize())).subscribe(
() => this.onSaveSuccess(),
() => this.onSaveError()
this.registerService
.save({
login,
email,
password,
langKey: this.translateService.currentLang,
name,
profileIcon: this.profileIcon,
isAdmin: 1,
})
.subscribe(
() => (this.success = true),
response => this.processError(response)
);
}
protected onSaveSuccess(): void {
this.previousState();
}
protected onSaveError(): void {
// Api for inheritance.
}
protected onSaveFinalize(): void {
this.isSaving = false;
}
protected updateForm(usuarioExtra: IUsuarioExtra): void {
this.editForm.patchValue({
id: usuarioExtra.id,
nombre: usuarioExtra.nombre,
iconoPerfil: usuarioExtra.iconoPerfil,
fechaNacimiento: usuarioExtra.fechaNacimiento ? usuarioExtra.fechaNacimiento.format(DATE_TIME_FORMAT) : null,
estado: usuarioExtra.estado,
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,
};
private processError(response: HttpErrorResponse): void {
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) {
this.errorEmailExists = true;
} else {
this.error = true;
}
}
selectIcon(event: MouseEvent): void {
if (event.target instanceof Element) {
document.querySelectorAll('.active').forEach(e => e.classList.remove('active'));
event.target.classList.add('active');
this.profileIcon = +event.target.getAttribute('id')! + 1;
}
}
}

View File

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

View File

@ -14,6 +14,7 @@
}
},
"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": {
"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.",