Skip to content
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
8 changes: 1 addition & 7 deletions api/openapi/v1.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
{
Expand Down Expand Up @@ -6063,11 +6063,6 @@
"title": "Storage Gib Monthly Price",
"default": 1
},
"users": {
"type": "integer",
"minimum": 0.0,
"title": "Users"
},
"status": {
"$ref": "#/components/schemas/Status"
},
Expand Down Expand Up @@ -6116,7 +6111,6 @@
},
"type": "object",
"required": [
"users",
"status",
"solutions",
"stripe_enabled",
Expand Down
14 changes: 3 additions & 11 deletions api/src/database/services/organizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,27 +403,19 @@ 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)
.where(col(Solution.organization_id) == organization_id, col(Solution.deleted_at).is_(None))
.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),
Expand Down
2 changes: 1 addition & 1 deletion api/src/kubernetes/solutions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 2 additions & 6 deletions api/src/models/companies.py
Original file line number Diff line number Diff line change
@@ -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


Expand Down Expand Up @@ -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):
Expand Down
1 change: 0 additions & 1 deletion api/src/models/organizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion api/src/routes/v1/organization/organizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
2 changes: 1 addition & 1 deletion api/tests/database/services/test_companies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}],
Expand Down
4 changes: 4 additions & 0 deletions api/tests/kubernetes/test_solutions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
)

Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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,
)

Expand Down
3 changes: 2 additions & 1 deletion api/tests/models/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})
15 changes: 3 additions & 12 deletions api/tests/routes/v1/test_organizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand All @@ -193,26 +193,17 @@ 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
response = await clients[0].get(f"/api/v1/organizations/{organization.id}/usage")

# Assert
assert response.status_code == 200
assert response.json()["users"] == 1
assert "users" not in response.json()
assert response.json()["solutions"] == 1


Expand Down
13 changes: 7 additions & 6 deletions sdk/longlink/database/companies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion sdk/tests/database/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
1 change: 0 additions & 1 deletion web/src/lib/generated/platform-api-v1/zod.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
7 changes: 7 additions & 0 deletions web/src/platform/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,13 @@ export function canAdminister(role: z.output<typeof schemas.zOrganizationRoles>)
return role === 'admin' || role === 'owner';
}

export function canManageMember(
caller: z.output<typeof schemas.zOrganizationRoles>,
target: z.output<typeof schemas.zOrganizationRoles>
): boolean {
return canAdminister(caller) && (caller === 'owner' || target !== 'owner');
}

/** Identifies organization roles allowed to maintain Solutions, registries, and invitations. */
export function canMaintain(role: z.output<typeof schemas.zOrganizationRoles>): boolean {
return role === 'maintain' || canAdminister(role);
Expand Down
2 changes: 1 addition & 1 deletion web/src/platform/routes/admin/compute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ export default function Compute() {
spacing="sm"
padding="none"
action={searchField}
footer={<DataGridPagination sizes={[25]} />}
footer={<DataGridPagination sizes={[pagination.pageSize]} />}
>
<DataGridScrollArea orientation="horizontal">
<DataGridTable />
Expand Down
2 changes: 1 addition & 1 deletion web/src/platform/routes/admin/operations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export default function Operations() {
spacing="sm"
padding="none"
action={searchField}
footer={<DataGridPagination sizes={[25]} />}
footer={<DataGridPagination sizes={[pagination.pageSize]} />}
>
<DataGridScrollArea orientation="horizontal">
<DataGridTable />
Expand Down
2 changes: 1 addition & 1 deletion web/src/platform/routes/admin/organizations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export default function Organizations() {
spacing="sm"
padding="none"
action={searchField}
footer={<DataGridPagination sizes={[25]} />}
footer={<DataGridPagination sizes={[pagination.pageSize]} />}
>
<DataGridScrollArea orientation="horizontal">
<DataGridTable />
Expand Down
2 changes: 1 addition & 1 deletion web/src/platform/routes/admin/solutions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ export default function Solutions() {
spacing="sm"
padding="none"
action={searchField}
footer={<DataGridPagination sizes={[25]} />}
footer={<DataGridPagination sizes={[pagination.pageSize]} />}
>
<DataGridScrollArea orientation="horizontal">
<DataGridTable />
Expand Down
7 changes: 4 additions & 3 deletions web/src/platform/routes/admin/use-filters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion web/src/platform/routes/admin/users.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export default function Users() {
spacing="sm"
padding="none"
action={searchField}
footer={<DataGridPagination sizes={[25]} />}
footer={<DataGridPagination sizes={[pagination.pageSize]} />}
>
<DataGridScrollArea orientation="horizontal">
<DataGridTable />
Expand Down
17 changes: 10 additions & 7 deletions web/src/platform/routes/orgs/dialogs/create-solution.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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<void>;
onClose: () => void;
}) {
const [stage, setStage] = useState<'image' | 'configure'>('image');
const [inspection, setInspection] = useState<{
source: string;
Expand Down Expand Up @@ -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;
Expand Down
Loading