Commit 53366081 authored by Heber Cordova's avatar Heber Cordova

feat: finished agent maintenance

parent 440544e3
This diff is collapsed.
......@@ -3,6 +3,7 @@ import { RouterModule, Routes } from '@angular/router';
import { AgentHomePageComponent } from './pages/home-page/home-page.component';
import { PassengersComponent } from './pages/passengers/passengers.component';
import { ReservationsComponent } from './pages/reservations/reservations.component';
import { PassengerAddComponent } from './pages/passenger-add/passenger-add.component';
const routes: Routes = [
{
......@@ -15,6 +16,16 @@ const routes: Routes = [
title: 'Pasajeros',
component: PassengersComponent
},
{
path: 'passengers/new',
title: 'Pasajeros',
component: PassengerAddComponent
},
{
path: 'passengers/edit/:id',
title: 'Pasajeros',
component: PassengerAddComponent
},
{
path: 'reservations',
title: 'Reservas',
......
......@@ -5,22 +5,27 @@ import { AgentRoutingModule } from './agent-routing.module';
import { AgentHomePageComponent } from './pages/home-page/home-page.component';
import { PassengersComponent } from './pages/passengers/passengers.component';
import { ReservationsComponent } from './pages/reservations/reservations.component';
import { PassengerAddComponent } from './pages/passenger-add/passenger-add.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AgentHomePageComponent,
PassengersComponent,
ReservationsComponent
ReservationsComponent,
PassengerAddComponent
],
imports: [
CommonModule,
SharedModule,
AgentRoutingModule
AgentRoutingModule,
HttpClientModule,
ReactiveFormsModule,
FormsModule,
],
exports:[
AgentRoutingModule
AgentRoutingModule,
]
})
export class AgentModule { }
export interface PassengerTable {
id: number;
name: string;
lastname: string;
country: string;
city: string;
}
export interface Passenger {
id: number;
name: string;
secondName: string;
lastname: string;
phone: string;
country: string;
city: string;
address: string;
email: string;
password: string;
}
export const EMPTY_PASSENGER: Passenger = {
id: 0,
name: '',
secondName: '',
lastname: '',
country: '',
city: '',
address: '',
phone: '',
email: '',
password: ''
};
......@@ -3,7 +3,7 @@
<shared-sidebar [toggle]="toggleSidebar" [menuItems]="menuItems"></shared-sidebar>
</div>
<div class="w-100">
<shared-navigation-user></shared-navigation-user>
<shared-navigation-user (toggleSidebarEvent)="toggleSidebarEvent()"></shared-navigation-user>
<router-outlet></router-outlet>
</div>
</div>
......@@ -13,12 +13,12 @@ export class AgentHomePageComponent {
public menuItems: MenuItem[] = [
{
label: 'Pasajeros',
icon: 'bi-heart',
icon: 'bi-people',
link: '/agents/passengers'
},
{
label: 'Reservas',
icon: 'bi-bookmarks',
icon: 'bi-bookmarks-fill',
link: '/agents/reservations'
},
];
......
.info, .credentials {
padding: 16px 32px 0 32px;
}
.info__title, .credentials__title {
font-size: 16px;
font-weight: 500;
border-bottom: 1px solid #8f8e8e;
padding-bottom: 10px;
margin-bottom: 30px;
}
.btn-save {
background-color: #1ab394;
border: #1ab394;
font-size: 12px;
}
.form__actions {
display: flex;
justify-content: flex-end;
margin-bottom: 8px;
}
/* Forms */
.custom-input {
position: relative;
margin-bottom: 30px;
}
.custom-input input {
......@@ -34,15 +62,18 @@
.custom-input input:focus + label {
top: -12px;
left: 1px;
left: 12px;
font-size: 12px;
color: #3f51b5;
}
.custom-input input:valid + label {
.custom-input input + label {
top: -12px;
left: 1px;
left: 12px;
font-size: 12px;
color: #ccc;
}
.custom-input-detail {
font-size: 12px;
}
<shared-navigation></shared-navigation>
<shared-mail-box
title="Pasajeros"
message="Este mantenimiento permite gestionar los pasajeros dentro de la agencia"
icon="bi-people"
[btnBack]="true">
<form [formGroup]="passengerForm" (ngSubmit)="onSave()" autocomplete="off">
<section class="info">
<h3 class="info__title">Información general</h3>
<div class="info__fields row">
<div class="col-6 custom-input">
<input type="text" name="name" formControlName="name" id="custom-input-name">
<label for="custom-input-name">Nombre *</label>
</div>
<div class="col-6 custom-input">
<input type="text" name="secondName" formControlName="secondName" id="custom-input-second">
<label for="custom-input-second">Segundo nombre *</label>
</div>
<div class="col-6 custom-input">
<input type="text" name="lastname" formControlName="lastname" id="custom-input-lastname">
<label for="custom-input-lastname">Apellidos *</label>
</div>
<div class="col-6 custom-input">
<input type="text" name="phone" formControlName="phone" id="custom-input-phone">
<label for="custom-input-phone">Telefono *</label>
</div>
<div class="col-6 custom-input">
<input type="text" name="country" formControlName="country" id="custom-input-country">
<label for="custom-input-country">Pais *</label>
</div>
<div class="col-6 custom-input">
<input type="text" name="city" formControlName="city" id="custom-input-city">
<label for="custom-input-city">Ciudad *</label>
</div>
<div class="col-12 custom-input">
<input type="text" name="address" formControlName="address" id="custom-input-address">
<label for="custom-input-address">Direccion *</label>
</div>
</div>
</section>
<section class="credentials">
<h3 class="credentials__title">Credenciales</h3>
<div class="credentials__fields row">
<div class="col-12 custom-input">
<input type="text" name="email" formControlName="email" id="custom-input-email">
<label for="custom-input-email">Email *</label>
</div>
<div class="col-12 custom-input">
<input type="password" name="password" formControlName="password" id="custom-input-password">
<label for="custom-input-password">Password *</label>
</div>
</div>
</section>
<hr>
<div class="form__actions">
<button [disabled]="!passengerForm.valid" class="btn btn-save">
<i class="bi bi-save me-1"></i>
<span>Guardar</span>
</button>
</div>
</form>
</shared-mail-box>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { PassengerService } from '../../services/passenger-service.service';
import { EMPTY_PASSENGER, Passenger } from '../../interfaces/passenger.interface';
@Component({
selector: 'app-passenger-add',
templateUrl: './passenger-add.component.html',
styleUrls: ['./passenger-add.component.css']
})
export class PassengerAddComponent implements OnInit {
public passengerForm: FormGroup = new FormGroup({
name: new FormControl('', [Validators.required]),
secondName: new FormControl('', [Validators.required]),
lastname: new FormControl('', [Validators.required]),
country: new FormControl('', [Validators.required]),
city: new FormControl('', [Validators.required]),
address: new FormControl('', [Validators.required]),
phone: new FormControl('', [Validators.required]),
email: new FormControl('', [Validators.required]),
password: new FormControl('', [Validators.required])
});
constructor(
private activatedRoute: ActivatedRoute,
private fb: FormBuilder,
private passengerService: PassengerService) { }
ngOnInit(): void {
this.activatedRoute.params.subscribe(param => {
if (!param['id']) {
this.buildForm();
return;
}
this.passengerService.getById(param['id'])
.subscribe(passenger => {
this.buildForm(passenger);
});
});
}
buildForm(passenger: Passenger = EMPTY_PASSENGER): void {
this.passengerForm.get('name')?.setValue(passenger.name);
this.passengerForm.get('secondName')?.setValue(passenger.secondName);
this.passengerForm.get('lastname')?.setValue(passenger.lastname);
this.passengerForm.get('country')?.setValue(passenger.country);
this.passengerForm.get('city')?.setValue(passenger.city);
this.passengerForm.get('address')?.setValue(passenger.address);
this.passengerForm.get('phone')?.setValue(passenger.phone);
this.passengerForm.get('email')?.setValue(passenger.email);
this.passengerForm.get('password')?.setValue(passenger.password);
}
onSave():void {
console.log(this.passengerForm.value);
}
}
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Itaque nisi earum libero illo neque, fugiat maiores esse voluptatem quisquam, qui quam iste facilis hic necessitatibus doloribus, excepturi quos cum inventore.</p>
<shared-navigation></shared-navigation>
<shared-mail-box
title="Pasajeros"
icon="bi-people"
message="Este mantenimiento permite gestionar los pasajeros dentro de la agencia">
<shared-table
[tableData]="passengerData"
[tableModel]="passengerModel"
newRouter="new"
editRouter="edit">
</shared-table>
</shared-mail-box>
import { Component } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { Passenger } from '../../interfaces/passenger.interface';
import { TableModel } from 'src/app/shared/interfaces/table-model.interface';
import { PassengerTable } from '../../interfaces/passenger-table.interface';
import { PassengerService } from '../../services/passenger-service.service';
@Component({
selector: 'app-passengers',
templateUrl: './passengers.component.html',
styleUrls: ['./passengers.component.css']
})
export class PassengersComponent {
export class PassengersComponent implements OnInit {
public passengerData: Passenger[] = [];
constructor(private passengerService: PassengerService) {}
ngOnInit(): void {
this.passengerService.getAll()
.subscribe(passengers => this.passengerData = passengers);
}
public passengerModel: TableModel[] = [
{
name: 'id',
title: '#'
},
{
name: 'name',
title: 'Nombres'
},
{
name: 'lastname',
title: 'Apellidos'
},
{
name: 'country',
title: 'Pais'
},
{
name: 'city',
title: 'Ciudad'
}
];
}
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Veniam harum facilis sequi excepturi asperiores labore, aliquam officiis tempore, eveniet illum voluptates fugiat rem ex rerum quaerat hic iure vero. Consectetur.</p>
<shared-navigation></shared-navigation>
<shared-mail-box
title="Reservas"
icon="bi-bookmarks-fill"
message="Este gestor permite realizar reservas de vuelos">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Sunt iste unde, alias fuga animi natus earum consequuntur quasi omnis sint voluptatem, minus ex! Corporis doloremque voluptate eos ullam, neque quae!</p>
</shared-mail-box>
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Passenger } from '../interfaces/passenger.interface';
import { Observable } from 'rxjs';
@Injectable({providedIn: 'root'})
export class PassengerService {
constructor(private http: HttpClient) { }
getAll(): Observable<Passenger[]> {
return this.http.get<Passenger[]>('http://localhost:3000/passengers');
}
getById(id: number): Observable<Passenger> {
return this.http.get<Passenger>(`http://localhost:3000/passengers/${id}`);
}
}
.dialog {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.2);
display: flex;
justify-content: center;
align-items: center;
}
.dialog__content {
background-color: white;
max-width: 600px;
max-height: 90vh;
width: 100%;
height: auto;
border-radius: 5px;
padding: 30px;
}
.dialog__content-title {
display: flex;
align-items: center;
}
.dialog__icon, .dialog__title {
font-size: 24px;
margin-bottom: 0;
margin-right: 5px;
}
.dialog__content-actions {
display: flex;
justify-content: space-between;
}
<div class="dialog" *ngIf="isActivated">
<div class="dialog__content">
<div class="dialog__content-title">
<span class="dialog__icon bi" [ngClass]="icon"></span>
<h3 class="dialog__title">{{ title }}</h3>
</div>
<hr>
<ng-content></ng-content>
</div>
import { Component, EventEmitter, Input } from '@angular/core';
@Component({
selector: 'shared-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.css']
})
export class DialogComponent {
@Input()
public title: string = 'Titulo';
@Input()
public icon: string = 'bi-house-door';
public closeDialog: EventEmitter<void> = new EventEmitter<void>();
public isActivated: boolean = true;
onCloseDialog(): void {
this.closeDialog.emit();
}
}
progress {
height: 20px;
/* border-radius: 0; */
width: 100%;
background-color: blue;
}
.custom-progress span {
font-size: 12px;
}
<div class="d-flex gap-4 mb-2">
<shared-input type="password" class="flex-fill" placeholder="Contraseña *"></shared-input>
<div class="d-flex flex-fill flex-column custom-progress">
<progress class="" value="20" max="100"></progress>
<span>* Ingrese la contraseña</span>
</div>
</div>
import { Component, Input } from '@angular/core';
@Component({
selector: 'shared-input-password',
templateUrl: './input-password.component.html',
styleUrls: ['./input-password.component.css']
})
export class InputPasswordComponent {
}
.text-error {
font-size: 12px;
color: red;
}
.input__lenght {
color: #8f8e8e;
}
.input__lenght-error {
color: red;
}
.input__validator {
color: red;
}
<div [ngClass]="['d-flex', 'text-error', displayStyle]">
<span *ngIf="isValidateField(field)" class="input__validator">{{ getFieldError(field) }}</span>
<span [ngClass]="hasTypeError(field, 'maxlength')? 'input__lenght-error' : 'input__lenght'">{{ formGroup.get(field)?.value?.length }} / {{ getValidatorLength(field).max }}</span>
</div>
import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { max, min } from 'rxjs';
@Component({
selector: 'shared-input-validator',
templateUrl: './input-validator.component.html',
styleUrls: ['./input-validator.component.css']
})
export class InputValidatorComponent {
@Input()
public formGroup: FormGroup = new FormGroup({});
@Input()
public field: string = '';
@Input()
public getValidatorLength: Function = (field: string): {min: string, max: string} => ({min: '', max: ''});
isValidateField(field: string): boolean | null {
return this.formGroup.controls[field]? this.formGroup.controls[field].errors && this.formGroup.controls[field].touched : null;
}
hasTypeError(field: string, type: string): boolean | null {
return this.formGroup.controls[field]? this.formGroup.controls[field].hasError(type) && this.formGroup.controls[field].touched : null;
}
getFieldError(field: string): string | null {
if (!this.formGroup.controls[field]) null;
const errors = this.formGroup.controls[field].errors || {};
for (const key of Object.keys(errors)) {
switch (key) {
case 'required':
return 'Este campo es requerido';
case 'email':
return 'El email no es valido';
case 'minlength':
return `El minimo de caracteres es ${errors[key].requiredLength}`;
case 'maxlength':
return `El maximo de caracteres es ${errors[key].requiredLength}`;
}
}
return null;
}
get displayStyle(): string {
return this.isValidateField(this.field) ? 'justify-content-between' : 'justify-content-end';
}
}
<div class="custom-input">
<input formControlName="name" [type]="type" [value]="value" (keyup)="onChangeInput(myInput)" id="custom-input" required #myInput>
<label for="custom-input">{{ placeholder }}</label>
<p *ngIf="maxLength">{{ myInput.value.length }} / {{ maxLength }}</p>
</div>
import { Component, Input } from '@angular/core';
@Component({
selector: 'shared-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css']
})
export class InputComponent {
@Input()
public placeholder: string = '';
@Input()
public value: string = '';
@Input()
public maxLength?: number;
@Input()
public type: string = 'text';
onChangeInput(input: HTMLInputElement) {
console.log(input.value);
}
}
......@@ -20,7 +20,7 @@
}
.mail-box-content {
padding: 10px 15px;
padding: 10px 20px 8px;
border: 1px solid #e4e5e6;
border-top: 0;
color: #676a6c;
......
......@@ -8,9 +8,9 @@ import { TableComponent } from './components/table/table.component';
import { TableFiltersComponent } from './components/table-filters/table-filters.component';
import { NavigationUserComponent } from './components/navigation-user/navigation-user.component';
import { FooterComponent } from './components/footer/footer.component';
import { InputComponent } from './components/input/input.component';
import { InputPasswordComponent } from './components/input-password/input-password.component';
import { DeleteDialogComponent } from './components/delete-dialog/delete-dialog.component';
import { DialogComponent } from './components/dialog/dialog.component';
import { InputValidatorComponent } from './components/input-validator/input-validator.component';
......@@ -23,9 +23,9 @@ import { DeleteDialogComponent } from './components/delete-dialog/delete-dialog.
TableFiltersComponent,
NavigationUserComponent,
FooterComponent,
InputComponent,
InputPasswordComponent,
DeleteDialogComponent
DeleteDialogComponent,
DialogComponent,
InputValidatorComponent
],
imports: [
CommonModule,
......@@ -38,9 +38,9 @@ import { DeleteDialogComponent } from './components/delete-dialog/delete-dialog.
TableComponent,
NavigationUserComponent,
FooterComponent,
InputComponent,
InputPasswordComponent,
DeleteDialogComponent
DeleteDialogComponent,
DialogComponent,
InputValidatorComponent
]
})
export class SharedModule { }
......@@ -6,3 +6,12 @@ export interface Agent {
email: string,
password: string
}
export const EMPTY_AGENT: Agent = {
id: 0,
name: '',
lastname: '',
detail: '',
email: '',
password: ''
}
.btn-save {
background-color: #18a689;
color: white;
font-size: 12px;
}
.btn-save:disabled {
color: #00000042;
}
/* Input */
/* Forms */
.custom-input {
.field {
position: relative;
padding-top: 12px;
}
.custom-input input {
.field input {
width: 100%;
border: none;
border-bottom: 1px solid #ccc;
......@@ -25,42 +15,83 @@
color: #8f8e8e;
}
.custom-input input:focus {
margin-bottom: -2px;
border-bottom: 2px solid #3f51b5;
.field input:focus {
border-bottom: 1px solid #3f51b5;
}
.custom-input label {
.field label {
position: absolute;
top: 0;
left: 0;
top: 0px;
left: 2px;
pointer-events: none;
transition: 0.2s;
font-size: 14px;
}
.custom-input p {
margin: 0;
font-size: 12px;
text-align: end;
}
.custom-input input:focus + label {
top: -12px;
left: 1px;
.field input:focus + label {
top: 0;
left: 0;
font-size: 12px;
color: #3f51b5;
}
.custom-input input + label {
top: -12px;
left: 1px;
.field input + label {
top: 0;
bottom: 0;
left: 12px;
font-size: 12px;
color: #ccc;
}
.custom-input-detail {
font-size: 12px;
/* Sections */
.general {
margin-top: 12px;
}
.credentials {
margin-top: 20px;
margin-bottom: 16px;
}
.general__title, .credentials__title {
font-size: 14px;
font-weight: 500;
padding-bottom: 8px;
margin-bottom: 16px;
border-bottom: 1px solid #8f8e8e;
}
.general__fields, .credentials__fields {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 16px;
}
.field-name {
grid-column: 1 / 2;
}
.field-lastname {
grid-column: 2 / 3;
}
.field-detail {
grid-column: 1 / 3;
}
/* Actions */
.actions {
display: flex;
justify-content: end;
margin-bottom: 10px;
}
.btn-save {
background-color: #1ab394;
border: #1ab394;
font-size: 14px;
padding: 5px 10px;
border-radius: 4px;
}
......@@ -4,69 +4,51 @@
message="Este mantenimiento permite gestionar los agentes dentro de la agencia"
icon="bi-people"
[btnBack]="true">
<form [formGroup]="myForm" (ngSubmit)="onSave()" autocomplete="off" class="px-3">
<p class="mb-0 mt-2 fw-medium">Información personal</p>
<hr class="mt-0">
<div class="d-flex flex-column gap-3 mt-4">
<div class="custom-input">
<input type="text" formControlName="name" id="custom-input">
<label for="custom-input">Nombre *</label>
<div class="d-flex custom-input-detail" [ngClass]="isValidField('name')? 'justify-content-between' : 'justify-content-end'">
<span *ngIf="isValidField('name')" class="text-danger">{{ getErrorMessage('name') }}</span>
<span>{{ myForm.controls['name'].value.length }} / {{ dataLengths['name'].max }}</span>
<form [formGroup]="agentForm" (ngSubmit)="onSave()" autocomplete="off">
<!-- General information section -->
<section class="general">
<h4 class="general__title">Información general</h4>
<div class="general__fields">
<div class="field field-name">
<label for="name">Nombre *</label>
<input type="text" formControlName="name" id="name">
<shared-input-validator [formGroup]="agentForm" field="name" [getValidatorLength]="getAgentValidatorLenght"></shared-input-validator>
</div>
</div>
<div class="custom-input">
<input type="text" formControlName="lastname" id="custom-input">
<label for="custom-input">Apellidos *</label>
<div class="d-flex custom-input-detail" [ngClass]="isValidField('lastname')? 'justify-content-between' : 'justify-content-end'">
<span *ngIf="isValidField('lastname')" class="text-danger">{{ getErrorMessage('lastname') }}</span>
<span>{{ myForm.controls['lastname'].value.length }} / {{ dataLengths['lastname'].max }}</span>
<div class="field field-lastname">
<label for="lastname">Apellidos *</label>
<input type="text" formControlName="lastname" name="lastname" id="lastname">
<shared-input-validator [formGroup]="agentForm" field="lastname" [getValidatorLength]="getAgentValidatorLenght"></shared-input-validator>
</div>
</div>
<div class="custom-input">
<input type="text" formControlName="detail" id="custom-input">
<label for="custom-input">Detalle *</label>
<div class="d-flex custom-input-detail" [ngClass]="isValidField('detail')? 'justify-content-between' : 'justify-content-end'">
<span *ngIf="isValidField('detail')" class="text-danger">{{ getErrorMessage('detail') }}</span>
<span>{{ myForm.controls['detail'].value.length }} / {{ dataLengths['detail'].max }}</span>
<div class="field field-detail">
<label for="detail">Detalle *</label>
<input type="text" formControlName="detail" name="detail" id="detail">
<shared-input-validator [formGroup]="agentForm" field="detail" [getValidatorLength]="getAgentValidatorLenght"></shared-input-validator>
</div>
</div>
</div>
<p class="mb-0 mt-4 fw-medium">Credenciales</p>
<hr class="mt-0">
<div class="d-flex flex-column gap-3 mt-4">
<div class="custom-input">
<input type="text" formControlName="email" id="custom-input">
<label for="custom-input">Correo *</label>
<div class="d-flex custom-input-detail" [ngClass]="isValidField('email')? 'justify-content-between' : 'justify-content-end'">
<span *ngIf="isValidField('email')" class="text-danger">{{ getErrorMessage('email') }}</span>
<span>{{ myForm.controls['email'].value.length }} / {{ dataLengths['email'].max }}</span>
</section>
<!-- Credentials information section -->
<section class="credentials">
<h4 class="credentials__title">Credenciales</h4>
<div class="credentials__fields">
<div class="field">
<label for="email">Correo *</label>
<input type="text" formControlName="email" name="email" id="email">
<shared-input-validator [formGroup]="agentForm" field="email" [getValidatorLength]="getAgentValidatorLenght"></shared-input-validator>
</div>
</div>
<div class="custom-input">
<input type="password" formControlName="password" id="custom-input">
<label for="custom-input">Contraseña *</label>
<div class="d-flex custom-input-detail" [ngClass]="isValidField('password')? 'justify-content-between' : 'justify-content-end'">
<span *ngIf="isValidField('password')" class="text-danger">{{ getErrorMessage('password') }}</span>
<span>{{ myForm.controls['password'].value.length }} / {{ dataLengths['password'].max }}</span>
<div class="field">
<label for="password">Contraseña *</label>
<input type="password" formControlName="password" name="password" id="password">
<shared-input-validator [formGroup]="agentForm" field="password" [getValidatorLength]="getAgentValidatorLenght"></shared-input-validator>
</div>
</div>
</div>
<hr>
<div class="d-flex justify-content-end mb-2">
<button [disabled]="!myForm.valid" type="submit" class="btn btn-save">
<i class="bi bi-floppy me-1"></i>
</section>
<!-- Actions section -->
<section class="actions">
<button [disabled]="!agentForm.valid" type="submit" class="btn-save">
<i class="bi bi-save me-1"></i>
<span>Guardar</span>
</button>
</div>
</section>
</form>
</shared-mail-box>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { AgentsService } from '../../services/agent.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Agent } from '../../interfaces/agent.interface';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { AGENT_VALIDATORS, getAgentValidatorLenght } from '../../validators/agent.validator';
import { Agent, EMPTY_AGENT } from '../../interfaces/agent.interface';
import { Location } from '@angular/common';
@Component({
......@@ -12,118 +13,49 @@ import { Location } from '@angular/common';
})
export class AgentAddComponent implements OnInit {
public myForm!: FormGroup;
private isNew: boolean = false;
constructor(
private _supervisorService:
AgentsService, private _activatedRoute:
ActivatedRoute, private _router: Router,
private fb: FormBuilder,
private location: Location) {}
private location: Location,
private activatedRouter: ActivatedRoute,
private agentsService: AgentsService) {}
agentForm: FormGroup = AGENT_VALIDATORS;
agentId?: number;
ngOnInit(): void {
this._activatedRoute.params.subscribe(param => {
this.activatedRouter.params.subscribe(param => {
if (param['id']) {
const id: number = param['id'];
const agent = this._supervisorService.getAgentById(id);
if (agent) {
this.buildForm(agent);
} else {
this._router.navigate(['/supervisors']);
}
} else {
this.buildForm();
}
})
this.agentsService.getById(param['id']).subscribe(agent => this.updateValues(agent))
this.agentId = param['id'];
} else this.updateValues(EMPTY_AGENT);
});
}
isValidField(field: string): boolean | undefined {
const fieldForm = this.myForm.get(field);
return fieldForm?.invalid && fieldForm?.touched;
updateValues(agent: Agent): void {
this.agentForm.get('name')?.setValue(agent.name || '');
this.agentForm.get('lastname')?.setValue(agent.lastname || '');
this.agentForm.get('detail')?.setValue(agent.detail || '');
this.agentForm.get('email')?.setValue(agent.email || '');
this.agentForm.get('password')?.setValue(agent.password || '');
}
getErrorMessage(field: string): string | null {
if (!this.myForm.controls[field]) return null;
const errors = this.myForm.controls[field].errors || {};
console.log(errors);
for (const key of Object.keys(errors)) {
switch (key) {
case 'required':
return 'Este campo es requerido';
case 'minlength':
return `Este campo debe tener al menos ${errors[key].requiredLength} caracteres`;
case 'maxlength':
return `Este campo debe tener como máximo ${errors[key].requiredLength} caracteres`;
case 'email':
return 'El email no es válido';
}
}
return null;
getAgentValidatorLenght(controlName: string) {
return getAgentValidatorLenght(controlName);
}
dataLengths = {
name: {
min: 3,
max: 20
},
lastname: {
min: 3,
max: 30
},
detail: {
min: 3,
max: 100
},
email: {
min: 3,
max: 30
},
password: {
min: 3,
max: 30
}
};
buildForm(agent?: Agent):void {
if (agent) {
this.myForm = this.fb.group({
name: [agent.name, [Validators.required, Validators.minLength(3), Validators.maxLength(this.dataLengths['name'].max)]],
lastname: [agent.lastname, [Validators.required, Validators.minLength(3), Validators.maxLength(this.dataLengths['lastname'].max)]],
detail: [agent.detail, [Validators.required, Validators.minLength(3), Validators.maxLength(this.dataLengths['detail'].max)]],
email: [agent.email, [Validators.required, Validators.minLength(3), Validators.maxLength(this.dataLengths['email'].max)]],
password: [agent.password, [Validators.required, Validators.minLength(3), Validators.maxLength(this.dataLengths['password'].max)]]
})
onSave(): void {
if (this.agentId) {
this.agentsService.edit(this.agentId, this.agentForm.value)
.subscribe(() => {
this.agentForm.reset();
this.location.back()
});
} else {
this.myForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(20)]],
lastname: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(30)]],
detail: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(100)]],
email: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(30)]],
password: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(30)]]
this.agentsService.save(this.agentForm.value)
.subscribe(() => {
this.agentForm.reset();
this.location.back()
});
this.isNew = true;
console.log(this.myForm);
}
}
onSave() {
this.myForm.markAllAsTouched();
if (this.myForm.valid) {
if (this.isNew) {
this._supervisorService.saveAgent(this.myForm.value);
} else {
const id: number = this._activatedRoute.snapshot.params['id'];
this._supervisorService.editAgent(id, this.myForm.value);
}
this.myForm.reset({name: '', lastname: '', detail: '', email: '', password: ''});
this.location.back();
}
}
}
......@@ -6,8 +6,8 @@
<shared-table
[tableData]="tableData"
[tableModel]="tableModel"
(onReloadData)="getAgents()"
(onDialogResult)="onDeleteAgent($event)"
(onReloadData)="getAll()"
(onDialogResult)="onDelete($event)"
newRouter="new"
editRouter="edit">
</shared-table>
......
......@@ -35,16 +35,17 @@ export class AgentsComponent implements OnInit {
constructor(private _supervisorService: AgentsService) {}
ngOnInit(): void {
this.getAgents();
this.getAll();
}
getAgents(): void {
this.tableData = this._supervisorService.agents;
getAll(): void {
this._supervisorService.getAll()
.subscribe(agents => this.tableData = agents);
}
onDeleteAgent(result: ResultDelete): void {
onDelete(result: ResultDelete): void {
if (!result.result) return;
this._supervisorService.deleteAgent(result.id);
this.getAgents();
this._supervisorService.delete(result.id)
.subscribe(() => this.getAll());
}
}
......@@ -5,95 +5,27 @@ import { Agent } from '../interfaces/agent.interface';
@Injectable({providedIn: 'root'})
export class AgentsService {
constructor(private httpClient: HttpClient) { }
constructor(private http: HttpClient) { }
private _agents: Agent[] = [
{
id: 1,
name: 'John',
lastname: 'Doe',
detail: 'Detail',
email: 'jodoe@gmail.com',
password: 'password1234'
},
{
id: 2,
name: 'Jane',
lastname: 'Doe',
detail: 'Detail',
email: 'jdoe@gmail.com',
password: 'password1234'
},
{
id: 3,
name: 'John',
lastname: 'Smith',
detail: 'Detail',
email: 'jsmith@gmail.com',
password: 'password1234'
},
{
id: 4,
name: 'Jane',
lastname: 'Smith',
detail: 'Detail',
email: 'jasmith@gmail.com',
password: 'password1234'
},
{
id: 5,
name: 'Jane',
lastname: 'Smith',
detail: 'Detail',
email: 'jasmith@gmail.com',
password: 'password1234'
},
{
id: 6,
name: 'Jane',
lastname: 'Smith',
detail: 'Detail',
email: 'jasmith@gmail.com',
password: 'password1234'
}
];
private BASE_URL: string = 'http://localhost:3000/agents';
get agents() {
return this._agents;
getAll(): Observable<Agent[]> {
return this.http.get<Agent[]>(this.BASE_URL);
}
getAgentById(id: number): Agent | null {
const result = this._agents.filter(agent => agent.id == id);
if (result.length > 0) return result[0];
return null;
getById(id: number): Observable<Agent> {
return this.http.get<Agent>(`${this.BASE_URL}/${id}`);
}
saveAgent(agent: Agent): Agent {
agent.id = this._agents.length + 1;
this._agents = [...this._agents, agent];
return agent;
save(agent: Agent): Observable<Agent> {
return this.http.post<Agent>(this.BASE_URL, agent);
}
editAgent(id: number, agent: Agent): Agent | null {
let edited: boolean = false;
agent.id = id;
// Edit agent
this._agents = this._agents.map(item => {
if (item.id == id) {
edited = true;
return agent;
}
return item;
});
return edited? agent : null;
edit(id: number, agent: Agent): Observable<Agent> {
return this.http.put<Agent>(`${this.BASE_URL}/${id}`, agent);
}
deleteAgent(id: number) {
this._agents = this._agents.filter(agent => agent.id != id);
delete(id: number): Observable<Agent> {
return this.http.delete<Agent>(`${this.BASE_URL}/${id}`);
}
}
import { FormControl, FormGroup, Validators } from "@angular/forms";
const nameLenght = { min: 3, max: 20 };
const lastnameLenght = { min: 3, max: 30 };
const detailLenght = { min: 3, max: 100 };
const emailLenght = { min: 3, max: 100 };
const passwordLenght = { min: 3, max: 45 };
export const AGENT_VALIDATORS = new FormGroup( {
name: new FormControl('', [Validators.required, Validators.minLength(nameLenght.min), Validators.maxLength(nameLenght.max)]),
lastname: new FormControl('', [Validators.required, Validators.minLength(lastnameLenght.min), Validators.maxLength(lastnameLenght.max)]),
detail: new FormControl('', [Validators.maxLength(detailLenght.max)]),
email: new FormControl('', [Validators.required, Validators.minLength(emailLenght.min), Validators.maxLength(emailLenght.max)]),
password: new FormControl('', [Validators.required, Validators.minLength(passwordLenght.min), Validators.maxLength(passwordLenght.max)])
});
export const getAgentValidatorLenght = (field: string) => {
switch (field) {
case 'name':
return nameLenght;
case 'lastname':
return lastnameLenght;
case 'detail':
return detailLenght;
case 'email':
return emailLenght;
case 'password':
return passwordLenght;
default:
return { min: 0, max: 0 };
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment