From bc8a821928fbfc87be85323e59b2904940c03214 Mon Sep 17 00:00:00 2001 From: Sau1707 <83017316+Sau1707@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:53:04 +0100 Subject: [PATCH] refactor!: simplify policy ownership and organization usage Centralize Solution refresh ownership, member eligibility, admin pagination, and company website normalization. Require explicit deployment CPU budgets and remove the unused live organization member count. BREAKING CHANGE: Organization usage GET and PATCH responses no longer include users. Clients must stop requiring that field and regenerate their schemas. Historical invoice member counts remain unchanged; no database migration is required. --- api/openapi/v1.json | 8 +-- api/src/database/services/organizations.py | 14 ++---- api/src/kubernetes/solutions.py | 2 +- api/src/models/companies.py | 8 +-- api/src/models/organizations.py | 1 - .../routes/v1/organization/organizations.py | 2 +- api/tests/database/services/test_companies.py | 2 +- api/tests/kubernetes/test_solutions.py | 4 ++ api/tests/models/test_types.py | 3 +- api/tests/routes/v1/test_organizations.py | 15 ++---- sdk/longlink/database/companies.py | 13 ++--- sdk/tests/database/test_base.py | 3 +- .../lib/generated/platform-api-v1/zod.gen.ts | 1 - web/src/platform/permissions.ts | 7 +++ web/src/platform/routes/admin/compute.tsx | 2 +- web/src/platform/routes/admin/operations.tsx | 2 +- .../platform/routes/admin/organizations.tsx | 2 +- web/src/platform/routes/admin/solutions.tsx | 2 +- web/src/platform/routes/admin/use-filters.ts | 7 +-- web/src/platform/routes/admin/users.tsx | 2 +- .../routes/orgs/dialogs/create-solution.tsx | 17 ++++--- .../routes/orgs/dialogs/deployment-review.tsx | 12 ++--- .../routes/orgs/dialogs/solution-tags.tsx | 6 +-- web/src/platform/routes/orgs/members.tsx | 5 +- web/src/platform/routes/orgs/organization.tsx | 10 +++- .../routes/orgs/solution-settings.tsx | 11 +++- .../routes/orgs/create-solution.test.tsx | 12 +++-- .../routes/orgs/deployment-review.test.tsx | 6 ++- .../routes/orgs/payment-methods.test.tsx | 2 - .../routes/orgs/settings-permissions.test.tsx | 50 +++++++++++++++++++ web/tests/platform/routes/orgs/tags.test.tsx | 1 + web/tests/platform/routes/orgs/usage.test.tsx | 2 - 32 files changed, 143 insertions(+), 91 deletions(-) diff --git a/api/openapi/v1.json b/api/openapi/v1.json index 3b37f3ab7..18b03b037 100644 --- a/api/openapi/v1.json +++ b/api/openapi/v1.json @@ -3906,7 +3906,7 @@ "/api/v1/organizations/{organization_id}/usage": { "get": { "summary": "Get Organization Usage", - "description": "Show current users, Solutions, and the same monthly rates used for invoicing.", + "description": "Show current Solutions, capacity, and the same monthly rates used for invoicing.", "operationId": "get_organization_usage_api_v1_organizations__organization_id__usage_get", "parameters": [ { @@ -6063,11 +6063,6 @@ "title": "Storage Gib Monthly Price", "default": 1 }, - "users": { - "type": "integer", - "minimum": 0.0, - "title": "Users" - }, "status": { "$ref": "#/components/schemas/Status" }, @@ -6116,7 +6111,6 @@ }, "type": "object", "required": [ - "users", "status", "solutions", "stripe_enabled", diff --git a/api/src/database/services/organizations.py b/api/src/database/services/organizations.py index 960a2b2b5..7ac3a1717 100644 --- a/api/src/database/services/organizations.py +++ b/api/src/database/services/organizations.py @@ -403,16 +403,9 @@ async def lock_active_access( async def usage(session: AsyncSession, organization_id: UUID) -> RowMapping: - """Read member counts, active Solutions, and capacity in one snapshot.""" + """Read active Solutions and capacity in one snapshot.""" - # Scope accepted active members and active Solutions to this Organization. - users = ( - select(func.count()) - .select_from(UserOrganization) - .join(User, col(User.id) == col(UserOrganization.user_id)) - .where(col(UserOrganization.organization_id) == organization_id, col(User.deleted_at).is_(None)) - .scalar_subquery() - ) + # Scope active Solutions to this Organization. solutions = ( select(func.count()) .select_from(Solution) @@ -420,10 +413,9 @@ async def usage(session: AsyncSession, organization_id: UUID) -> RowMapping: .scalar_subquery() ) - # Read counts, capacity, and payment authorization in one database snapshot. + # Read the Solution count, capacity, and payment authorization in one database snapshot. capacity = await session.execute( select( - users.label("users"), solutions.label("solutions"), col(Organization.compute_ram_bytes), col(Organization.storage_bytes), diff --git a/api/src/kubernetes/solutions.py b/api/src/kubernetes/solutions.py index d4511411f..bcd6fc110 100644 --- a/api/src/kubernetes/solutions.py +++ b/api/src/kubernetes/solutions.py @@ -159,7 +159,7 @@ async def apply( secrets: dict[str, str], *, revision_id: UUID, - cpu_millicores: int = 500, + cpu_millicores: int, migrate: bool = True, # Private images use the Organization's retained registry connection. registry_connection_id: UUID | None = None, diff --git a/api/src/models/companies.py b/api/src/models/companies.py index 97d536fed..c541cecfe 100644 --- a/api/src/models/companies.py +++ b/api/src/models/companies.py @@ -1,5 +1,6 @@ from uuid import UUID from pydantic import Field, HttpUrl, BaseModel, ConfigDict, field_validator +from longlink.database import companies from src.models.pagination import Page @@ -39,12 +40,7 @@ class CompanySummary(BaseModel): website: str | None = Field(default=None, max_length=255) description: str | None = Field(default=None, max_length=20000) - @field_validator("website", mode="before") - @classmethod - def validate_url(cls, value: str | None) -> str | None: - """Allow only HTTP company websites.""" - - return str(HttpUrl(value)) if value is not None else None + validate_website = field_validator("website", mode="before")(companies.normalize_website) class CompanyProfile(CompanySummary): diff --git a/api/src/models/organizations.py b/api/src/models/organizations.py index b8a310570..d0014abba 100644 --- a/api/src/models/organizations.py +++ b/api/src/models/organizations.py @@ -35,7 +35,6 @@ class OrganizationUsage(BaseModel): storage_gib_monthly_price: int = int(pricing.STORAGE_GIB_MONTHLY_PRICE) # Usage and payments - users: int = Field(ge=0) status: Status solutions: int = Field(ge=0) max_solutions: int = MAX_SOLUTIONS diff --git a/api/src/routes/v1/organization/organizations.py b/api/src/routes/v1/organization/organizations.py index ef9399644..1e83955b6 100644 --- a/api/src/routes/v1/organization/organizations.py +++ b/api/src/routes/v1/organization/organizations.py @@ -57,7 +57,7 @@ async def get_organization_solutions(session: auth.Session, membership: auth.Org @router.get("/organizations/{organization_id}/usage", response_model=OrganizationUsage) async def get_organization_usage(session: auth.Session, membership: auth.OrganizationMember) -> dict[str, int | bool | str | None]: - """Show current users, Solutions, and the same monthly rates used for invoicing.""" + """Show current Solutions, capacity, and the same monthly rates used for invoicing.""" usage = await organizations.usage(session, membership.organization_id) return {**usage, "stripe_enabled": env.stripe_enabled} diff --git a/api/tests/database/services/test_companies.py b/api/tests/database/services/test_companies.py index a0454263c..6adc17fe5 100644 --- a/api/tests/database/services/test_companies.py +++ b/api/tests/database/services/test_companies.py @@ -25,7 +25,7 @@ async def test_company_profiles_serialize_detached_without_loading_logos_or_refe sector="Technology", source="ch", address="Bahnhofstrasse 1, 8001 Zürich", - website="https://example.com/", + website="https://example.com", legal_form=LegalForm.CORPORATION, description="Retained description", locations=[{"kind": "office", "address": "Bundesplatz 1, 3011 Bern"}], diff --git a/api/tests/kubernetes/test_solutions.py b/api/tests/kubernetes/test_solutions.py index 1b8928a2d..d3c167073 100644 --- a/api/tests/kubernetes/test_solutions.py +++ b/api/tests/kubernetes/test_solutions.py @@ -136,6 +136,7 @@ async def apply(resource: solutions.APIObject) -> None: "ghcr.io/longlink/dashboard:latest", {}, revision_id=UUID(int=1), + cpu_millicores=500, ) # A failed migration must prevent application Service publication. @@ -256,6 +257,7 @@ async def apply(_resource: solutions.APIObject) -> None: {}, # Keep the rendered release identity deterministic. revision_id=UUID(int=1), + cpu_millicores=500, migrate=False, ) @@ -285,6 +287,7 @@ async def apply(_resource: solutions.APIObject) -> None: "ghcr.io/longlink/dashboard:latest", {}, revision_id=UUID(int=1), + cpu_millicores=500, # Recovery of an already-migrated release must not rerun its Job. migrate=False, ) @@ -349,6 +352,7 @@ async def sleep(delay: float) -> None: "ghcr.io/longlink/dashboard:latest", {}, revision_id=UUID(int=1), + cpu_millicores=500, migrate=False, ) diff --git a/api/tests/models/test_types.py b/api/tests/models/test_types.py index 8ef0bf0b9..cc4e51848 100644 --- a/api/tests/models/test_types.py +++ b/api/tests/models/test_types.py @@ -65,6 +65,7 @@ def test_company_summary_validates_public_profile_limits_and_normalizes_websites CompanySummary.model_validate(profile | {"slug": slug}) assert CompanySummary.model_validate(profile | {"website": website}).website == website assert CompanySummary.model_validate(profile | {"website": "https://example.com"}).website == "https://example.com/" - for invalid_website in (website + "x", "https://" + ".".join(["a" * 60] * 4) + ".com"): + assert CompanySummary.model_validate(profile | {"website": None}).website is None + for invalid_website in ("", "ftp://example.com", website + "x", "https://" + ".".join(["a" * 60] * 4) + ".com"): with pytest.raises(ValidationError, match="website"): CompanySummary.model_validate(profile | {"website": invalid_website}) diff --git a/api/tests/routes/v1/test_organizations.py b/api/tests/routes/v1/test_organizations.py index 0eba08381..f000b3ef1 100644 --- a/api/tests/routes/v1/test_organizations.py +++ b/api/tests/routes/v1/test_organizations.py @@ -181,10 +181,10 @@ async def test_usage_edit_revalidates_ownership_and_payment_authorization( assert split.status_code == 402 -async def test_usage_counts_only_active_members_and_solutions_in_the_organization( +async def test_usage_counts_only_active_solutions_in_the_organization( clients: tuple[AsyncClient, AsyncClient, AsyncClient], users: tuple[User, User, User] ) -> None: - """Exclude other tenants, pending invitations, and deleted users and Solutions.""" + """Exclude deleted and other tenants' Solutions without reporting member counts.""" # Arrange organization = await create_organization(users[0]) @@ -193,18 +193,9 @@ async def test_usage_counts_only_active_members_and_solutions_in_the_organizatio deleted_solution = await create_solution(organization, name="deleted") await create_solution(foreign, name="foreign") async with session_scope() as session: - deleted_user = await session.get(User, users[2].id) persisted_solution = await session.get(Solution, deleted_solution.id) - assert deleted_user is not None assert persisted_solution is not None - deleted_user.deleted_at = datetime.now(UTC) persisted_solution.deleted_at = datetime.now(UTC) - session.add_all( - [ - UserOrganization(user_id=users[2].id, organization_id=organization.id, role=OrganizationRoles.read), - OrganizationInvitation(organization_id=organization.id, email="pending@example.com", role=OrganizationRoles.read), - ] - ) await session.commit() # Act @@ -212,7 +203,7 @@ async def test_usage_counts_only_active_members_and_solutions_in_the_organizatio # Assert assert response.status_code == 200 - assert response.json()["users"] == 1 + assert "users" not in response.json() assert response.json()["solutions"] == 1 diff --git a/sdk/longlink/database/companies.py b/sdk/longlink/database/companies.py index 69743bab9..5562abca7 100644 --- a/sdk/longlink/database/companies.py +++ b/sdk/longlink/database/companies.py @@ -10,6 +10,12 @@ from longlink.database.legalforms import LegalForm +def normalize_website(value: str | None) -> str | None: + """Normalize nullable company websites before enforcing field length limits.""" + + return str(HttpUrl(value)) if value is not None else None + + class Company(PlatformModel, table=True): """Persist public company profiles independently of collection systems.""" @@ -67,12 +73,7 @@ def generate_slug(cls, value: object) -> object: slug = f"{stem[: cls.MAX_SLUG_LENGTH - len(ehra) - 1].rstrip('-')}-{ehra}" return {**value, "slug": slug} - @field_validator("website", mode="before") - @classmethod - def validate_website(cls, value: str | None) -> str | None: - """Normalize HTTP websites before enforcing the storage limit.""" - - return str(HttpUrl(value)) if value is not None else None + validate_website = field_validator("website", mode="before")(normalize_website) @field_validator("legal_form", mode="before") @classmethod diff --git a/sdk/tests/database/test_base.py b/sdk/tests/database/test_base.py index 15a648306..1fc997991 100644 --- a/sdk/tests/database/test_base.py +++ b/sdk/tests/database/test_base.py @@ -83,7 +83,8 @@ async def test_company_collector_persists_profile_outside_solution_metadata() -> Company.model_validate({"uid": "CHE123456789", "name": "Company", "slug": slug}) website = "https://example.com/" + "x" * 235 assert Company.model_validate({"uid": "CHE123456789", "name": "Company", "slug": "company", "website": website}).website == website - for invalid_website in (website + "x", "https://" + ".".join(["a" * 60] * 4) + ".com"): + assert Company.model_validate({"uid": "CHE123456789", "name": "Company", "slug": "company", "website": None}).website is None + for invalid_website in ("", "ftp://example.com", website + "x", "https://" + ".".join(["a" * 60] * 4) + ".com"): with pytest.raises(ValidationError, match="website"): Company.model_validate({"uid": "CHE123456789", "name": "Company", "slug": "company", "website": invalid_website}) with pytest.raises(ValidationError): diff --git a/web/src/lib/generated/platform-api-v1/zod.gen.ts b/web/src/lib/generated/platform-api-v1/zod.gen.ts index a22efaabf..2b85668f5 100644 --- a/web/src/lib/generated/platform-api-v1/zod.gen.ts +++ b/web/src/lib/generated/platform-api-v1/zod.gen.ts @@ -719,7 +719,6 @@ export const zOrganizationUsage = z.object({ cpu_monthly_price: z.int().optional().default(1000), ram_gib_monthly_price: z.int().optional().default(500), storage_gib_monthly_price: z.int().optional().default(1), - users: z.int().gte(0), status: zStatus, solutions: z.int().gte(0), max_solutions: z.int().optional().default(9), diff --git a/web/src/platform/permissions.ts b/web/src/platform/permissions.ts index 5d80f4196..5ca0cb036 100644 --- a/web/src/platform/permissions.ts +++ b/web/src/platform/permissions.ts @@ -10,6 +10,13 @@ export function canAdminister(role: z.output) return role === 'admin' || role === 'owner'; } +export function canManageMember( + caller: z.output, + target: z.output +): boolean { + return canAdminister(caller) && (caller === 'owner' || target !== 'owner'); +} + /** Identifies organization roles allowed to maintain Solutions, registries, and invitations. */ export function canMaintain(role: z.output): boolean { return role === 'maintain' || canAdminister(role); diff --git a/web/src/platform/routes/admin/compute.tsx b/web/src/platform/routes/admin/compute.tsx index 5756f7e36..a76ef3e0e 100644 --- a/web/src/platform/routes/admin/compute.tsx +++ b/web/src/platform/routes/admin/compute.tsx @@ -133,7 +133,7 @@ export default function Compute() { spacing="sm" padding="none" action={searchField} - footer={} + footer={} > diff --git a/web/src/platform/routes/admin/operations.tsx b/web/src/platform/routes/admin/operations.tsx index d14dc7aa2..a4e56ca1c 100644 --- a/web/src/platform/routes/admin/operations.tsx +++ b/web/src/platform/routes/admin/operations.tsx @@ -156,7 +156,7 @@ export default function Operations() { spacing="sm" padding="none" action={searchField} - footer={} + footer={} > diff --git a/web/src/platform/routes/admin/organizations.tsx b/web/src/platform/routes/admin/organizations.tsx index 67e6a8efd..8d1cf8dea 100644 --- a/web/src/platform/routes/admin/organizations.tsx +++ b/web/src/platform/routes/admin/organizations.tsx @@ -129,7 +129,7 @@ export default function Organizations() { spacing="sm" padding="none" action={searchField} - footer={} + footer={} > diff --git a/web/src/platform/routes/admin/solutions.tsx b/web/src/platform/routes/admin/solutions.tsx index 9d7f6c088..adf4514ae 100644 --- a/web/src/platform/routes/admin/solutions.tsx +++ b/web/src/platform/routes/admin/solutions.tsx @@ -156,7 +156,7 @@ export default function Solutions() { spacing="sm" padding="none" action={searchField} - footer={} + footer={} > diff --git a/web/src/platform/routes/admin/use-filters.ts b/web/src/platform/routes/admin/use-filters.ts index 3283184f1..475daa478 100644 --- a/web/src/platform/routes/admin/use-filters.ts +++ b/web/src/platform/routes/admin/use-filters.ts @@ -2,9 +2,10 @@ import { useDeferredValue, useState } from 'react'; import type { OnChangeFn, PaginationState } from '@tanstack/react-table'; export function useFilters() { + const pageSize = 25; const [filters, setFilters] = useState({ search: '', pageIndex: 0 }); const { search, pageIndex } = useDeferredValue(filters); - const suffix = `?page=${pageIndex + 1}&page_size=25&search=${encodeURIComponent(search.trim())}`; + const suffix = `?page=${pageIndex + 1}&page_size=${pageSize}&search=${encodeURIComponent(search.trim())}`; const setSearch = (search: string) => { setFilters({ search, pageIndex: 0 }); @@ -15,14 +16,14 @@ export function useFilters() { ...current, pageIndex: typeof updater === 'function' - ? updater({ pageIndex: current.pageIndex, pageSize: 25 }).pageIndex + ? updater({ pageIndex: current.pageIndex, pageSize }).pageIndex : updater.pageIndex })); }; return { search: filters.search, - pagination: { pageIndex: filters.pageIndex, pageSize: 25 }, + pagination: { pageIndex: filters.pageIndex, pageSize }, suffix, setSearch, setPagination diff --git a/web/src/platform/routes/admin/users.tsx b/web/src/platform/routes/admin/users.tsx index 83901286b..604d0a5ef 100644 --- a/web/src/platform/routes/admin/users.tsx +++ b/web/src/platform/routes/admin/users.tsx @@ -122,7 +122,7 @@ export default function Users() { spacing="sm" padding="none" action={searchField} - footer={} + footer={} > diff --git a/web/src/platform/routes/orgs/dialogs/create-solution.tsx b/web/src/platform/routes/orgs/dialogs/create-solution.tsx index 981748390..cb1370950 100644 --- a/web/src/platform/routes/orgs/dialogs/create-solution.tsx +++ b/web/src/platform/routes/orgs/dialogs/create-solution.tsx @@ -4,7 +4,6 @@ import { useForm } from 'react-hook-form'; import { Input } from '@/components/shadcn/input'; import { useSubmit } from '@/lib/hooks/use-submit'; import { zodResolver } from '@hookform/resolvers/zod'; -import { useQueryClient } from '@tanstack/react-query'; import { Stack } from '@/components/longlink/layout/stack'; import { Button } from '@/components/longlink/action/button'; import { Dialog } from '@/components/longlink/layout/dialog'; @@ -15,8 +14,15 @@ import { IllustratedForm } from '@/platform/components/illustrated-form'; import { Field, FieldError, FieldLabel } from '@/components/shadcn/field'; /** Owns image inspection and configuration for one creation attempt. */ -export default function CreateSolution({ organizationId, onClose }: { organizationId: string; onClose: () => void }) { - const client = useQueryClient(); +export default function CreateSolution({ + organizationId, + onSaved, + onClose +}: { + organizationId: string; + onSaved: () => Promise; + onClose: () => void; +}) { const [stage, setStage] = useState<'image' | 'configure'>('image'); const [inspection, setInspection] = useState<{ source: string; @@ -66,10 +72,7 @@ export default function CreateSolution({ organizationId, onClose }: { organizati }; await api.post(`/api/v1/organizations/${organizationId}/solutions`, { json }); - await client.invalidateQueries({ - queryKey: ['api', `/api/v1/organizations/${organizationId}/solutions`], - exact: true - }); + await onSaved(); onClose(); })(); return; diff --git a/web/src/platform/routes/orgs/dialogs/deployment-review.tsx b/web/src/platform/routes/orgs/dialogs/deployment-review.tsx index 514f0dc4c..fbe47474c 100644 --- a/web/src/platform/routes/orgs/dialogs/deployment-review.tsx +++ b/web/src/platform/routes/orgs/dialogs/deployment-review.tsx @@ -1,6 +1,7 @@ import type { z } from 'zod'; import { api } from '@/lib/api'; import { ArrowRight } from 'lucide-react'; +import { useQuery } from '@tanstack/react-query'; import { Input } from '@/components/shadcn/input'; import { useSubmit } from '@/lib/hooks/use-submit'; import { useEffect, useId, useState } from 'react'; @@ -10,12 +11,11 @@ import { Stack } from '@/components/longlink/layout/stack'; import { Button } from '@/components/longlink/action/button'; import { Dialog } from '@/components/longlink/layout/dialog'; import { Heading } from '@/components/longlink/display/heading'; -import { useQuery, useQueryClient } from '@tanstack/react-query'; import * as schemas from '@/lib/generated/platform-api-v1/zod.gen'; import { Controller, useForm, useWatch, type ResolverResult } from 'react-hook-form'; import { Field, FieldDescription, FieldError, FieldLabel } from '@/components/shadcn/field'; -type DeploymentReviewProps = { item: { id: string; name: string }; organizationId: string; onClose: () => void }; +type DeploymentReviewProps = { item: { id: string; name: string }; onSaved: () => Promise; onClose: () => void }; type DeploymentDraft = { envs: Record }; @@ -35,8 +35,7 @@ function imageDigest(image: string) { } /** Owns fresh inspection, the deployment draft, and submission for one review attempt. */ -export default function DeploymentReview({ item, organizationId, onClose }: DeploymentReviewProps) { - const client = useQueryClient(); +export default function DeploymentReview({ item, onSaved, onClose }: DeploymentReviewProps) { const formId = useId(); const [step, setStep] = useState(0); @@ -113,10 +112,7 @@ export default function DeploymentReview({ item, organizationId, onClose }: Depl const edits = environmentEdits(values.envs); if (candidate.metadata.image === candidate.current_image && Object.keys(edits).length === 0) return; await api.post(path, { json: { envs: edits, expected_revision_id: candidate.revision_id } }); - await client.invalidateQueries({ - queryKey: ['api', `/api/v1/organizations/${organizationId}/solutions`], - exact: true - }); + await onSaved(); onClose(); } diff --git a/web/src/platform/routes/orgs/dialogs/solution-tags.tsx b/web/src/platform/routes/orgs/dialogs/solution-tags.tsx index ee1c92641..4ca92a9d7 100644 --- a/web/src/platform/routes/orgs/dialogs/solution-tags.tsx +++ b/web/src/platform/routes/orgs/dialogs/solution-tags.tsx @@ -4,7 +4,6 @@ import * as tabs from '@/platform/tabs'; import { useSubmit } from '@/lib/hooks/use-submit'; import { zodResolver } from '@hookform/resolvers/zod'; import { Controller, useForm } from 'react-hook-form'; -import { useQueryClient } from '@tanstack/react-query'; import { Stack } from '@/components/longlink/layout/stack'; import { Button } from '@/components/longlink/action/button'; import { Dialog } from '@/components/longlink/layout/dialog'; @@ -28,14 +27,15 @@ export function SolutionTags({ base, tags, solution, + onSaved, onClose }: { + onSaved: () => Promise; onClose: () => void; base: string; tags: z.output[]; solution: Pick, 'id' | 'name' | 'tag_ids'>; }) { - const client = useQueryClient(); const anchor = useComboboxAnchor(); const availableTags = tags.filter((tag) => tag.kind === 'tag'); const tagsById = new Map(availableTags.map((tag) => [tag.id, tag])); @@ -48,7 +48,7 @@ export function SolutionTags({ const submit = useSubmit( async (data: z.output) => { await api.patch(`${base}/solutions/${solution.id}/tags`, { json: data }); - await client.invalidateQueries({ queryKey: ['api', `${base}/solutions`], exact: true }); + await onSaved(); onClose(); }, { onError: () => form.setError('root', { message: 'Could not save the tags. Please try again.' }) } diff --git a/web/src/platform/routes/orgs/members.tsx b/web/src/platform/routes/orgs/members.tsx index 4a32b499a..2e037f134 100644 --- a/web/src/platform/routes/orgs/members.tsx +++ b/web/src/platform/routes/orgs/members.tsx @@ -30,7 +30,6 @@ export default function MembersSection({ base, role }: { base: string; role: Org const client = useQueryClient(); const navigate = useNavigate(); const canAdminister = permissions.canAdminister(role); - const canManageOwners = role === 'owner'; const [member, setMember, closeMember] = useSelection<{ id: string; @@ -44,7 +43,7 @@ export default function MembersSection({ base, role }: { base: string; role: Org const selectedMember = members.find((row) => row.user.id === member?.id); const canManageSelectedMember = - canAdminister && selectedMember !== undefined && (canManageOwners || selectedMember.role !== 'owner'); + selectedMember !== undefined && permissions.canManageMember(role, selectedMember.role); return ( <> @@ -79,7 +78,7 @@ export default function MembersSection({ base, role }: { base: string; role: Org {canAdminister && ( - {row.role === 'owner' && !canManageOwners ? null : ( + {permissions.canManageMember(role, row.role) && ( (); - const [solutions] = useOrganizationSolutions(membership.organization.id); + const [solutions, invalidateSolutions] = useOrganizationSolutions(membership.organization.id); const [creation, setCreation, closeCreation] = useSelection<{ kind: 'create' }>(); const { organization, tags, activeTag, role } = membership; const canMaintain = permissions.canMaintain(role); @@ -123,7 +123,13 @@ export default function Organization() { )} - {creation && } + {creation && ( + + )} ); } diff --git a/web/src/platform/routes/orgs/solution-settings.tsx b/web/src/platform/routes/orgs/solution-settings.tsx index 3d8a117b8..8db95f05b 100644 --- a/web/src/platform/routes/orgs/solution-settings.tsx +++ b/web/src/platform/routes/orgs/solution-settings.tsx @@ -186,7 +186,13 @@ export default function SolutionSettings({ membership }: { membership: Organizat - {selected?.kind === 'create' && } + {selected?.kind === 'create' && ( + + )} {selected?.kind === 'permissions' && ( )} @@ -207,7 +214,7 @@ export default function SolutionSettings({ membership }: { membership: Organizat )} diff --git a/web/tests/platform/routes/orgs/create-solution.test.tsx b/web/tests/platform/routes/orgs/create-solution.test.tsx index 2dd2563ba..350b3ddf9 100644 --- a/web/tests/platform/routes/orgs/create-solution.test.tsx +++ b/web/tests/platform/routes/orgs/create-solution.test.tsx @@ -59,7 +59,13 @@ it('gates creation on inspection and validation, retaining configuration through try { await withMounted( - completions.push('created')} />, + { + await client.invalidateQueries({ queryKey: ['api', path], exact: true }); + }} + onClose={() => completions.push('created')} + />, async () => { const events = userEvent.setup(); const dialog = document.querySelector('[role="dialog"]'); @@ -195,7 +201,7 @@ it('reports failed inspection and allows retrying the same image without losing try { await withMounted( - + {}} onClose={onClose} /> , async () => { const events = userEvent.setup(); @@ -268,7 +274,7 @@ it('cancels inspection when its creation attempt unmounts without reporting an e try { await withMounted( - + {}} onClose={onClose} /> , async () => { const events = userEvent.setup(); diff --git a/web/tests/platform/routes/orgs/deployment-review.test.tsx b/web/tests/platform/routes/orgs/deployment-review.test.tsx index 45b364179..419b93e1e 100644 --- a/web/tests/platform/routes/orgs/deployment-review.test.tsx +++ b/web/tests/platform/routes/orgs/deployment-review.test.tsx @@ -62,7 +62,9 @@ describe('DeploymentReview', () => { await withMounted( { + await client.invalidateQueries({ queryKey: ['api', path], exact: true }); + }} onClose={onClose} />, async () => { @@ -412,7 +414,7 @@ function ReviewHost({ onClose }: { onClose: () => void }) { return open ? ( {}} onClose={() => { onClose(); setOpen(false); diff --git a/web/tests/platform/routes/orgs/payment-methods.test.tsx b/web/tests/platform/routes/orgs/payment-methods.test.tsx index 476453733..e78d3d6dd 100644 --- a/web/tests/platform/routes/orgs/payment-methods.test.tsx +++ b/web/tests/platform/routes/orgs/payment-methods.test.tsx @@ -32,7 +32,6 @@ it('loads cards only with management access and hides them even when a refresh f if (request.method === 'GET' && path === `${base}/usage`) { return Response.json({ - users: 1, status: 'running', solutions: 1, stripe_enabled: true, @@ -158,7 +157,6 @@ it('attempts checkout offline, guards rapid activation, and permits retry after client.setQueryData( ['api', `${base}/usage`], schemas.zOrganizationUsage.parse({ - users: 1, status: 'running', solutions: 1, stripe_enabled: true, diff --git a/web/tests/platform/routes/orgs/settings-permissions.test.tsx b/web/tests/platform/routes/orgs/settings-permissions.test.tsx index 4962dbe17..0d0f15791 100644 --- a/web/tests/platform/routes/orgs/settings-permissions.test.tsx +++ b/web/tests/platform/routes/orgs/settings-permissions.test.tsx @@ -117,6 +117,56 @@ it.each([ expect(memberActions(output, email)).not.toBeNull(); }); +it('revokes an open member confirmation when its target becomes an owner', async () => { + // Arrange + const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0, refetchOnMount: false } } }); + client.setQueryData( + ['api', `${base}/members`], + [ + { user: caller, role: 'admin' }, + { user: owner, role: 'write' } + ] + ); + + await withMounted( + settingsFor('admin'), + async (output) => { + const actions = memberActions(output, owner.email); + + if (!actions) throw new Error('Expected member actions'); + + // Act + await act(async () => actions.dispatchEvent(new MouseEvent('click', { bubbles: true }))); + + const remove = Array.from(document.querySelectorAll('[role="menuitem"]')).find( + (item) => item.textContent === 'Remove member' + ); + + if (!remove) throw new Error('Expected the remove member action'); + + await act(async () => remove.click()); + expect(document.querySelector('[role="alertdialog"]')?.textContent).toContain(owner.name); + + await act(async () => { + client.setQueryData( + ['api', `${base}/members`], + [ + { user: caller, role: 'admin' }, + { user: owner, role: 'owner' } + ] + ); + await new Promise((resolve) => window.setTimeout(resolve, 0)); + }); + + // Assert + expect(document.querySelector('[role="alertdialog"]')).toBeNull(); + expect(memberActions(output, owner.email)).toBeNull(); + }, + `${path}#members`, + client + ); +}); + it.each([ { role: 'maintain', options: ['read', 'write', 'maintain'] }, { role: 'admin', options: ['read', 'write', 'maintain', 'admin'] }, diff --git a/web/tests/platform/routes/orgs/tags.test.tsx b/web/tests/platform/routes/orgs/tags.test.tsx index fe5394380..57730663d 100644 --- a/web/tests/platform/routes/orgs/tags.test.tsx +++ b/web/tests/platform/routes/orgs/tags.test.tsx @@ -250,6 +250,7 @@ it.each(['unchanged', 'cleared', 'unknown'] as const)('submits only explicit tag tag_ids: edit === 'unknown' ? [tags[0].id, '00000000-0000-4000-8000-000000000099'] : [tags[0].id] }} + onSaved={async () => {}} onClose={completed} /> , diff --git a/web/tests/platform/routes/orgs/usage.test.tsx b/web/tests/platform/routes/orgs/usage.test.tsx index da60b3b9b..21337e21c 100644 --- a/web/tests/platform/routes/orgs/usage.test.tsx +++ b/web/tests/platform/routes/orgs/usage.test.tsx @@ -13,7 +13,6 @@ it('edits independent pools atomically, validates steps, and preserves failed ed // Arrange const base = '/api/v1/organizations/00000000-0000-4000-8000-000000000002'; const usage = schemas.zOrganizationUsage.parse({ - users: 1, status: 'running', solutions: 1, stripe_enabled: true, @@ -223,7 +222,6 @@ it('keeps database editing available with failed metrics and cancels without sav // Arrange const base = '/api/v1/organizations/00000000-0000-4000-8000-000000000002'; const usage = schemas.zOrganizationUsage.parse({ - users: 1, status: 'running', solutions: 1, stripe_enabled: true,