implement organisation management #175
@@ -36,7 +36,10 @@ class Organization(Durable, table=True):
|
||||
description="Unique identifier for the organization. Generated automatically if not provided.",
|
||||
)
|
||||
name: str = Field(
|
||||
index=True, nullable=False, description="The name of the organization."
|
||||
index=True,
|
||||
unique=True,
|
||||
nullable=False,
|
||||
description="The unique name of the organization.",
|
||||
)
|
||||
openalex_institution_id: str | None = Field(
|
||||
default=None,
|
||||
|
||||
@@ -43,7 +43,7 @@ def in_memory_session():
|
||||
def create_org_and_account(
|
||||
session: Session, email: str, password: str, role=UserRole.USER
|
||||
):
|
||||
org = Organization(name="Test Org")
|
||||
org = Organization(name=f"Test Org {email}")
|
||||
session.add(org)
|
||||
session.flush()
|
||||
assert org.id is not None
|
||||
|
||||
@@ -30,6 +30,7 @@ from inse.patents.service import router as patents_service_router
|
||||
|
||||
from inse.auth.router import router as auth_router
|
||||
from inse.account_management.router import router as account_management_router
|
||||
from inse.organization_management.router import router as organization_management_router
|
||||
|
||||
|
||||
from inse.institutions.router import router as institutions_router
|
||||
@@ -80,6 +81,7 @@ app.include_router(service_router)
|
||||
|
||||
app.include_router(auth_router)
|
||||
app.include_router(account_management_router)
|
||||
app.include_router(organization_management_router)
|
||||
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Organization management API."""
|
||||
@@ -0,0 +1,30 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class OrganizationProfile(BaseModel):
|
||||
id: uuid.UUID
|
||||
name: str
|
||||
other_inst_id: Optional[str] = None
|
||||
deleted: bool
|
||||
member_count: int
|
||||
|
||||
|
||||
class OrganizationPage(BaseModel):
|
||||
items: List[OrganizationProfile]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
|
||||
|
||||
class CreateOrganizationRequest(BaseModel):
|
||||
name: str = Field(min_length=1)
|
||||
other_inst_id: Optional[str] = None
|
||||
|
||||
|
||||
class UpdateOrganizationRequest(BaseModel):
|
||||
name: Optional[str] = Field(default=None, min_length=1)
|
||||
other_inst_id: Optional[str] = None
|
||||
deleted: Optional[bool] = None
|
||||
@@ -0,0 +1,81 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Response, status
|
||||
from sqlmodel import Session
|
||||
|
||||
from inse.auth import service as auth_service
|
||||
from inse.auth.model import AccessToken
|
||||
from inse.database import get_session
|
||||
from inse.tags import Tags
|
||||
|
||||
from . import service
|
||||
from .model import (
|
||||
CreateOrganizationRequest,
|
||||
OrganizationPage,
|
||||
OrganizationProfile,
|
||||
UpdateOrganizationRequest,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/organizations", tags=[Tags.ORGANIZATION])
|
||||
|
||||
|
||||
@router.get("", operation_id="getOrganisations", response_model=OrganizationPage)
|
||||
async def get_organizations(
|
||||
page: int = Query(default=0, ge=0),
|
||||
page_size: int = Query(default=25, ge=1, le=100),
|
||||
offset: Optional[int] = Query(default=None, ge=0),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> OrganizationPage:
|
||||
return service.get_organizations(
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
offset=offset,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
operation_id="createOrganisation",
|
||||
response_model=OrganizationProfile,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
async def create_organization(
|
||||
payload: CreateOrganizationRequest,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> OrganizationProfile:
|
||||
return service.create_organization(session, access_token, payload)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/{organization_id}",
|
||||
operation_id="updateOrganisation",
|
||||
response_model=OrganizationProfile,
|
||||
)
|
||||
async def update_organization(
|
||||
organization_id: uuid.UUID,
|
||||
payload: UpdateOrganizationRequest,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> OrganizationProfile:
|
||||
return service.update_organization(
|
||||
session, access_token, organization_id, payload
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{organization_id}",
|
||||
operation_id="deleteOrganisation",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
)
|
||||
async def delete_organization(
|
||||
organization_id: uuid.UUID,
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> Response:
|
||||
service.delete_organization(session, access_token, organization_id)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,183 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import Session, func, select
|
||||
|
||||
from inse.auth.model import AccessToken, Account, Organization, UserRole
|
||||
|
||||
from .model import (
|
||||
CreateOrganizationRequest,
|
||||
OrganizationPage,
|
||||
OrganizationProfile,
|
||||
UpdateOrganizationRequest,
|
||||
)
|
||||
|
||||
|
||||
def _require_super_admin(access_token: AccessToken) -> None:
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only superadmins can manage organizations.",
|
||||
)
|
||||
|
||||
|
||||
def _normalize_name(name: str) -> str:
|
||||
normalized_name = name.strip()
|
||||
if not normalized_name:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Organization name must not be empty.",
|
||||
)
|
||||
return normalized_name
|
||||
|
||||
|
||||
def _ensure_name_available(
|
||||
session: Session,
|
||||
name: str,
|
||||
excluded_organization_id: Optional[uuid.UUID] = None,
|
||||
) -> None:
|
||||
statement = select(Organization).where(
|
||||
func.lower(Organization.name) == name.lower()
|
||||
)
|
||||
if excluded_organization_id is not None:
|
||||
statement = statement.where(Organization.id != excluded_organization_id)
|
||||
|
||||
if session.exec(statement).first() is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="An organization with this name already exists.",
|
||||
)
|
||||
|
||||
|
||||
def _get_organization_or_404(
|
||||
session: Session, organization_id: uuid.UUID
|
||||
) -> Organization:
|
||||
organization = session.get(Organization, organization_id)
|
||||
if organization is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Organization not found.",
|
||||
)
|
||||
return organization
|
||||
|
||||
|
||||
def _member_counts(
|
||||
session: Session, organization_ids: list[uuid.UUID]
|
||||
) -> dict[uuid.UUID, int]:
|
||||
if not organization_ids:
|
||||
return {}
|
||||
|
||||
rows = session.exec(
|
||||
select(Account.organization_id, func.count(Account.id))
|
||||
.where(
|
||||
Account.organization_id.in_(organization_ids),
|
||||
Account.deleted == False, # noqa: E712
|
||||
)
|
||||
.group_by(Account.organization_id)
|
||||
).all()
|
||||
return {organization_id: count for organization_id, count in rows}
|
||||
|
||||
|
||||
def _to_profile(
|
||||
organization: Organization, member_count: int
|
||||
) -> OrganizationProfile:
|
||||
return OrganizationProfile(
|
||||
id=organization.id,
|
||||
name=organization.name,
|
||||
other_inst_id=organization.openalex_institution_id,
|
||||
deleted=organization.deleted,
|
||||
member_count=member_count,
|
||||
)
|
||||
|
||||
|
||||
def get_organizations(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
page: int,
|
||||
page_size: int,
|
||||
offset: Optional[int] = None,
|
||||
) -> OrganizationPage:
|
||||
statement = select(Organization)
|
||||
count_statement = select(func.count()).select_from(Organization)
|
||||
|
||||
if access_token.effective_role != UserRole.SUPER_ADMIN:
|
||||
scope_filter = Organization.id == access_token.effective_organization_id
|
||||
statement = statement.where(scope_filter)
|
||||
count_statement = count_statement.where(scope_filter)
|
||||
|
||||
total = session.exec(count_statement).one()
|
||||
effective_offset = offset if offset is not None else page * page_size
|
||||
organizations = session.exec(
|
||||
statement.order_by(Organization.name)
|
||||
.offset(effective_offset)
|
||||
.limit(page_size)
|
||||
).all()
|
||||
organization_ids = [organization.id for organization in organizations]
|
||||
counts = _member_counts(session, organization_ids)
|
||||
|
||||
return OrganizationPage(
|
||||
items=[
|
||||
_to_profile(organization, counts.get(organization.id, 0))
|
||||
for organization in organizations
|
||||
],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
def create_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
payload: CreateOrganizationRequest,
|
||||
) -> OrganizationProfile:
|
||||
_require_super_admin(access_token)
|
||||
name = _normalize_name(payload.name)
|
||||
_ensure_name_available(session, name)
|
||||
|
||||
organization = Organization(
|
||||
name=name,
|
||||
openalex_institution_id=(payload.other_inst_id or '').strip() or None,
|
||||
)
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
return _to_profile(organization, 0)
|
||||
|
||||
|
||||
def update_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
organization_id: uuid.UUID,
|
||||
payload: UpdateOrganizationRequest,
|
||||
) -> OrganizationProfile:
|
||||
_require_super_admin(access_token)
|
||||
organization = _get_organization_or_404(session, organization_id)
|
||||
|
||||
if payload.name is not None:
|
||||
name = _normalize_name(payload.name)
|
||||
_ensure_name_available(session, name, organization.id)
|
||||
organization.name = name
|
||||
if payload.other_inst_id is not None:
|
||||
organization.openalex_institution_id = payload.other_inst_id.strip() or None
|
||||
if payload.deleted is not None:
|
||||
organization.deleted = payload.deleted
|
||||
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
session.refresh(organization)
|
||||
counts = _member_counts(session, [organization.id])
|
||||
return _to_profile(organization, counts.get(organization.id, 0))
|
||||
|
||||
|
||||
def delete_organization(
|
||||
session: Session,
|
||||
access_token: AccessToken,
|
||||
organization_id: uuid.UUID,
|
||||
) -> None:
|
||||
_require_super_admin(access_token)
|
||||
organization = _get_organization_or_404(session, organization_id)
|
||||
organization.deleted = True
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
@@ -0,0 +1,181 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from inse.auth.model import Account, Organization, UserRole
|
||||
from inse.organization_management import service
|
||||
from inse.organization_management.model import (
|
||||
CreateOrganizationRequest,
|
||||
UpdateOrganizationRequest,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def session():
|
||||
engine = create_engine(
|
||||
"sqlite:///:memory:", connect_args={"check_same_thread": False}
|
||||
)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
with Session(engine) as database_session:
|
||||
yield database_session
|
||||
|
||||
|
||||
def token(role: UserRole, organization_id):
|
||||
return SimpleNamespace(
|
||||
effective_role=role,
|
||||
effective_organization_id=organization_id,
|
||||
)
|
||||
|
||||
|
||||
def test_superadmin_lists_all_organizations_with_active_member_count(session):
|
||||
first = Organization(name="Alpha")
|
||||
second = Organization(name="Beta", deleted=True)
|
||||
session.add(first)
|
||||
session.add(second)
|
||||
session.flush()
|
||||
session.add(
|
||||
Account(
|
||||
email="active@example.org",
|
||||
name="Active",
|
||||
password_hash="hash",
|
||||
organization_id=first.id,
|
||||
)
|
||||
)
|
||||
session.add(
|
||||
Account(
|
||||
email="deleted@example.org",
|
||||
name="Deleted",
|
||||
password_hash="hash",
|
||||
organization_id=first.id,
|
||||
deleted=True,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
|
||||
result = service.get_organizations(
|
||||
session, token(UserRole.SUPER_ADMIN, first.id), page=0, page_size=10
|
||||
)
|
||||
|
||||
assert result.total == 2
|
||||
assert [item.name for item in result.items] == ["Alpha", "Beta"]
|
||||
assert result.items[0].member_count == 1
|
||||
assert result.items[1].deleted is True
|
||||
|
||||
|
||||
def test_non_superadmin_only_sees_own_organization(session):
|
||||
own = Organization(name="Own")
|
||||
session.add(own)
|
||||
session.add(Organization(name="Other"))
|
||||
session.commit()
|
||||
|
||||
result = service.get_organizations(
|
||||
session, token(UserRole.USER, own.id), page=0, page_size=10
|
||||
)
|
||||
|
||||
assert result.total == 1
|
||||
assert result.items[0].id == own.id
|
||||
|
||||
|
||||
def test_superadmin_can_create_update_and_soft_delete(session):
|
||||
scope = Organization(name="Scope")
|
||||
session.add(scope)
|
||||
session.commit()
|
||||
access_token = token(UserRole.SUPER_ADMIN, scope.id)
|
||||
|
||||
created = service.create_organization(
|
||||
session,
|
||||
access_token,
|
||||
CreateOrganizationRequest(name=" New tenant ", other_inst_id="I123"),
|
||||
)
|
||||
assert created.name == "New tenant"
|
||||
assert created.other_inst_id == "I123"
|
||||
|
||||
updated = service.update_organization(
|
||||
session,
|
||||
access_token,
|
||||
created.id,
|
||||
UpdateOrganizationRequest(name="Renamed", other_inst_id=""),
|
||||
)
|
||||
assert updated.name == "Renamed"
|
||||
assert updated.other_inst_id is None
|
||||
|
||||
service.delete_organization(session, access_token, created.id)
|
||||
assert session.get(Organization, created.id).deleted is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", [UserRole.ADMIN, UserRole.MANAGER, UserRole.USER])
|
||||
def test_only_superadmin_can_create_organizations(session, role):
|
||||
organization = Organization(name="Scope")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.create_organization(
|
||||
session,
|
||||
token(role, organization.id),
|
||||
CreateOrganizationRequest(name="Forbidden"),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 403
|
||||
|
||||
|
||||
def test_organization_name_must_not_be_blank(session):
|
||||
organization = Organization(name="Scope")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
service.create_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, organization.id),
|
||||
CreateOrganizationRequest(name=" "),
|
||||
)
|
||||
|
||||
assert error.value.status_code == 422
|
||||
|
||||
|
||||
def test_organization_name_is_unique_ignoring_case(session):
|
||||
existing = Organization(name="Unique tenant")
|
||||
session.add(existing)
|
||||
session.commit()
|
||||
access_token = token(UserRole.SUPER_ADMIN, existing.id)
|
||||
|
||||
with pytest.raises(HTTPException) as create_error:
|
||||
service.create_organization(
|
||||
session,
|
||||
access_token,
|
||||
CreateOrganizationRequest(name=" unique TENANT "),
|
||||
)
|
||||
|
||||
assert create_error.value.status_code == 409
|
||||
|
||||
other = Organization(name="Other tenant")
|
||||
session.add(other)
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(HTTPException) as update_error:
|
||||
service.update_organization(
|
||||
session,
|
||||
access_token,
|
||||
other.id,
|
||||
UpdateOrganizationRequest(name="UNIQUE TENANT"),
|
||||
)
|
||||
|
||||
assert update_error.value.status_code == 409
|
||||
|
||||
|
||||
def test_organization_can_keep_its_name_when_updating(session):
|
||||
organization = Organization(name="Same tenant")
|
||||
session.add(organization)
|
||||
session.commit()
|
||||
|
||||
result = service.update_organization(
|
||||
session,
|
||||
token(UserRole.SUPER_ADMIN, organization.id),
|
||||
organization.id,
|
||||
UpdateOrganizationRequest(name="same TENANT"),
|
||||
)
|
||||
|
||||
assert result.name == "same TENANT"
|
||||
@@ -11,3 +11,4 @@ class Tags(StrEnum):
|
||||
PROJECTS = "Projects"
|
||||
AUTH = "Auth"
|
||||
ACCOUNT = "Account"
|
||||
ORGANIZATION = "Organization"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { userGuard } from './shared/guards/user.guard';
|
||||
import { adminGuard } from './shared/guards/admin.guard';
|
||||
import { superAdminGuard } from './shared/guards/super-admin.guard';
|
||||
import { collaborationNetworkResolver } from './resolvers/collaboration-network.resolver';
|
||||
import { personListResolver } from './resolvers/person-list.resolver';
|
||||
import { personBioResolver } from './resolvers/person-bio.resolver';
|
||||
@@ -99,6 +100,14 @@ export const routes: Routes = [
|
||||
(mod) => mod.AccountsComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'organizations',
|
||||
canActivate: [superAdminGuard],
|
||||
loadComponent: () =>
|
||||
import('./modules/organizations/organizations.component').then(
|
||||
(mod) => mod.OrganizationsComponent,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'news/:id',
|
||||
canActivate: [userGuard],
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
<h2 mat-dialog-title>
|
||||
{{
|
||||
data.mode === 'create'
|
||||
? 'Organisation erstellen'
|
||||
: 'Organisation bearbeiten'
|
||||
}}
|
||||
</h2>
|
||||
|
||||
<mat-dialog-content>
|
||||
<form class="organization-form" [formGroup]="form" (ngSubmit)="submit()">
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Name</mat-label>
|
||||
<input matInput formControlName="name" />
|
||||
@if (form.controls.name.hasError('required')) {
|
||||
<mat-error>Name ist erforderlich.</mat-error>
|
||||
}
|
||||
</mat-form-field>
|
||||
|
||||
<mat-form-field appearance="outline">
|
||||
<mat-label>Externe Institutions-ID</mat-label>
|
||||
<input matInput formControlName="otherInstId" />
|
||||
</mat-form-field>
|
||||
|
||||
@if (data.mode === 'edit') {
|
||||
<mat-checkbox formControlName="deleted">
|
||||
Organisation als gelöscht markieren
|
||||
</mat-checkbox>
|
||||
}
|
||||
</form>
|
||||
</mat-dialog-content>
|
||||
|
||||
<mat-dialog-actions align="end">
|
||||
<button mat-button type="button" (click)="close()">Abbrechen</button>
|
||||
<button mat-flat-button color="primary" type="button" (click)="submit()">
|
||||
<mat-icon>save</mat-icon>
|
||||
Speichern
|
||||
</button>
|
||||
</mat-dialog-actions>
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
.organization-form {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
min-width: min(540px, calc(100vw - 64px));
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.organization-form mat-form-field {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
mat-dialog-actions {
|
||||
padding: 12px 24px 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.organization-form {
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, inject } from '@angular/core';
|
||||
import {
|
||||
FormControl,
|
||||
FormGroup,
|
||||
ReactiveFormsModule,
|
||||
Validators,
|
||||
} from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCheckboxModule } from '@angular/material/checkbox';
|
||||
import {
|
||||
MAT_DIALOG_DATA,
|
||||
MatDialogModule,
|
||||
MatDialogRef,
|
||||
} from '@angular/material/dialog';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import type {
|
||||
CreateOrganizationPayload,
|
||||
OrganizationProfile,
|
||||
UpdateOrganizationPayload,
|
||||
} from '../../../shared/services/organization-management.service';
|
||||
|
||||
export interface OrganizationDialogData {
|
||||
mode: 'create' | 'edit';
|
||||
organization?: OrganizationProfile;
|
||||
}
|
||||
|
||||
export type OrganizationDialogResult =
|
||||
| { mode: 'create'; payload: CreateOrganizationPayload }
|
||||
| {
|
||||
mode: 'edit';
|
||||
organizationId: string;
|
||||
payload: UpdateOrganizationPayload;
|
||||
};
|
||||
|
||||
@Component({
|
||||
selector: 'app-organization-dialog',
|
||||
imports: [
|
||||
CommonModule,
|
||||
ReactiveFormsModule,
|
||||
MatButtonModule,
|
||||
MatCheckboxModule,
|
||||
MatDialogModule,
|
||||
MatFormFieldModule,
|
||||
MatIconModule,
|
||||
MatInputModule,
|
||||
],
|
||||
templateUrl: './organization-dialog.component.html',
|
||||
styleUrl: './organization-dialog.component.scss',
|
||||
standalone: true,
|
||||
})
|
||||
export class OrganizationDialogComponent {
|
||||
private readonly dialogRef =
|
||||
inject<
|
||||
MatDialogRef<
|
||||
OrganizationDialogComponent,
|
||||
OrganizationDialogResult | undefined
|
||||
>
|
||||
>(MatDialogRef);
|
||||
protected readonly data = inject<OrganizationDialogData>(MAT_DIALOG_DATA);
|
||||
|
||||
protected readonly form = new FormGroup({
|
||||
name: new FormControl(this.data.organization?.name ?? '', {
|
||||
nonNullable: true,
|
||||
validators: [Validators.required],
|
||||
}),
|
||||
otherInstId: new FormControl(
|
||||
this.data.organization?.other_inst_id ?? '',
|
||||
{ nonNullable: true },
|
||||
),
|
||||
deleted: new FormControl(this.data.organization?.deleted ?? false, {
|
||||
nonNullable: true,
|
||||
}),
|
||||
});
|
||||
|
||||
protected submit(): void {
|
||||
if (this.form.invalid) {
|
||||
this.form.markAllAsTouched();
|
||||
return;
|
||||
}
|
||||
|
||||
const value = this.form.getRawValue();
|
||||
const payload = {
|
||||
name: value.name.trim(),
|
||||
other_inst_id: value.otherInstId.trim(),
|
||||
};
|
||||
|
||||
if (this.data.mode === 'create') {
|
||||
this.dialogRef.close({ mode: 'create', payload });
|
||||
return;
|
||||
}
|
||||
|
||||
this.dialogRef.close({
|
||||
mode: 'edit',
|
||||
organizationId: this.data.organization!.id,
|
||||
payload: { ...payload, deleted: value.deleted },
|
||||
});
|
||||
}
|
||||
|
||||
protected close(): void {
|
||||
this.dialogRef.close(undefined);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<section class="organizations-page">
|
||||
<header class="page-header">
|
||||
<div>
|
||||
<h1>Organisationen</h1>
|
||||
<p>Mandanten, externe Institutions-IDs und Status verwalten.</p>
|
||||
</div>
|
||||
<button
|
||||
mat-flat-button
|
||||
color="primary"
|
||||
type="button"
|
||||
(click)="startCreate()">
|
||||
<mat-icon>add_business</mat-icon>
|
||||
Neue Organisation
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section class="table-panel">
|
||||
<div class="table-header">
|
||||
<strong>{{ total }} Organisationen</strong>
|
||||
@if (isLoading) {
|
||||
<span>Wird geladen...</span>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Externe Institutions-ID</th>
|
||||
<th>Mitglieder</th>
|
||||
<th>Status</th>
|
||||
<th>Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (organization of organizations; track organization.id) {
|
||||
<tr [class.deleted]="organization.deleted">
|
||||
<td>
|
||||
<button
|
||||
class="link-button"
|
||||
type="button"
|
||||
(click)="startEdit(organization)">
|
||||
{{ organization.name }}
|
||||
</button>
|
||||
</td>
|
||||
<td>{{ organization.other_inst_id || '–' }}</td>
|
||||
<td>{{ organization.member_count }}</td>
|
||||
<td>
|
||||
<span
|
||||
class="status"
|
||||
[class.status--deleted]="organization.deleted">
|
||||
{{ organization.deleted ? 'deleted' : 'active' }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="row-actions">
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Bearbeiten"
|
||||
(click)="startEdit(organization)">
|
||||
<mat-icon>edit</mat-icon>
|
||||
</button>
|
||||
<button
|
||||
mat-icon-button
|
||||
type="button"
|
||||
aria-label="Deaktivieren"
|
||||
[disabled]="organization.deleted"
|
||||
(click)="deleteOrganization(organization)">
|
||||
<mat-icon>delete</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
} @empty {
|
||||
<tr>
|
||||
<td colspan="6" class="empty">Keine Organisationen gefunden.</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pagination">
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
[disabled]="!canPageBack"
|
||||
(click)="loadOrganizations(page - 1)">
|
||||
<mat-icon>chevron_left</mat-icon>
|
||||
Zurück
|
||||
</button>
|
||||
<span>Seite {{ page + 1 }}</span>
|
||||
<button
|
||||
mat-button
|
||||
type="button"
|
||||
[disabled]="!canPageForward"
|
||||
(click)="loadOrganizations(page + 1)">
|
||||
Weiter
|
||||
<mat-icon>chevron_right</mat-icon>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
@@ -0,0 +1,130 @@
|
||||
.organizations-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.page-header,
|
||||
.table-header,
|
||||
.pagination,
|
||||
.row-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
h1,
|
||||
p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.page-header p,
|
||||
.table-header span {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.page-header p {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.table-panel {
|
||||
overflow: hidden;
|
||||
border: 1px solid #d7dde6;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.table-header {
|
||||
justify-content: space-between;
|
||||
padding: 16px;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 12px 16px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #edf1f7;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
th {
|
||||
color: #475569;
|
||||
font-weight: 700;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
tr.deleted {
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.identifier {
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.link-button {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #1d4ed8;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 24px;
|
||||
border-radius: 999px;
|
||||
padding: 2px 10px;
|
||||
background: #dcfce7;
|
||||
color: #166534;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.status--deleted {
|
||||
background: #fee2e2;
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
.row-actions {
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
color: #64748b;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.pagination {
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.organizations-page {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, OnInit, inject } from '@angular/core';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { finalize } from 'rxjs';
|
||||
import {
|
||||
OrganizationManagementService,
|
||||
OrganizationProfile,
|
||||
} from '../../shared/services/organization-management.service';
|
||||
import type {
|
||||
OrganizationDialogComponent,
|
||||
OrganizationDialogData,
|
||||
OrganizationDialogResult,
|
||||
} from './organization-dialog/organization-dialog.component';
|
||||
|
||||
@Component({
|
||||
selector: 'app-organizations',
|
||||
imports: [
|
||||
CommonModule,
|
||||
MatButtonModule,
|
||||
MatDialogModule,
|
||||
MatIconModule,
|
||||
MatSnackBarModule,
|
||||
],
|
||||
templateUrl: './organizations.component.html',
|
||||
styleUrl: './organizations.component.scss',
|
||||
standalone: true,
|
||||
})
|
||||
export class OrganizationsComponent implements OnInit {
|
||||
private readonly organizationService = inject(OrganizationManagementService);
|
||||
private readonly dialog = inject(MatDialog);
|
||||
private readonly snackBar = inject(MatSnackBar);
|
||||
|
||||
protected organizations: OrganizationProfile[] = [];
|
||||
protected total = 0;
|
||||
protected page = 0;
|
||||
protected readonly pageSize = 10;
|
||||
protected isLoading = false;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadOrganizations();
|
||||
}
|
||||
|
||||
protected loadOrganizations(page = this.page): void {
|
||||
this.page = page;
|
||||
this.isLoading = true;
|
||||
this.organizationService
|
||||
.getOrganizations(page, this.pageSize)
|
||||
.pipe(finalize(() => (this.isLoading = false)))
|
||||
.subscribe({
|
||||
next: (result) => {
|
||||
this.organizations = result.items;
|
||||
this.total = result.total;
|
||||
},
|
||||
error: () => this.showError('Organisationen konnten nicht geladen werden.'),
|
||||
});
|
||||
}
|
||||
|
||||
protected startCreate(): void {
|
||||
this.openDialog({ mode: 'create' });
|
||||
}
|
||||
|
||||
protected startEdit(organization: OrganizationProfile): void {
|
||||
this.openDialog({ mode: 'edit', organization });
|
||||
}
|
||||
|
||||
protected deleteOrganization(organization: OrganizationProfile): void {
|
||||
if (organization.deleted) return;
|
||||
|
||||
import('../../shared/ui/confirmation-dialog/confirmation-dialog.component').then(
|
||||
({ ConfirmationDialogComponent }) => {
|
||||
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
|
||||
data: {
|
||||
title: 'Organisation deaktivieren',
|
||||
message: `Möchtest Du die Organisation „${organization.name}“ wirklich deaktivieren?`,
|
||||
confirmText: 'Deaktivieren',
|
||||
cancelText: 'Abbrechen',
|
||||
},
|
||||
});
|
||||
|
||||
dialogRef.componentInstance.confirmDelete.subscribe(() => {
|
||||
this.softDeleteOrganization(organization);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private softDeleteOrganization(organization: OrganizationProfile): void {
|
||||
this.organizationService.deleteOrganization(organization.id).subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open('Organisation wurde deaktiviert.', 'OK', {
|
||||
duration: 3000,
|
||||
});
|
||||
this.loadOrganizations();
|
||||
},
|
||||
error: () => this.showError('Organisation konnte nicht deaktiviert werden.'),
|
||||
});
|
||||
}
|
||||
|
||||
protected get canPageBack(): boolean {
|
||||
return this.page > 0;
|
||||
}
|
||||
|
||||
protected get canPageForward(): boolean {
|
||||
return (this.page + 1) * this.pageSize < this.total;
|
||||
}
|
||||
|
||||
private openDialog(data: OrganizationDialogData): void {
|
||||
import('./organization-dialog/organization-dialog.component').then(
|
||||
({ OrganizationDialogComponent }) => {
|
||||
const dialogRef = this.dialog.open<
|
||||
OrganizationDialogComponent,
|
||||
OrganizationDialogData,
|
||||
OrganizationDialogResult | undefined
|
||||
>(OrganizationDialogComponent, {
|
||||
width: '620px',
|
||||
maxWidth: 'calc(100vw - 32px)',
|
||||
data,
|
||||
});
|
||||
|
||||
dialogRef.afterClosed().subscribe((result) => {
|
||||
if (result) this.save(result);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
private save(result: OrganizationDialogResult): void {
|
||||
const request =
|
||||
result.mode === 'create'
|
||||
? this.organizationService.createOrganization(result.payload)
|
||||
: this.organizationService.updateOrganization(
|
||||
result.organizationId,
|
||||
result.payload,
|
||||
);
|
||||
|
||||
request.subscribe({
|
||||
next: () => {
|
||||
this.snackBar.open('Organisation wurde gespeichert.', 'OK', {
|
||||
duration: 3000,
|
||||
});
|
||||
this.loadOrganizations(0);
|
||||
},
|
||||
error: (error) =>
|
||||
this.showError(
|
||||
error.status === 409
|
||||
? 'Eine Organisation mit diesem Namen existiert bereits.'
|
||||
: 'Organisation konnte nicht gespeichert werden.',
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
private showError(message: string): void {
|
||||
this.snackBar.open(message, 'OK', { duration: 5000 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { CanActivateFn, Router } from '@angular/router';
|
||||
import { catchError, filter, of, switchMap, take } from 'rxjs';
|
||||
import { CredentialService } from '../services/credential.service';
|
||||
|
||||
export const superAdminGuard: CanActivateFn = () => {
|
||||
const credentialService = inject(CredentialService);
|
||||
const router = inject(Router);
|
||||
|
||||
return credentialService.validating.pipe(
|
||||
filter((validating) => !validating),
|
||||
take(1),
|
||||
switchMap(() => {
|
||||
if (!credentialService.isAuthenticated.value) {
|
||||
void router.navigate(['/login']);
|
||||
return of(false);
|
||||
}
|
||||
|
||||
return credentialService.validateCurrentSession().pipe(
|
||||
switchMap(() => {
|
||||
if (!credentialService.isEffectiveSuperAdmin()) {
|
||||
void router.navigate(['/dashboard']);
|
||||
return of(false);
|
||||
}
|
||||
return of(true);
|
||||
}),
|
||||
catchError(() => of(false)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,75 @@
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Configuration } from '../../api';
|
||||
|
||||
export interface OrganizationProfile {
|
||||
id: string;
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
deleted: boolean;
|
||||
member_count: number;
|
||||
}
|
||||
|
||||
export interface OrganizationPage {
|
||||
items: OrganizationProfile[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
export interface CreateOrganizationPayload {
|
||||
name: string;
|
||||
other_inst_id?: string | null;
|
||||
}
|
||||
|
||||
export interface UpdateOrganizationPayload {
|
||||
name?: string;
|
||||
other_inst_id?: string | null;
|
||||
deleted?: boolean;
|
||||
}
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class OrganizationManagementService {
|
||||
private readonly httpClient = inject(HttpClient);
|
||||
private readonly apiConfiguration = inject(Configuration, { optional: true });
|
||||
|
||||
getOrganizations(page: number, pageSize: number): Observable<OrganizationPage> {
|
||||
const params = new HttpParams()
|
||||
.set('page', page)
|
||||
.set('page_size', pageSize);
|
||||
return this.httpClient.get<OrganizationPage>(
|
||||
`${this.apiBasePath}/api/organizations`,
|
||||
{ params },
|
||||
);
|
||||
}
|
||||
|
||||
createOrganization(
|
||||
payload: CreateOrganizationPayload,
|
||||
): Observable<OrganizationProfile> {
|
||||
return this.httpClient.post<OrganizationProfile>(
|
||||
`${this.apiBasePath}/api/organizations`,
|
||||
payload,
|
||||
);
|
||||
}
|
||||
|
||||
updateOrganization(
|
||||
organizationId: string,
|
||||
payload: UpdateOrganizationPayload,
|
||||
): Observable<OrganizationProfile> {
|
||||
return this.httpClient.put<OrganizationProfile>(
|
||||
`${this.apiBasePath}/api/organizations/${organizationId}`,
|
||||
payload,
|
||||
);
|
||||
}
|
||||
|
||||
deleteOrganization(organizationId: string): Observable<void> {
|
||||
return this.httpClient.delete<void>(
|
||||
`${this.apiBasePath}/api/organizations/${organizationId}`,
|
||||
);
|
||||
}
|
||||
|
||||
private get apiBasePath(): string {
|
||||
return this.apiConfiguration?.basePath ?? '';
|
||||
}
|
||||
}
|
||||
@@ -43,9 +43,11 @@
|
||||
<mat-nav-list class="nav-list">
|
||||
@for (item of navItems; track item.label) {
|
||||
@if (
|
||||
!item.adminOnly ||
|
||||
credentialService.isEffectiveSuperAdmin() ||
|
||||
credentialService.isEffectiveAdmin()
|
||||
(!item.adminOnly ||
|
||||
credentialService.isEffectiveSuperAdmin() ||
|
||||
credentialService.isEffectiveAdmin()) &&
|
||||
(!item.superAdminOnly ||
|
||||
credentialService.isEffectiveSuperAdmin())
|
||||
) {
|
||||
@if (collapsed()) {
|
||||
<a
|
||||
@@ -108,7 +110,6 @@
|
||||
(credentialService.login | async) || 'Max Mustermann'
|
||||
}}</strong>
|
||||
<strong>{{ credentialService.organizationName | async }}</strong>
|
||||
<span>Startup Coach</span>
|
||||
</div>
|
||||
<mat-icon>expand_more</mat-icon>
|
||||
</div>
|
||||
|
||||
@@ -22,6 +22,7 @@ type NavItem = {
|
||||
disabled: boolean;
|
||||
queryParams?: Record<string, string | number | boolean>;
|
||||
adminOnly?: boolean;
|
||||
superAdminOnly?: boolean;
|
||||
};
|
||||
|
||||
@Component({
|
||||
@@ -106,6 +107,13 @@ export class AppMenuComponent {
|
||||
disabled: false,
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
label: 'Organisationen',
|
||||
icon: 'domain',
|
||||
route: '/organizations',
|
||||
disabled: false,
|
||||
superAdminOnly: true,
|
||||
},
|
||||
];
|
||||
|
||||
constructor(
|
||||
|
||||
Reference in New Issue
Block a user