Files
smartguide/webapp/src/app/modules/accounts/accounts.component.ts
T

332 lines
9.4 KiB
TypeScript

import { CommonModule } from '@angular/common';
import {
Component,
OnInit,
TemplateRef,
computed,
inject,
input,
viewChild,
} from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { CredentialService } from '../../shared/services/credential.service';
import type {
AccountDialogComponent,
AccountDialogResult,
} from './account-dialog.component';
import { RolePipe } from '../../shared/pipes/role.pipe';
import {
GenericColumn,
DataTableComponent,
} from '../../shared/ui/data-table/data-table.component';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
import {
QueryParamSelectorComponent,
SelectorOption,
} from '../../shared/ui/query-param-selector/query-param-selector.component';
import { MatCardModule } from '@angular/material/card';
import {
AccountPage,
AccountProfile,
AuthService,
InseAccountManagementModelOrganizationProfile,
UserRole,
} from '../../api';
import { StatusPipe } from '../../shared/pipes/status.pipe';
@Component({
selector: 'app-accounts',
imports: [
CommonModule,
ReactiveFormsModule,
MatButtonModule,
MatIconModule,
MatFormFieldModule,
MatInputModule,
MatSelectModule,
MatSnackBarModule,
MatTooltipModule,
MatDialogModule,
RolePipe,
DataTableComponent,
QueryParamPaginatorComponent,
QueryParamInputComponent,
QueryParamSelectorComponent,
MatCardModule,
StatusPipe,
],
templateUrl: './accounts.component.html',
styleUrl: './accounts.component.scss',
standalone: true,
})
export class AccountsComponent implements OnInit {
protected readonly credentialService = inject(CredentialService);
private readonly snackBar = inject(MatSnackBar);
private readonly router = inject(Router);
private readonly dialog = inject(MatDialog);
private readonly authService = inject(AuthService);
protected get isReadOnly(): boolean {
return this.credentialService.isEffectiveManager();
}
accountColumns: GenericColumn<AccountProfile>[] = [];
accountRoleTmp = viewChild.required<TemplateRef<any>>('accountRoleTmp');
accountStatusTmp = viewChild.required<TemplateRef<any>>('accountStatusTmp');
accountActionsTmp = viewChild.required<TemplateRef<any>>('accountActionsTmp');
availableRoles = computed<UserRole[]>(() => {
if (this.credentialService.isEffectiveSuperAdmin()) {
return ['SUPER_ADMIN', 'ADMIN', 'MANAGER', 'USER'];
}
return ['MANAGER', 'USER'];
});
selectorOptions = computed<SelectorOption[]>(() => {
return this.organizations().map((org) => ({
value: org.id,
display_name: org.name,
}));
});
accountPage = input.required<AccountPage>();
organizations =
input.required<InseAccountManagementModelOrganizationProfile[]>();
ngOnInit(): void {
this.accountColumns = [
{
id: 'name',
header: 'Name',
type: 'accessor',
accessorKey: 'name',
},
{
id: 'email',
header: 'E-Mail',
type: 'accessor',
accessorKey: 'email',
},
{
id: 'organization_name',
header: 'Organisation',
type: 'accessor',
accessorKey: 'organization_name',
},
{
id: 'role',
header: 'Rolle',
type: 'accessor',
accessorKey: 'role',
cellTemplate: this.accountRoleTmp(),
},
{
id: 'status',
header: 'Status',
type: 'display',
cellTemplate: this.accountStatusTmp(),
},
{
id: 'actions',
header: 'Aktionen',
type: 'display',
cellTemplate: this.accountActionsTmp(),
},
];
}
protected startCreate(): void {
this.openAccountDialog({ mode: 'create' });
}
protected startEdit(account: AccountProfile): void {
this.openAccountDialog({ mode: 'edit', account });
}
private saveDialogResult(result: AccountDialogResult): void {
const request =
result.mode === 'create'
? this.authService.createAccount(result.payload)
: this.authService.updateAccount(result.accountId, result.payload);
request.subscribe({
next: () => {
this.snackBar.open('Account wurde gespeichert.', 'OK', {
duration: 3000,
});
this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
},
error: (error) => {
const message =
error.status === 409
? 'Diese E-Mail-Adresse wird bereits verwendet.'
: 'Account konnte nicht gespeichert werden.';
this.snackBar.open(message, 'OK', { duration: 5000 });
},
});
}
private openAccountDialog(data: {
mode: 'create' | 'edit';
account?: AccountProfile;
}): void {
import('./account-dialog.component').then(({ AccountDialogComponent }) => {
const dialogRef = this.dialog.open<
AccountDialogComponent,
{
mode: 'create' | 'edit';
account?: AccountProfile;
organizations: InseAccountManagementModelOrganizationProfile[];
canSelectOrganization: boolean;
roles: UserRole[];
},
AccountDialogResult | undefined
>(AccountDialogComponent, {
width: '760px',
maxWidth: 'calc(100vw - 32px)',
data: {
...data,
organizations: this.organizations(),
canSelectOrganization: this.credentialService.isEffectiveSuperAdmin(),
roles: this.availableRoles(),
},
});
dialogRef.afterClosed().subscribe((result) => {
if (result) {
this.saveDialogResult(result);
}
});
});
}
protected deleteAccount(account: AccountProfile): void {
if (account.is_current) {
return;
}
this.authService.deleteAccount(account.id).subscribe({
next: () => {
this.snackBar.open('Account wurde deaktiviert.', 'OK', {
duration: 3000,
});
this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
},
error: () => {
this.snackBar.open('Account konnte nicht deaktiviert werden.', 'OK', {
duration: 5000,
});
},
});
}
protected toggleAccountActivation(account: AccountProfile): void {
if (
!this.credentialService.isEffectiveSuperAdmin() ||
account.is_current ||
account.deleted
) {
return;
}
const activated = !account.activated;
const action = activated ? 'aktivieren' : 'deaktivieren';
import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then(
({ ConfirmationDialogComponent }) => {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
data: {
title: activated ? 'Account aktivieren' : 'Account deaktivieren',
message: `Möchtest Du den Account „${account.name}“ wirklich ${action}?`,
confirmText: activated ? 'Aktivieren' : 'Deaktivieren',
cancelText: 'Abbrechen',
},
});
dialogRef.componentInstance.confirmDelete.subscribe(() => {
this.updateAccountActivation(account, activated);
});
},
);
}
private updateAccountActivation(
account: AccountProfile,
activated: boolean,
): void {
this.authService.updateAccount(account.id, { activated }).subscribe({
next: () => {
this.snackBar.open(
activated ? 'Account wurde aktiviert.' : 'Account wurde deaktiviert.',
'OK',
{ duration: 3000 },
);
this.router.navigate([], {
queryParams: { page: 0 },
queryParamsHandling: 'merge',
});
},
error: () => {
this.snackBar.open(
'Account-Status konnte nicht geändert werden.',
'OK',
{ duration: 5000 },
);
},
});
}
protected async impersonate(account: AccountProfile): Promise<void> {
if (!this.canImpersonate(account)) {
return;
}
try {
await this.credentialService.impersonateAccount(account.id);
this.snackBar.open(`Impersonation aktiv: ${account.name}`, 'OK', {
duration: 4000,
});
this.router.navigate(['/dashboard']);
} catch (error) {
console.error('Impersonation failed:', error);
this.snackBar.open('Impersonation konnte nicht gestartet werden.', 'OK', {
duration: 5000,
});
return;
}
}
protected canImpersonate(account: AccountProfile): boolean {
if (account.is_current || account.deleted || !account.activated) {
return false;
}
if (this.credentialService.isEffectiveSuperAdmin()) {
return true;
}
return (
this.credentialService.isEffectiveAdmin() &&
(account.role === 'MANAGER' || account.role === 'USER')
);
}
}