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
95 changes: 95 additions & 0 deletions api/schema/aimodel_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import strawberry
import strawberry_django
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db.models import QuerySet
from strawberry.types import Info
from strawberry_django.pagination import OffsetPaginationInput

Expand All @@ -21,6 +22,7 @@
AIModelLifecycleStageEnum,
AIModelOrder,
AIModelProviderEnum,
AIModelResponse,
AIModelStatusEnum,
AIModelTypeEnum,
AIModelVersionFilter,
Expand All @@ -34,6 +36,12 @@
TypeVersionProvider,
)
from api.utils.graphql_telemetry import trace_resolver
from api.utils.qs_utils import (
FilterSpec,
SortSpec,
get_pagination_window,
status_counts,
)
from authorization.graphql_permissions import IsAuthenticated
from authorization.models import OrganizationMembership, Role

Expand Down Expand Up @@ -281,6 +289,57 @@ class UpdateVersionProviderInput:
config: Optional[strawberry.scalars.JSON] = None


# Fields a table client may filter or sort on. Explicit allowlists are what
# stop arbitrary columns (and relations) from becoming queryable.
AI_MODELS_TABLE_FILTER_FIELDS = [
"id",
"name",
"display_name",
"status",
"model_type",
"provider",
"domain",
"organization",
"organization__slug",
"sectors__id",
"sectors__slug",
"sectors__name",
"geographies__id",
"geographies__name",
"geographies__code",
"tags__value",
"created_at",
"updated_at",
]
AI_MODELS_TABLE_SORT_FIELDS = [
"name",
"display_name",
"created_at",
"updated_at",
"status",
"model_type",
"provider",
]


def _visible_ai_models(info: Info, include_public: Optional[bool] = False) -> QuerySet:
"""The AI models a caller may list. Same rules as `aiModels`."""
organization = info.context.context.get("organization")
user = info.context.user
public = AIModel.objects.filter(is_public=True, is_active=True)
if organization:
queryset = AIModel.objects.filter(organization=organization)
elif not user.is_authenticated:
queryset = public
elif user.is_superuser:
queryset = AIModel.objects.all()
else:
queryset = AIModel.objects.filter(user=user, organization=None)
if include_public:
queryset = queryset | public
return queryset.distinct()


@strawberry.type
class Query:
"""Queries for AI Models."""
Expand Down Expand Up @@ -330,6 +389,42 @@ def ai_models(

return TypeAIModel.from_django_list(list(queryset))

@strawberry.field
@trace_resolver(name="ai_models_table", attributes={"component": "aimodel"})
def ai_models_table(
self,
info: Info,
filters: Optional[List[FilterSpec]] = None,
sort_options: Optional[List[SortSpec]] = None,
limit: int = 50,
offset: int = 0,
include_public: Optional[bool] = False,
) -> AIModelResponse:
"""AI models for a table UI: client-driven filters, sortable columns and
page controls backed by a real total count.

Additive next to `aiModels`, with the same visibility rules, plus
public, active models when `include_public` is set. Filters are `{field,
condition, value}` and sorts are `{field, direction}`, limited to the
allowlists above; anything else is a GraphQL error naming the allowed
fields. Default order: newest first.
"""
visible = _visible_ai_models(info, include_public)
window = get_pagination_window(
visible,
limit=limit,
offset=offset,
filters=filters,
filtering_allowed_fields=AI_MODELS_TABLE_FILTER_FIELDS,
sort_options=sort_options or [SortSpec(field="created_at", direction="desc")],
sorting_allowed_fields=AI_MODELS_TABLE_SORT_FIELDS,
)
return AIModelResponse(
data=TypeAIModel.from_django_list(window["data"]),
total_items_count=window["total_items_count"],
status_counts=status_counts(visible, filters, AI_MODELS_TABLE_FILTER_FIELDS),
)

@strawberry.field
@trace_resolver(name="get_ai_model", attributes={"component": "aimodel"})
def get_ai_model(self, info: Info, model_id: int) -> Optional[TypeAIModel]:
Expand Down
93 changes: 93 additions & 0 deletions api/schema/collaborative_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import strawberry
import strawberry_django
from django.db import models
from django.db.models import QuerySet
from strawberry import auto
from strawberry.file_uploads import Upload
from strawberry.types import Info
Expand Down Expand Up @@ -37,6 +38,7 @@
from api.types.type_collaborative import (
CollaborativeFilter,
CollaborativeOrder,
CollaborativeResponse,
TypeCollaborative,
)
from api.types.type_collaborative_organization import (
Expand All @@ -48,6 +50,12 @@
from api.types.type_usecase import TypeUseCase
from api.utils.enums import CollaborativeStatus, OrganizationRelationshipType
from api.utils.graphql_telemetry import trace_resolver
from api.utils.qs_utils import (
FilterSpec,
SortSpec,
get_pagination_window,
status_counts,
)
from authorization.models import User
from authorization.types import TypeUser

Expand Down Expand Up @@ -95,6 +103,55 @@ class CollaborativeInputPartial:
completed_on: Optional[datetime.date] = None


# Fields a table client may filter or sort on. Explicit allowlists are what
# stop arbitrary columns (and relations) from becoming queryable.
COLLABORATIVES_TABLE_FILTER_FIELDS = [
"id",
"title",
"status",
"organization",
"organization__slug",
"sectors__id",
"sectors__slug",
"sectors__name",
"geographies__id",
"geographies__name",
"geographies__code",
"tags__value",
"sdgs__code",
"sdgs__slug",
"started_on",
"completed_on",
"created",
"modified",
]
COLLABORATIVES_TABLE_SORT_FIELDS = [
"title",
"created",
"modified",
"status",
"started_on",
"completed_on",
]


def _visible_collaboratives(info: Info, include_public: Optional[bool] = False) -> QuerySet:
"""The collaboratives a caller may list. Same rules as `collaboratives`."""
user = info.context.user
organization = info.context.context.get("organization")
if organization:
queryset = Collaborative.objects.filter(organization=organization)
elif user.is_superuser:
queryset = Collaborative.objects.all()
elif user.is_authenticated:
queryset = Collaborative.objects.filter(user=user)
else:
queryset = Collaborative.objects.filter(status=CollaborativeStatus.PUBLISHED)
if include_public:
queryset = queryset | Collaborative.objects.filter(status=CollaborativeStatus.PUBLISHED)
return queryset.distinct()


@strawberry.type(name="Query")
class Query:
"""Queries for collaboratives."""
Expand Down Expand Up @@ -138,6 +195,42 @@ def collaboratives(

return TypeCollaborative.from_django_list(queryset)

@strawberry.field
@trace_resolver(name="collaboratives_table", attributes={"component": "collaborative"})
def collaboratives_table(
self,
info: Info,
filters: Optional[List[FilterSpec]] = None,
sort_options: Optional[List[SortSpec]] = None,
limit: int = 50,
offset: int = 0,
include_public: Optional[bool] = False,
) -> CollaborativeResponse:
"""Collaboratives for a table UI: client-driven filters, sortable columns and
page controls backed by a real total count.

Additive next to `collaboratives`, with the same visibility rules, plus
published collaboratives when `include_public` is set. Filters are `{field,
condition, value}` and sorts are `{field, direction}`, limited to the
allowlists above; anything else is a GraphQL error naming the allowed
fields. Default order: newest first.
"""
visible = _visible_collaboratives(info, include_public)
window = get_pagination_window(
visible,
limit=limit,
offset=offset,
filters=filters,
filtering_allowed_fields=COLLABORATIVES_TABLE_FILTER_FIELDS,
sort_options=sort_options or [SortSpec(field="created", direction="desc")],
sorting_allowed_fields=COLLABORATIVES_TABLE_SORT_FIELDS,
)
return CollaborativeResponse(
data=TypeCollaborative.from_django_list(window["data"]),
total_items_count=window["total_items_count"],
status_counts=status_counts(visible, filters, COLLABORATIVES_TABLE_FILTER_FIELDS),
)

@strawberry_django.field
@trace_resolver(name="get_published_collaboratives", attributes={"component": "collaborative"})
def published_collaboratives(
Expand Down
16 changes: 4 additions & 12 deletions api/schema/dataset_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@
from api.utils.qs_utils import (
FilterSpec,
SortSpec,
apply_filters,
get_pagination_window,
status_counts,
)
from authorization.models import DatasetPermission, OrganizationMembership, Role, User
from authorization.permissions import (
Expand Down Expand Up @@ -539,20 +539,12 @@ def datasets_table(
sort_options=sort_options or [SortSpec(field="created", direction="desc")],
sorting_allowed_fields=DATASETS_TABLE_SORT_FIELDS,
)
# Tab labels: counts per status under every filter except status itself.
without_status = [f for f in (filters or []) if f.field.strip() != "status"]
status_rows = (
apply_filters(visible, without_status, DATASETS_TABLE_FILTER_FIELDS)
.order_by()
.values("status")
.annotate(n=Count("id", distinct=True))
)
return DatasetResponse(
data=TypeDataset.from_django_list(window["data"]),
total_items_count=window["total_items_count"],
status_counts=[
DatasetStatusCount(status=row["status"], count=row["n"]) for row in status_rows
],
status_counts=status_counts(
visible, filters, DATASETS_TABLE_FILTER_FIELDS, item_type=DatasetStatusCount
),
)

@strawberry.field(
Expand Down
Loading
Loading