Merge branch 'dev' into feature/US-07

This commit is contained in:
Mariela Bonilla 2021-07-08 17:23:52 -06:00
commit 64af3725de
22 changed files with 517 additions and 449 deletions

2
.gitignore vendored
View File

@ -157,3 +157,5 @@ Desktop.ini
###################### ######################
/coverage/ /coverage/
/.nyc_output/ /.nyc_output/
.mvn/wrapper/maven-wrapper.jar

0
mvnw vendored Normal file → Executable file
View File

0
npmw Normal file → Executable file
View File

View File

@ -156,8 +156,7 @@ public class UserService {
* Modified to register extra user data * Modified to register extra user data
* name, iconoPerfil, fechaNacimiento, estado, pais * name, iconoPerfil, fechaNacimiento, estado, pais
*/ */
public User registerUser(AdminUserDTO userDTO, String password, String name, Integer profileIcon) { public User registerUser(AdminUserDTO userDTO, String password, String name, Integer profileIcon, Integer isAdmin) {
System.out.println(name);
userRepository userRepository
.findOneByLogin(userDTO.getLogin().toLowerCase()) .findOneByLogin(userDTO.getLogin().toLowerCase())
.ifPresent( .ifPresent(
@ -195,7 +194,12 @@ public class UserService {
// new user gets registration key // new user gets registration key
newUser.setActivationKey(RandomUtil.generateActivationKey()); newUser.setActivationKey(RandomUtil.generateActivationKey());
Set<Authority> authorities = new HashSet<>(); Set<Authority> authorities = new HashSet<>();
// Check whether it's an ADMIN or USER and apply authorities
if (isAdmin == 1) {
authorityRepository.findById(AuthoritiesConstants.ADMIN).ifPresent(authorities::add);
}
authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add); authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add);
newUser.setAuthorities(authorities); newUser.setAuthorities(authorities);
userRepository.save(newUser); userRepository.save(newUser);
this.clearUserCaches(newUser); this.clearUserCaches(newUser);

View File

@ -66,7 +66,8 @@ public class AccountResource {
managedUserVM, managedUserVM,
managedUserVM.getPassword(), managedUserVM.getPassword(),
managedUserVM.getName(), managedUserVM.getName(),
managedUserVM.getProfileIcon() managedUserVM.getProfileIcon(),
managedUserVM.getIsAdmin()
); );
mailService.sendActivationEmail(user); mailService.sendActivationEmail(user);
} }

View File

@ -22,6 +22,8 @@ public class ManagedUserVM extends AdminUserDTO {
private Integer profileIcon; private Integer profileIcon;
private Integer isAdmin;
public ManagedUserVM() { public ManagedUserVM() {
// Empty constructor needed for Jackson. // Empty constructor needed for Jackson.
} }
@ -50,6 +52,14 @@ public class ManagedUserVM extends AdminUserDTO {
this.profileIcon = profileIcon; this.profileIcon = profileIcon;
} }
public Integer getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(Integer isAdmin) {
this.isAdmin = isAdmin;
}
// prettier-ignore // prettier-ignore
@Override @Override
public String toString() { public String toString() {

View File

@ -64,6 +64,7 @@ describe('Component Tests', () => {
langKey: 'es', langKey: 'es',
name: '', name: '',
profileIcon: 1, profileIcon: 1,
isAdmin: 0,
}); });
expect(comp.success).toBe(true); expect(comp.success).toBe(true);
expect(comp.errorUserExists).toBe(false); expect(comp.errorUserExists).toBe(false);

View File

@ -1,7 +1,8 @@
import { Component, AfterViewInit, ElementRef, ViewChild } from '@angular/core'; import { Component, OnInit, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms'; import { FormBuilder, Validators } from '@angular/forms';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { Router } from '@angular/router';
import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from 'app/config/error.constants'; import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from 'app/config/error.constants';
import { RegisterService } from './register.service'; import { RegisterService } from './register.service';
@ -86,7 +87,15 @@ export class RegisterComponent implements AfterViewInit {
console.log(name); console.log(name);
this.registerService this.registerService
.save({ login, email, password, langKey: this.translateService.currentLang, name, profileIcon: this.profileIcon }) .save({
login,
email,
password,
langKey: this.translateService.currentLang,
name,
profileIcon: this.profileIcon,
isAdmin: 0,
})
.subscribe( .subscribe(
() => (this.success = true), () => (this.success = true),
response => this.processError(response) response => this.processError(response)

View File

@ -5,6 +5,7 @@ export class Registration {
public password: string, public password: string,
public langKey: string, public langKey: string,
public name: string, public name: string,
public profileIcon: number public profileIcon: number,
public isAdmin: number
) {} ) {}
} }

View File

@ -18,6 +18,7 @@ describe('Component Tests', () => {
let fixture: ComponentFixture<SettingsComponent>; let fixture: ComponentFixture<SettingsComponent>;
let mockAccountService: AccountService; let mockAccountService: AccountService;
const account: Account = { const account: Account = {
id: 0,
firstName: 'John', firstName: 'John',
lastName: 'Doe', lastName: 'Doe',
activated: true, activated: true,

View File

@ -1,5 +1,6 @@
export class Account { export class Account {
constructor( constructor(
public id: number,
public activated: boolean, public activated: boolean,
public authorities: string[], public authorities: string[],
public email: string, public email: string,

View File

@ -19,6 +19,7 @@ import { AccountService } from './account.service';
function accountWithAuthorities(authorities: string[]): Account { function accountWithAuthorities(authorities: string[]): Account {
return { return {
id: 0,
activated: true, activated: true,
authorities, authorities,
email: '', email: '',

View File

@ -1,118 +1,246 @@
<div class="row justify-content-center"> <div class="container">
<div class="col-8"> <div class="row justify-content-center">
<form name="editForm" role="form" novalidate (ngSubmit)="save()" [formGroup]="editForm"> <div class="col-xxl-8 col-lg-6">
<h2 <div class="card mt-1">
id="jhi-usuario-extra-heading" <!-- <div class="pl-4 pt-4 pr-4 pb-1 text-center">
data-cy="UsuarioExtraCreateUpdateHeading" <img src="../../content/img_datasurvey/datasurvey-logo-text-black.svg" alt="" />
jhiTranslate="dataSurveyApp.usuarioExtra.home.createOrEditLabel" </div> -->
>
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 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>
<div class="form-group"> <div class="alert alert-success" *ngIf="success" jhiTranslate="register.messages.adminsuccess">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.iconoPerfil" for="field_iconoPerfil" <strong>Registration saved!</strong> Please check your email for confirmation.
>Icono Perfil</label
>
<input
type="text"
class="form-control"
name="iconoPerfil"
id="field_iconoPerfil"
data-cy="iconoPerfil"
formControlName="iconoPerfil"
/>
</div>
<div class="form-group">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.fechaNacimiento" for="field_fechaNacimiento"
>Fecha Nacimiento</label
>
<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>
</div>
<div class="form-group"> <div class="alert alert-danger" *ngIf="error" jhiTranslate="register.messages.error.fail">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.estado" for="field_estado">Estado</label> <strong>Registration failed!</strong> Please try again later.
<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>
</div> </div>
</div>
<div class="form-group"> <div class="alert alert-danger" *ngIf="errorEmailExists" jhiTranslate="register.messages.error.emailexists">
<label class="form-control-label" jhiTranslate="dataSurveyApp.usuarioExtra.user" for="field_user">User</label> <strong>Email is already in use!</strong> Please choose another one.
<select class="form-control" id="field_user" data-cy="user" name="user" formControlName="user"> </div>
<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"
>
{{ userOption.id }}
</option>
</select>
</div>
<div class="form-group"> <div class="alert alert-danger" *ngIf="doNotMatch" jhiTranslate="global.messages.error.dontmatch">
<label jhiTranslate="dataSurveyApp.usuarioExtra.plantilla" for="field_plantillas">Plantilla</label> The password and its confirmation do not match!
<select class="form-control" id="field_plantillas" data-cy="plantilla" multiple name="plantillas" formControlName="plantillas"> </div>
<option
[ngValue]="getSelectedPlantilla(plantillaOption, editForm.get('plantillas')!.value)" <form name="form" role="form" class="form" (ngSubmit)="register()" [formGroup]="registerForm" *ngIf="!success" autocomplete="off">
*ngFor="let plantillaOption of plantillasSharedCollection; trackBy: trackPlantillaById" <div class="mb-3">
> <div class="form-group">
{{ plantillaOption.id }} <label for="name" class="form-label">Nombre</label>
</option> <input
</select> type="text"
class="form-control"
id="name"
name="name"
placeholder="{{ 'global.form.name.placeholder' | translate }}"
formControlName="name"
data-cy="name"
/>
<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"
>
Your name is required.
</small>
<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 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"
>
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 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)
"
>
<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 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"
[disabled]="registerForm.invalid"
class="btn btn-primary w-100"
jhiTranslate="register.form.button"
data-cy="submit"
>
Register
</button>
</div>
</form>
</div> </div>
</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>
<button
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
[disabled]="editForm.invalid || isSaving"
class="btn btn-primary"
>
<fa-icon icon="save"></fa-icon>&nbsp;<span jhiTranslate="entity.action.save">Save</span>
</button>
</div>
</form>
</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; beforeEach(
let plantillaService: PlantillaService; waitForAsync(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [UsuarioExtraUpdateComponent],
providers: [FormBuilder, TranslateService],
})
.overrideTemplate(UsuarioExtraUpdateComponent, '')
.compileComponents();
})
);
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [UsuarioExtraUpdateComponent],
providers: [FormBuilder, ActivatedRoute],
})
.overrideTemplate(UsuarioExtraUpdateComponent, '')
.compileComponents();
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', () => {
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);
});
}); });
describe('save', () => { it('should update success to true after creating an account', inject(
it('Should call update service on save for existing entity', () => { [RegisterService, TranslateService],
// GIVEN fakeAsync((service: RegisterService, mockLanguageService: TranslateService) => {
const saveSubject = new Subject<HttpResponse<UsuarioExtra>>(); jest.spyOn(service, 'save').mockReturnValue(of({}));
const usuarioExtra = { id: 123 }; mockLanguageService.currentLang = 'es';
jest.spyOn(usuarioExtraService, 'update').mockReturnValue(saveSubject); comp.registerForm.patchValue({
jest.spyOn(comp, 'previousState'); password: 'password',
activatedRoute.data = of({ usuarioExtra }); confirmPassword: 'password',
comp.ngOnInit();
// WHEN
comp.save();
expect(comp.isSaving).toEqual(true);
saveSubject.next(new HttpResponse({ body: usuarioExtra }));
saveSubject.complete();
// THEN
expect(comp.previousState).toHaveBeenCalled();
expect(usuarioExtraService.update).toHaveBeenCalledWith(usuarioExtra);
expect(comp.isSaving).toEqual(false);
});
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();
// WHEN
comp.save();
expect(comp.isSaving).toEqual(true);
saveSubject.next(new HttpResponse({ body: usuarioExtra }));
saveSubject.complete();
// THEN
expect(usuarioExtraService.create).toHaveBeenCalledWith(usuarioExtra);
expect(comp.isSaving).toEqual(false);
expect(comp.previousState).toHaveBeenCalled();
});
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();
// WHEN
comp.save();
expect(comp.isSaving).toEqual(true);
saveSubject.error('This is an error!');
// THEN
expect(usuarioExtraService.update).toHaveBeenCalledWith(usuarioExtra);
expect(comp.isSaving).toEqual(false);
expect(comp.previousState).not.toHaveBeenCalled();
});
});
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);
});
});
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', () => { comp.register();
const option = { id: 123 }; tick();
const selected = { id: 123 };
const selected2 = { id: 456 }; expect(service.save).toHaveBeenCalledWith({
const result = comp.getSelectedPlantilla(option, [selected2, selected]); email: '',
expect(result === selected).toEqual(true); password: 'password',
expect(result === selected2).toEqual(false); login: '',
expect(result === option).toEqual(false); 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);
})
));
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 return option if this Plantilla is not selected', () => { comp.register();
const option = { id: 123 }; tick();
const selected = { id: 456 };
const result = comp.getSelectedPlantilla(option, [selected]); expect(comp.errorUserExists).toBe(true);
expect(result === option).toEqual(true); expect(comp.errorEmailExists).toBe(false);
expect(result === selected).toEqual(false); expect(comp.error).toBe(false);
})
));
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',
}); });
});
}); comp.register();
tick();
expect(comp.errorEmailExists).toBe(true);
expect(comp.errorUserExists).toBe(false);
expect(comp.error).toBe(false);
})
));
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',
});
comp.register();
tick();
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 { 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);
this.loadRelationshipsOptions();
});
} }
previousState(): void { register(): void {
window.history.back(); this.doNotMatch = false;
} this.error = false;
this.errorEmailExists = false;
this.errorUserExists = false;
save(): void { const password = this.registerForm.get(['password'])!.value;
this.isSaving = true; if (password !== this.registerForm.get(['confirmPassword'])!.value) {
const usuarioExtra = this.createFromForm(); this.doNotMatch = true;
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);
this.registerService
.save({
login,
email,
password,
langKey: this.translateService.currentLang,
name,
profileIcon: this.profileIcon,
isAdmin: 1,
})
.subscribe(
() => (this.success = true),
response => this.processError(response)
);
} }
} }
trackUserById(index: number, item: IUser): number { private processError(response: HttpErrorResponse): void {
return item.id!; 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) {
trackPlantillaById(index: number, item: IPlantilla): number { this.errorEmailExists = true;
return item.id!; } else {
} this.error = true;
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 { selectIcon(event: MouseEvent): void {
result.pipe(finalize(() => this.onSaveFinalize())).subscribe( if (event.target instanceof Element) {
() => this.onSaveSuccess(), document.querySelectorAll('.active').forEach(e => e.classList.remove('active'));
() => this.onSaveError() event.target.classList.add('active');
); this.profileIcon = +event.target.getAttribute('id')! + 1;
} }
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,
};
} }
} }

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

@ -17,6 +17,7 @@ describe('Component Tests', () => {
let mockAccountService: AccountService; let mockAccountService: AccountService;
let mockRouter: Router; let mockRouter: Router;
const account: Account = { const account: Account = {
id: 0,
activated: true, activated: true,
authorities: [], authorities: [],
email: '', email: '',

View File

@ -9,12 +9,12 @@
<div class="sidebar-wrapper"> <div class="sidebar-wrapper">
<div class="user" routerLink="/account/settings"> <div class="user" routerLink="/account/settings">
<div class="photo mb-2"> <div class="photo mb-2">
<img src="../../../content/profile_icons/C2.png" /> <img src="../../../content/profile_icons/C{{ usuarioExtra?.iconoPerfil }}.png" />
</div> </div>
<div class="info"> <div class="info">
<a data-toggle="collapse" class="collapsed"> <a data-toggle="collapse" class="collapsed">
<span> <span>
Pablo Bonilla {{ usuarioExtra?.nombre }}
<!-- <b class="caret"></b> --> <!-- <b class="caret"></b> -->
</span> </span>
</a> </a>

View File

@ -8,6 +8,8 @@ import { LoginService } from 'app/login/login.service';
import { ProfileService } from 'app/layouts/profiles/profile.service'; import { ProfileService } from 'app/layouts/profiles/profile.service';
import { SessionStorageService } from 'ngx-webstorage'; import { SessionStorageService } from 'ngx-webstorage';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { UsuarioExtraService } from 'app/entities/usuario-extra/service/usuario-extra.service';
import { UsuarioExtra } from 'app/entities/usuario-extra/usuario-extra.model';
@Component({ @Component({
selector: 'jhi-sidebar', selector: 'jhi-sidebar',
@ -24,12 +26,15 @@ export class SidebarComponent {
version = ''; version = '';
account: Account | null = null; account: Account | null = null;
usuarioExtra: UsuarioExtra | null = null;
constructor( constructor(
private loginService: LoginService, private loginService: LoginService,
private sessionStorageService: SessionStorageService, private sessionStorageService: SessionStorageService,
private accountService: AccountService, private accountService: AccountService,
private profileService: ProfileService, private profileService: ProfileService,
private router: Router private router: Router,
private usuarioExtraService: UsuarioExtraService
) { ) {
if (VERSION) { if (VERSION) {
this.version = VERSION.toLowerCase().startsWith('v') ? VERSION : 'v' + VERSION; this.version = VERSION.toLowerCase().startsWith('v') ? VERSION : 'v' + VERSION;
@ -48,7 +53,16 @@ export class SidebarComponent {
this.inProduction = profileInfo.inProduction; this.inProduction = profileInfo.inProduction;
this.openAPIEnabled = profileInfo.openAPIEnabled; this.openAPIEnabled = profileInfo.openAPIEnabled;
}); });
this.accountService.getAuthenticationState().subscribe(account => (this.account = account));
// Get jhi_user and usuario_extra information
this.accountService.getAuthenticationState().subscribe(account => {
this.account = account;
if (account !== null) {
this.usuarioExtraService.find(account.id).subscribe(usuarioExtra => {
this.usuarioExtra = usuarioExtra.body;
});
}
});
} }
ngAfterViewInit() {} ngAfterViewInit() {}

View File

@ -2,20 +2,20 @@
"dataSurveyApp": { "dataSurveyApp": {
"categoria": { "categoria": {
"home": { "home": {
"title": "Categorias", "title": "Categorías",
"refreshListLabel": "Refrescar lista", "refreshListLabel": "Refrescar lista",
"createLabel": "Crear nuevo Categoria", "createLabel": "Crear nueva Categoría",
"createOrEditLabel": "Crear o editar Categoria", "createOrEditLabel": "Crear o editar Categoría",
"notFound": "Ningún Categorias encontrado" "notFound": "Ninguna Categoría encontrada"
}, },
"created": "Un nuevo Categoria ha sido creado con el identificador {{ param }}", "created": "Una nueva Categoría ha sido creada con el identificador {{ param }}",
"updated": "Un Categoria ha sido actualizado con el identificador {{ param }}", "updated": "Una Categoría ha sido actualizado con el identificador {{ param }}",
"deleted": "Un Categoria ha sido eliminado con el identificador {{ param }}", "deleted": "Una Categoría ha sido eliminado con el identificador {{ param }}",
"delete": { "delete": {
"question": "¿Seguro que quiere eliminar Categoria {{ id }}?" "question": "¿Seguro que quiere eliminar Categoría {{ id }}?"
}, },
"detail": { "detail": {
"title": "Categoria" "title": "Categoría"
}, },
"id": "ID", "id": "ID",
"nombre": "Nombre", "nombre": "Nombre",

View File

@ -2,8 +2,8 @@
"dataSurveyApp": { "dataSurveyApp": {
"EstadoCategoria": { "EstadoCategoria": {
"null": "", "null": "",
"ACTIVE": "ACTIVE", "ACTIVE": "ACTIVA",
"INACTIVE": "INACTIVE" "INACTIVE": "INACTIVA"
} }
} }
} }

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.",