Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

33 edit room #57

Merged
merged 9 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/app/app-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { VisitStatusComponent } from './visit/visit-status/visit-status.componen
import { VisitCancelComponent } from './visit/visit-cancel/visit-cancel.component';
import { RoomListComponent } from './room/room-list/room-list.component';
import { RoomCreateComponent } from './room/room-create/room-create.component';
import { RoomDeleteComponent } from './room/room-delete/room-delete.component';
import { RoomUpdateComponent } from './room/room-update/room-update.component';
import { MyAdvertisementComponent } from './advertisement/my-advertisement-list/my-advertisement.component';
import { ImageCreateComponent } from './image/image-create/image.component';

Expand All @@ -43,9 +43,9 @@ const routes: Routes = [
{ path: 'visit/:id/cancel', component:VisitCancelComponent},
{ path: 'rooms', component: RoomListComponent},
{ path: 'room/create', component: RoomCreateComponent},
{ path: 'room/:id/delete', component: RoomDeleteComponent},
{ path: 'room/update/:id', component: RoomUpdateComponent},
{ path: '404', component: NotFoundComponent},
{ path: '', redirectTo: 'about', pathMatch: 'full'}
{ path: '', redirectTo: 'about', pathMatch: 'full'},
];

@NgModule({
Expand Down
4 changes: 3 additions & 1 deletion src/app/room/room-list/room-list.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ <h4 class="mb-1">List of Rooms</h4>
<td>{{ room.isOccupied }}</td>
<td>{{ room.surface}}</td>
<td><button class="deleteButton" (click)="deleteRoom(room.getRoomIdFromLinks())"><span class="deleteSpan">Delete</span></button></td>
<td><button class="updateButton" (click)="updateRoom(room.getRoomIdFromLinks())"><span class="updateSpan">Edit</span></button></td>

</tr>
</tbody>
</table>
Expand All @@ -32,4 +34,4 @@ <h4 class="mb-1">List of Rooms</h4>
<div *ngIf="rooms.length === 0" class="alert alert-info" role="alert">
No rooms available for this apartment.
</div>
</div>
</div>
8 changes: 8 additions & 0 deletions src/app/room/room-list/room-list.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,12 @@ export class RoomListComponent implements OnInit {
console.error('Invalid room ID');
}
}
updateRoom(roomId: string): void {
if (roomId) {
console.log('Room ID:', roomId);
this.router.navigate([`/room/update/${roomId}`]);
} else {
console.error('Invalid room ID');
}
}
}
Empty file.
51 changes: 51 additions & 0 deletions src/app/room/room-update/room-update.component.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<div *ngIf="isAuthorized" class="container mt-5 w-50 p-3">
<h1 class="mb-4">Update Room</h1>

<div *ngIf="isLoading" class="d-flex justify-content-center align-items-center">
<div class="spinner-border" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>

<div *ngIf="!isLoading && errorFetchMsg" class="alert alert-danger" role="alert">
{{ errorFetchMsg }}
</div>

<form *ngIf="!isLoading && !errorFetchMsg" (ngSubmit)="onSubmit()" [formGroup]="roomForm">
<div class="mb-3">
<label for="surface" class="form-label">Surface</label>
<input type="number" formControlName="surface" class="form-control" id="surface" required>
<div *ngIf="roomForm.get('surface')?.invalid && roomForm.get('surface')?.touched" class="text-danger">
Surface is required and must be at least 0.
</div>
</div>

<div class="mb-3 form-check">
<input type="checkbox" formControlName="isOccupied" class="form-check-input" id="isOccupied">
<label class="form-check-label" for="isOccupied">Is Occupied</label>
</div>

<div class="mb-3 form-check">
<input type="checkbox" formControlName="hasWindow" class="form-check-input" id="hasWindow">
<label class="form-check-label" for="hasWindow">Has Window</label>
</div>

<div class="mb-3 form-check">
<input type="checkbox" formControlName="hasDesk" class="form-check-input" id="hasDesk">
<label class="form-check-label" for="hasDesk">Has Desk</label>
</div>

<div class="mb-3 form-check">
<input type="checkbox" formControlName="hasBed" class="form-check-input" id="hasBed">
<label class="form-check-label" for="hasBed">Has Bed</label>
</div>
<button type="submit" class="btn btn-primary mt-3">Submit</button>
<button type="button" (click)="onCancel()" class="btn btn-danger mt-3 ms-2">Cancel</button>
</form>
</div>

<div *ngIf="!isAuthorized" class="container mt-5 w-50 p-3">
<div class="alert alert-danger" role="alert">
You are not authorized to update this room.
</div>
</div>
23 changes: 23 additions & 0 deletions src/app/room/room-update/room-update.component.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { RoomUpdateComponent } from './room-update.component';

describe('RoomUpdateComponent', () => {
let component: RoomUpdateComponent;
let fixture: ComponentFixture<RoomUpdateComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [RoomUpdateComponent]
})
.compileComponents();

fixture = TestBed.createComponent(RoomUpdateComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
125 changes: 125 additions & 0 deletions src/app/room/room-update/room-update.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { Component, OnInit } from '@angular/core';
import {
FormBuilder,
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { RoomService } from '../room.service';
import { Room } from '../room';
import { AuthenticationBasicService } from '../../login-basic/authentication-basic.service';
import { ErrorMessageService } from '../../error-handler/error-message.service';
import { CommonModule } from '@angular/common';
import { Apartment } from '../../apartment/apartment';

@Component({
selector: 'app-room-update',
standalone: true,
imports: [FormsModule, CommonModule, ReactiveFormsModule],
templateUrl: './room-update.component.html',
styleUrls: ['./room-update.component.css']
})
export class RoomUpdateComponent implements OnInit {
public room: Room = new Room();
public roomForm: FormGroup = new FormGroup({});
public errorFetchMsg: string = '';
public roomId: string = '';
public isLoading: boolean = false;
public isAuthorized: boolean = false;

constructor(
private formBuilder: FormBuilder,
private roomService: RoomService,
private router: Router,
private activatedRoute: ActivatedRoute,
private errorMessageService: ErrorMessageService,
private authenticationService: AuthenticationBasicService,
) {}

ngOnInit(): void {
this.isLoading = true;
this.roomId = this.activatedRoute.snapshot.paramMap.get('id') || '';

// Configuración inicial del formulario
this.roomForm = this.formBuilder.group({
surface: new FormControl('', { validators: [Validators.required, Validators.min(0)] }),
isOccupied: new FormControl(false),
hasWindow: new FormControl(false),
hasDesk: new FormControl(false),
hasBed: new FormControl(false),
});

// Cargar la habitación desde el servicio
this.roomService
.findById(this.roomId)
.subscribe(
(_room) => {
this.room = _room;
this.room.getRelation<Apartment>('apart').subscribe(
(apartment) => this.room.apart = apartment);
this.setUpForm();
this.isAuthorized = this.isAuthorised();
if (!this.isAuthorized) {
this.onUnauthorised();
}
this.isLoading = false;
},
(error) => {
this.errorFetchMsg = error.message;
this.isLoading = false;
}
);
}

setUpForm(): void {
this.roomForm.setValue({
surface: this.room.surface || 0,
isOccupied: this.room.isOccupied || false,
hasWindow: this.room.hasWindow || false,
hasDesk: this.room.hasDesk || false,
hasBed: this.room.hasBed || false,
});
}

private isAuthorised(): boolean {
const userRoles = this.authenticationService.getCurrentUser()?.getRoles() || [];
return userRoles.includes('admin') || userRoles.includes('owner');
}

onSubmit(): void {
if (!this.isAuthorized) {
this.onUnauthorised();
return;
}
if (this.roomForm.invalid) {
this.errorMessageService.showErrorMessage('Invalid form');
return;
}

// Obtener los valores del formulario, excluyendo los campos deshabilitados
const updatedRoomData = this.roomForm.getRawValue();
delete updatedRoomData.apartName; // Excluir el nombre del apartamento

// Asignar los valores actualizados al objeto `room`
Object.assign(this.room, updatedRoomData);

this.roomService.updateResource(this.room).subscribe(
() => this.router.navigate(['/rooms']),
() => {
this.errorMessageService.showErrorMessage('Failed to update room');
}
);
}

onUnauthorised(): void {
this.errorMessageService.showErrorMessage('You are not authorized to update this room.');
this.router.navigate(['/rooms']);
}

onCancel(): void {
this.router.navigate(['/rooms']);
}
}
1 change: 0 additions & 1 deletion src/app/room/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ export class Room extends Resource {
Object.assign(this, values);
}


getRoomIdFromLinks(): string {
if (this._links?.self?.href) {
return this._links.self.href.split('/').pop() || ''; // Último segmento
Expand Down
Loading