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

NAS-132298 / 25.04 / Add Delete and Edit actions for virtualization instances #10996

Merged
merged 6 commits into from
Nov 9, 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
2 changes: 1 addition & 1 deletion src/app/interfaces/api/api-job-directory.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ export interface ApiJobDirectory {

// Virt
'virt.instance.create': { params: [CreateVirtualizationInstance]; response: VirtualizationInstance };
'virt.instance.delete ': { params: [instanceId: string]; response: boolean };
'virt.instance.delete': { params: [instanceId: string]; response: boolean };
'virt.instance.restart': { params: VirtualizationStopParams; response: boolean };
'virt.instance.start': { params: [instanceId: string]; response: boolean };
'virt.instance.stop': { params: VirtualizationStopParams; response: boolean };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@
<h3 mat-card-title>
{{ 'General Info' | translate }}
</h3>

<button
mat-button
ixTest="edit-instance"
(click)="editInstance()"
>
{{ 'Edit' | translate }}
</button>
</mat-card-header>

<mat-card-content>
Expand All @@ -15,5 +23,16 @@ <h3 mat-card-title>
<p>{{ 'Memory' | translate }}: {{ formatter.memorySizeFormatting(instance.memory) || '-' }}</p>
}
</mat-card-content>

<mat-card-actions>
<button
*ixRequiresRoles="[Role.VirtInstanceWrite]"
mat-button
ixTest="delete-instance"
(click)="deleteInstance()"
>
{{ 'Delete' | translate }}
</button>
</mat-card-actions>
</mat-card>

Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import { createComponentFactory, Spectator } from '@ngneat/spectator/jest';
import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatButtonHarness } from '@angular/material/button/testing';
import { createComponentFactory, mockProvider, Spectator } from '@ngneat/spectator/jest';
import { of } from 'rxjs';
import { mockAuth } from 'app/core/testing/utils/mock-auth.utils';
import { mockJob, mockWebSocket } from 'app/core/testing/utils/mock-websocket.utils';
import { VirtualizationInstance } from 'app/interfaces/virtualization.interface';
import { DialogService } from 'app/modules/dialog/dialog.service';
import { InstanceGeneralInfoComponent } from 'app/pages/virtualization/components/all-instances/instance-details/instance-general-info/instance-general-info.component';
import { InstanceEditFormComponent } from 'app/pages/virtualization/components/instance-edit-form/instance-edit-form.component';
import { VirtualizationInstancesStore } from 'app/pages/virtualization/stores/virtualization-instances.store';
import { SlideInService } from 'app/services/slide-in.service';
import { WebSocketService } from 'app/services/ws.service';

const demoInstance = {
id: 'demo',
Expand All @@ -20,9 +31,30 @@ const demoInstance = {

describe('InstanceGeneralInfoComponent', () => {
let spectator: Spectator<InstanceGeneralInfoComponent>;
let loader: HarnessLoader;

const createComponent = createComponentFactory({
component: InstanceGeneralInfoComponent,
providers: [
mockAuth(),
mockProvider(DialogService, {
jobDialog: jest.fn(() => {
return {
afterClosed: jest.fn(() => of()),
};
}),
confirm: () => of(true),
}),
mockProvider(SlideInService, {
open: jest.fn(),
}),
mockWebSocket([
mockJob('virt.instance.delete'),
]),
mockProvider(VirtualizationInstancesStore, {
selectedInstance: jest.fn(),
}),
],
});

beforeEach(() => {
Expand All @@ -31,6 +63,8 @@ describe('InstanceGeneralInfoComponent', () => {
instance: demoInstance,
},
});

loader = TestbedHarnessEnvironment.loader(spectator.fixture);
});

it('checks card title', () => {
Expand All @@ -48,4 +82,21 @@ describe('InstanceGeneralInfoComponent', () => {
expect(chartExtra[4]).toHaveText('CPU: 525');
expect(chartExtra[5]).toHaveText('Memory: 125 MiB');
});

it('deletes instance when "Delete" button is pressed', async () => {
const deleteButton = await loader.getHarness(MatButtonHarness.with({ text: 'Delete' }));
await deleteButton.click();

expect(spectator.inject(DialogService).jobDialog).toHaveBeenCalled();
expect(spectator.inject(WebSocketService).job).toHaveBeenLastCalledWith('virt.instance.delete', ['demo']);
});

it('navigates to app edit page when Edit button is pressed', async () => {
const editButton = await loader.getHarness(MatButtonHarness.with({ text: 'Edit' }));
await editButton.click();

expect(spectator.inject(SlideInService).open).toHaveBeenCalledWith(InstanceEditFormComponent, {
data: demoInstance,
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,26 @@ import { TitleCasePipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
import { MatButton } from '@angular/material/button';
import {
MatCard, MatCardContent, MatCardHeader,
MatCard, MatCardActions, MatCardContent, MatCardHeader,
MatCardTitle,
} from '@angular/material/card';
import { TranslateModule } from '@ngx-translate/core';
import { Router, RouterLink } from '@angular/router';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { filter, switchMap } from 'rxjs';
import { RequiresRolesDirective } from 'app/directives/requires-roles/requires-roles.directive';
import { Role } from 'app/enums/role.enum';
import { VirtualizationInstance } from 'app/interfaces/virtualization.interface';
import { DialogService } from 'app/modules/dialog/dialog.service';
import { IxFormatterService } from 'app/modules/forms/ix-forms/services/ix-formatter.service';
import { YesNoPipe } from 'app/modules/pipes/yes-no/yes-no.pipe';
import { InstanceEditFormComponent } from 'app/pages/virtualization/components/instance-edit-form/instance-edit-form.component';
import { VirtualizationInstancesStore } from 'app/pages/virtualization/stores/virtualization-instances.store';
import { ErrorHandlerService } from 'app/services/error-handler.service';
import { SlideInService } from 'app/services/slide-in.service';
import { WebSocketService } from 'app/services/ws.service';

@UntilDestroy()
@Component({
selector: 'ix-instance-general-info',
templateUrl: './instance-general-info.component.html',
Expand All @@ -21,16 +33,51 @@ import { YesNoPipe } from 'app/modules/pipes/yes-no/yes-no.pipe';
MatCard,
MatCardTitle,
MatCardHeader,
MatCardActions,
TranslateModule,
MatCardContent,
YesNoPipe,
TitleCasePipe,
RouterLink,
RequiresRolesDirective,
],
})
export class InstanceGeneralInfoComponent {
instance = input.required<VirtualizationInstance>();

protected readonly Role = Role;

constructor(
protected formatter: IxFormatterService,
private dialogService: DialogService,
private translate: TranslateService,
private ws: WebSocketService,
private errorHandler: ErrorHandlerService,
private router: Router,
private slideInService: SlideInService,
private instancesStore: VirtualizationInstancesStore,
) {}

editInstance(): void {
this.slideInService.open(InstanceEditFormComponent, { data: this.instance() });
}

deleteInstance(): void {
this.dialogService.confirm({
title: this.translate.instant('Delete'),
message: this.translate.instant('Delete {name}?', { name: this.instance().name }),
}).pipe(
filter(Boolean),
switchMap(() => {
return this.dialogService.jobDialog(
this.ws.job('virt.instance.delete', [this.instance().id]),
).afterClosed();
}),
this.errorHandler.catchError(),
untilDestroyed(this),
).subscribe(() => {
this.instancesStore.selectInstance(null);
this.router.navigate(['/virtualization'], { state: { hideMobileDetails: true } });
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@
} @else {
<ix-empty [conf]="emptyConfig()"></ix-empty>
}

@for (instance of filteredInstances(); track instance.id) {
<ix-instance-row
[instance]="instance"
[class.selected]="selectedInstance()?.id === instance.id"
[selected]="selection.isSelected(instance.id)"
(click)="viewDetails(instance)"
(keydown.enter)="viewDetails(instance)"
(click)="navigateToDetails(instance)"
(keydown.enter)="navigateToDetails(instance)"
(onStart)="start(instance.id)"
(onStop)="stop(instance.id)"
(onRestart)="restart(instance.id)"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { SelectionModel } from '@angular/cdk/collections';
import {
Component, ChangeDetectionStrategy,
signal, computed, inject, AfterViewInit,
signal, computed, inject,
effect,
} from '@angular/core';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { ActivatedRoute, Router } from '@angular/router';
Expand Down Expand Up @@ -40,7 +41,7 @@ import { WebSocketService } from 'app/services/ws.service';
],
})

export class InstanceListComponent implements AfterViewInit {
export class InstanceListComponent {
protected readonly requireRoles = [Role.VirtInstanceWrite];
protected readonly searchQuery = signal<string>('');
protected readonly showMobileDetails = signal<boolean>(false);
Expand Down Expand Up @@ -81,6 +82,20 @@ export class InstanceListComponent implements AfterViewInit {
};
});

protected selectInstanceDetails = effect(() => {
const instanceId = this.activatedRoute.snapshot.paramMap.get('id');

if (this.isLoading() || !this.instances()?.length) {
return;
}

if (instanceId) {
this.selectForDetails(instanceId);
} else {
this.navigateToDetails(this.instances()[0]);
}
}, { allowSignalWrites: true });

constructor(
private store: VirtualizationInstancesStore,
private router: Router,
Expand All @@ -91,14 +106,6 @@ export class InstanceListComponent implements AfterViewInit {
private errorHandler: ErrorHandlerService,
) {}

ngAfterViewInit(): void {
this.activatedRoute.paramMap.pipe(
untilDestroyed(this),
).subscribe((params) => {
this.selectForDetails(params.get('id'));
});
}

onSearch(query: string): void {
this.searchQuery.set(query);
}
Expand All @@ -111,7 +118,7 @@ export class InstanceListComponent implements AfterViewInit {
}
}

viewDetails(instance: VirtualizationInstance): void {
navigateToDetails(instance: VirtualizationInstance): void {
this.selectForDetails(instance.id);

this.router.navigate(['/virtualization', 'view', instance.id]);
Expand All @@ -123,28 +130,6 @@ export class InstanceListComponent implements AfterViewInit {
}
}

private selectForDetails(instanceId: string): void {
if (!this.instances()?.length) {
return;
}

const selected = instanceId && this.instances().find((instance) => instance.id === instanceId);
if (selected) {
this.store.selectInstance(selected.id);
return;
}

this.selectFirstInstance();
}

private selectFirstInstance(): void {
const [first] = this.instances();

if (first) {
this.store.selectInstance(first.id);
}
}

closeMobileDetails(): void {
this.showMobileDetails.set(false);
}
Expand Down Expand Up @@ -178,4 +163,15 @@ export class InstanceListComponent implements AfterViewInit {
.pipe(this.errorHandler.catchError(), untilDestroyed(this))
.subscribe();
}

private selectForDetails(instanceId: string): void {
if (!this.instances()?.length) {
return;
}

const selected = instanceId && this.instances().find((instance) => instance.id === instanceId);
if (selected) {
this.store.selectInstance(selected.id);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<ix-modal-header [requiredRoles]="requiredRoles" [title]="title" [loading]="isLoading()"></ix-modal-header>

<div class="container">
<form class="form" [formGroup]="form" (submit)="onSubmit()">
<ix-fieldset [title]="'Instance Configuration' | translate">
<ix-checkbox
formControlName="autostart"
[label]="'Autostart' | translate"
></ix-checkbox>
</ix-fieldset>

<ix-fieldset [title]="'CPU & Memory' | translate">
<ix-input
formControlName="cpu"
[required]="true"
[label]="'CPU Configuration' | translate"
></ix-input>

<ix-input
formControlName="memory"
[required]="true"
[label]="'Memory Size' | translate"
[format]="formatter.memorySizeFormatting"
[parse]="formatter.memorySizeParsing"
></ix-input>
</ix-fieldset>

<div class="actions">
<button
mat-button
type="submit"
color="primary"
ixTest="save"
[disabled]="form.invalid || isLoading()"
>
{{ 'Save' | translate }}
</button>
</div>
</form>
</div>
Loading
Loading