AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(backend): add backend support for store listings submissions (#9628)
Nicholas Tindle56663c5fe9f1
diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.pyindex 8fa7a9cf07..45c6fd8d21 100644--- a/autogpt_platform/backend/backend/data/graph.py+++ b/autogpt_platform/backend/backend/data/graph.py@@ -6,6 +6,7 @@ from typing import Any, Literal, Optional, Typeimport prismafrom prisma import Json+from prisma.enums import SubmissionStatusfrom prisma.models import (AgentGraph,AgentGraphExecution,@@ -732,7 +733,7 @@ async def get_graph("agentId": graph_id,"agentVersion": version or graph.version,"isDeleted": False,- "StoreListing": {"is": {"isApproved": True}},+ "submissionStatus": SubmissionStatus.APPROVED,}))@@ -740,7 +741,7 @@ async def get_graph(return Noneif for_export:- sub_graphs = await _get_sub_graphs(graph)+ sub_graphs = await get_sub_graphs(graph)return GraphModel.from_db(graph=graph,sub_graphs=sub_graphs,@@ -750,7 +751,7 @@ async def get_graph(return GraphModel.from_db(graph, for_export)-async def _get_sub_graphs(graph: AgentGraph) -> list[AgentGraph]:+async def get_sub_graphs(graph: AgentGraph) -> list[AgentGraph]:"""Iteratively fetches all sub-graphs of a given graph, and flattens them into a list.This call involves a DB fetch in batch, breadth-first, per-level of graph depth.diff --git a/autogpt_platform/backend/backend/data/notifications.py b/autogpt_platform/backend/backend/data/notifications.pyindex 402a83cdc2..9f2fe3f323 100644--- a/autogpt_platform/backend/backend/data/notifications.py+++ b/autogpt_platform/backend/backend/data/notifications.py@@ -372,7 +372,7 @@ class UserNotificationBatchDTO(BaseModel):type=model.type,notifications=[UserNotificationEventDTO.from_db(notification)- for notification in model.notifications or []+ for notification in model.Notifications or []],created_at=model.createdAt,updated_at=model.updatedAt,@@ -410,7 +410,7 @@ async def create_or_add_to_user_notification_batch("type": notification_type,}},- include={"notifications": True},+ include={"Notifications": True},)if not existing_batch:@@ -427,9 +427,9 @@ async def create_or_add_to_user_notification_batch(data={"userId": user_id,"type": notification_type,- "notifications": {"connect": [{"id": notification_event.id}]},+ "Notifications": {"connect": [{"id": notification_event.id}]},},- include={"notifications": True},+ include={"Notifications": True},)return UserNotificationBatchDTO.from_db(resp)else:@@ -445,9 +445,9 @@ async def create_or_add_to_user_notification_batch(resp = await tx.usernotificationbatch.update(where={"id": existing_batch.id},data={- "notifications": {"connect": [{"id": notification_event.id}]}+ "Notifications": {"connect": [{"id": notification_event.id}]}},- include={"notifications": True},+ include={"Notifications": True},)if not resp:raise DatabaseError(@@ -467,13 +467,13 @@ async def get_user_notification_oldest_message_in_batch(try:batch = await UserNotificationBatch.prisma().find_first(where={"userId": user_id, "type": notification_type},- include={"notifications": True},+ include={"Notifications": True},)if not batch:return None- if not batch.notifications:+ if not batch.Notifications:return None- sorted_notifications = sorted(batch.notifications, key=lambda x: x.createdAt)+ sorted_notifications = sorted(batch.Notifications, key=lambda x: x.createdAt)return (UserNotificationEventDTO.from_db(sorted_notifications[0])@@ -518,7 +518,7 @@ async def get_user_notification_batch(try:batch = await UserNotificationBatch.prisma().find_first(where={"userId": user_id, "type": notification_type},- include={"notifications": True},+ include={"Notifications": True},)return UserNotificationBatchDTO.from_db(batch) if batch else Noneexcept Exception as e:@@ -534,11 +534,11 @@ async def get_all_batches_by_type(batches = await UserNotificationBatch.prisma().find_many(where={"type": notification_type,- "notifications": {+ "Notifications": {"some": {} # Only return batches with at least one notification},},- include={"notifications": True},+ include={"Notifications": True},)return [UserNotificationBatchDTO.from_db(batch) for batch in batches]except Exception as e:diff --git a/autogpt_platform/backend/backend/server/rest_api.py b/autogpt_platform/backend/backend/server/rest_api.pyindex 40d25563e4..e054cfebf8 100644--- a/autogpt_platform/backend/backend/server/rest_api.py+++ b/autogpt_platform/backend/backend/server/rest_api.py@@ -11,6 +11,7 @@ from autogpt_libs.feature_flag.client import (initialize_launchdarkly,shutdown_launchdarkly,)+from prisma.enums import SubmissionStatusimport backend.data.blockimport backend.data.db@@ -23,6 +24,7 @@ import backend.server.v2.library.modelimport backend.server.v2.library.routesimport backend.server.v2.otto.routesimport backend.server.v2.postmark.postmark+import backend.server.v2.store.admin_routesimport backend.server.v2.store.modelimport backend.server.v2.store.routesimport backend.util.service@@ -99,6 +101,11 @@ app.include_router(backend.server.routers.v1.v1_router, tags=["v1"], prefix="/apapp.include_router(backend.server.v2.store.routes.router, tags=["v2"], prefix="/api/store")+app.include_router(+ backend.server.v2.store.admin_routes.router,+ tags=["v2", "admin"],+ prefix="/api/store",+)app.include_router(backend.server.v2.library.routes.router, tags=["v2"], prefix="/api/library")@@ -250,12 +257,53 @@ class AgentServer(backend.util.service.AppProcess):):return await backend.server.v2.store.routes.create_submission(request, user_id)+ ### ADMIN ###+ @staticmethod+ async def test_get_store_submissions(+ status: SubmissionStatus | None = None,+ search: str | None = None,+ page: int = 1,+ page_size: int = 20,+ ):+ return await backend.server.v2.store.admin_routes.get_submissions(+ status, search, page, page_size+ )++ @staticmethod+ async def test_get_pending_store_submissions(+ page: int = 1,+ page_size: int = 20,+ ):+ return await backend.server.v2.store.admin_routes.get_pending_submissions(+ page, page_size+ )++ @staticmethod+ async def test_get_store_submission_details(+ store_listing_version_id: str,+ ):+ return await backend.server.v2.store.admin_routes.get_submission_details(+ store_listing_version_id+ )++ @staticmethod+ async def test_get_listing_history(+ listing_id: str,+ page: int = 1,+ page_size: int = 20,+ ):+ return await backend.server.v2.store.admin_routes.get_listing_history(+ listing_id, page, page_size+ )+@staticmethodasync def test_review_store_listing(request: backend.server.v2.store.model.ReviewSubmissionRequest,user: autogpt_libs.auth.models.User,):- return await backend.server.v2.store.routes.review_submission(request, user)+ return await backend.server.v2.store.admin_routes.review_submission(+ request.store_listing_version_id, request, user+ )@staticmethoddef test_create_credentials(diff --git a/autogpt_platform/backend/backend/server/v2/library/db_test.py b/autogpt_platform/backend/backend/server/v2/library/db_test.pyindex 87c668bee1..b118fb349c 100644--- a/autogpt_platform/backend/backend/server/v2/library/db_test.py+++ b/autogpt_platform/backend/backend/server/v2/library/db_test.py@@ -1,5 +1,6 @@from datetime import datetime+import prisma.enumsimport prisma.errorsimport prisma.modelsimport pytest@@ -91,7 +92,6 @@ async def test_add_agent_to_library(mocker):updatedAt=datetime.now(),agentId="agent1",agentVersion=1,- slug="test-agent",name="Test Agent",subHeading="Test Agent Subheading",imageUrls=["https://example.com/image.jpg"],@@ -100,7 +100,8 @@ async def test_add_agent_to_library(mocker):isFeatured=False,isDeleted=False,isAvailable=True,- isApproved=True,+ storeListingId="listing123",+ submissionStatus=prisma.enums.SubmissionStatus.APPROVED,Agent=prisma.models.AgentGraph(id="agent1",version=1,diff --git a/autogpt_platform/backend/backend/server/v2/store/admin_routes.py b/autogpt_platform/backend/backend/server/v2/store/admin_routes.pynew file mode 100644index 0000000000..2c9273ffe4--- /dev/null+++ b/autogpt_platform/backend/backend/server/v2/store/admin_routes.py@@ -0,0 +1,207 @@+import logging+import typing++import autogpt_libs.auth.depends+import fastapi+import fastapi.responses+import prisma.enums++import backend.server.v2.store.db+import backend.server.v2.store.exceptions+import backend.server.v2.store.model++logger = logging.getLogger(__name__)++router = fastapi.APIRouter(prefix="/admin", tags=["store", "admin"])+++ "/submissions",+ response_model=backend.server.v2.store.model.StoreSubmissionsResponse,+ dependencies=[fastapi.Depends(autogpt_libs.auth.depends.requires_admin_user)],+)+async def get_submissions(+ status: typing.Optional[prisma.enums.SubmissionStatus] = None,+ search: typing.Optional[str] = None,+ page: int = 1,+ page_size: int = 20,+):+ """+ Get all store submissions with filtering options.++ Admin only endpoint for managing agent submissions.++ Args:+ status: Filter by submission status (ALL, PENDING, APPROVED, REJECTED)+ search: Search by name, creator, or description+ page: Page number for pagination+ page_size: Number of items per page++ Returns:+ StoreSubmissionsResponse with filtered submissions+ """+ try:+ submissions = await backend.server.v2.store.db.get_admin_submissions(+ status=status,+ search_query=search,+ page=page,+ page_size=page_size,+ )+ return submissions+ except Exception as e:+ logger.exception("Error getting admin submissions: %s", e)+ return fastapi.responses.JSONResponse(+ status_code=500,+ content={"detail": "An error occurred while retrieving submissions"},+ )+++ "/submissions/pending",+ response_model=backend.server.v2.store.model.StoreSubmissionsResponse,+ dependencies=[fastapi.Depends(autogpt_libs.auth.depends.requires_admin_user)],+)+async def get_pending_submissions(+ page: int = 1,+ page_size: int = 20,+):+ """+ Get pending submissions that need admin review.++ Convenience endpoint for the admin dashboard.++ Args:+ page: Page number for pagination+ page_size: Number of items per page++ Returns:+ StoreSubmissionsResponse with pending submissions+ """+ try:+ submissions = await backend.server.v2.store.db.get_pending_submissions(+ page=page,+ page_size=page_size,+ )+ return submissions+ except Exception as e:+ logger.exception("Error getting pending submissions: %s", e)+ return fastapi.responses.JSONResponse(+ status_code=500,+ content={+ "detail": "An error occurred while retrieving pending submissions"+ },+ )+++ "/submissions/{store_listing_version_id}",+ response_model=backend.server.v2.store.model.StoreSubmission,+ dependencies=[fastapi.Depends(autogpt_libs.auth.depends.requires_admin_user)],+)+async def get_submission_details(+ store_listing_version_id: str,+):+ """+ Get detailed information about a specific submission.++ Args:+ store_listing_version_id: ID of the submission version++ Returns:+ StoreSubmission with full details including internal comments+ """+ try:+ submission = await backend.server.v2.store.db.get_submission_details(+ store_listing_version_id=store_listing_version_id,+ )+ return submission+ except backend.server.v2.store.exceptions.SubmissionNotFoundError:+ return fastapi.responses.JSONResponse(+ status_code=404,+ content={"detail": "Submission not found"},+ )+ except Exception as e:+ logger.exception("Error getting submission details: %s", e)+ return fastapi.responses.JSONResponse(+ status_code=500,+ content={"detail": "An error occurred while retrieving submission details"},+ )+++ "/submissions/listing/{listing_id}/history",+ response_model=backend.server.v2.store.model.StoreSubmissionsResponse,+ dependencies=[fastapi.Depends(autogpt_libs.auth.depends.requires_admin_user)],+)+async def get_listing_history(+ listing_id: str,+ page: int = 1,+ page_size: int = 20,+):+ """+ Get all submissions for a specific listing.++ This shows the version history of a listing over time.++ Args:+ listing_id: The ID of the store listing+ page: Page number for pagination+ page_size: Number of items per page++ Returns:+ StoreSubmissionsResponse with all versions of a specific listing+ """+ try:+ submissions = await backend.server.v2.store.db.get_listing_submissions_history(+ listing_id=listing_id,+ page=page,+ page_size=page_size,+ )+ return submissions+ except Exception as e:+ logger.exception("Error getting listing history: %s", e)+ return fastapi.responses.JSONResponse(+ status_code=500,+ content={"detail": "An error occurred while retrieving listing history"},+ )+++ "/submissions/{store_listing_version_id}/review",+ response_model=backend.server.v2.store.model.StoreSubmission,+ dependencies=[fastapi.Depends(autogpt_libs.auth.depends.requires_admin_user)],+)+async def review_submission(+ store_listing_version_id: str,+ request: backend.server.v2.store.model.ReviewSubmissionRequest,+ user: typing.Annotated[+ autogpt_libs.auth.models.User,+ fastapi.Depends(autogpt_libs.auth.depends.requires_admin_user),+ ],+):+ """+ Review a store listing submission.++ Args:+ store_listing_version_id: ID of the submission to review+ request: Review details including approval status and comments+ user: Authenticated admin user performing the review++ Returns:+ StoreSubmission with updated review information+ """+ try:+ submission = await backend.server.v2.store.db.review_store_submission(+ store_listing_version_id=store_listing_version_id,+ is_approved=request.is_approved,+ external_comments=request.comments,+ internal_comments=request.internal_comments or "",+ reviewer_id=user.user_id,+ )+ return submission+ except Exception as e:+ logger.exception("Error reviewing submission: %s", e)+ return fastapi.responses.JSONResponse(+ status_code=500,+ content={"detail": "An error occurred while reviewing the submission"},+ )diff --git a/autogpt_platform/backend/backend/server/v2/store/db.py b/autogpt_platform/backend/backend/server/v2/store/db.pyindex c6cf640319..3b97dee395 100644--- a/autogpt_platform/backend/backend/server/v2/store/db.py+++ b/autogpt_platform/backend/backend/server/v2/store/db.py@@ -1,5 +1,5 @@import logging-from datetime import datetime+from datetime import datetime, timezoneimport fastapiimport prisma.enums@@ -10,7 +10,8 @@ import prisma.typesimport backend.data.graphimport backend.server.v2.store.exceptionsimport backend.server.v2.store.model-from backend.data.graph import GraphModel+from backend.data.graph import GraphModel, get_sub_graphs+from backend.data.includes import AGENT_GRAPH_INCLUDElogger = logging.getLogger(__name__)@@ -43,6 +44,9 @@ async def get_store_agents(page: int = 1,page_size: int = 20,) -> backend.server.v2.store.model.StoreAgentsResponse:+ """+ Get PUBLIC store agents from the StoreAgent view+ """logger.debug(f"Getting store agents. featured={featured}, creator={creator}, sorted_by={sorted_by}, search={search_query}, category={category}, page={page}")@@ -128,6 +132,7 @@ async def get_store_agents(async def get_store_agent_details(username: str, agent_name: str) -> backend.server.v2.store.model.StoreAgentDetails:+ """Get PUBLIC store agent details from the StoreAgent view"""logger.debug(f"Getting store agent details for {username}/{agent_name}")try:@@ -141,6 +146,20 @@ async def get_store_agent_details(f"Agent {username}/{agent_name} not found")+ # Retrieve StoreListing to get active_version_id and has_approved_version+ store_listing = await prisma.models.StoreListing.prisma().find_first(+ where=prisma.types.StoreListingWhereInput(+ slug=agent_name,+ owningUserId=username, # Direct equality check instead of 'has'+ ),+ include={"ActiveVersion": True},+ )++ active_version_id = store_listing.activeVersionId if store_listing else None+ has_approved_version = (+ store_listing.hasApprovedVersion if store_listing else False+ )+logger.debug(f"Found agent details for {username}/{agent_name}")return backend.server.v2.store.model.StoreAgentDetails(store_listing_version_id=agent.storeListingVersionId,@@ -157,6 +176,8 @@ async def get_store_agent_details(rating=agent.rating,versions=agent.versions,last_updated=agent.updated_at,+ active_version_id=active_version_id,+ has_approved_version=has_approved_version,)except backend.server.v2.store.exceptions.AgentNotFoundError:raise@@ -174,6 +195,7 @@ async def get_store_creators(page: int = 1,page_size: int = 20,) -> backend.server.v2.store.model.CreatorsResponse:+ """Get PUBLIC store creators from the Creator view"""logger.debug(f"Getting store creators. featured={featured}, search={search_query}, sorted_by={sorted_by}, page={page}")@@ -321,6 +343,7 @@ async def get_store_creator_details(async def get_store_submissions(user_id: str, page: int = 1, page_size: int = 20) -> backend.server.v2.store.model.StoreSubmissionsResponse:+ """Get store submissions for the authenticated user -- not an admin"""logger.debug(f"Getting store submissions for user {user_id}, page={page}")try:@@ -342,8 +365,9 @@ async def get_store_submissions(total_pages = (total + page_size - 1) // page_size# Convert to response models- submission_models = [- backend.server.v2.store.model.StoreSubmission(+ submission_models = []+ for sub in submissions:+ submission_model = backend.server.v2.store.model.StoreSubmission(agent_id=sub.agent_id,agent_version=sub.agent_version,name=sub.name,@@ -351,13 +375,18 @@ async def get_store_submissions(slug=sub.slug,description=sub.description,image_urls=sub.image_urls or [],- date_submitted=sub.date_submitted or datetime.now(),+ date_submitted=sub.date_submitted or datetime.now(tz=timezone.utc),status=sub.status,runs=sub.runs or 0,rating=sub.rating or 0.0,+ store_listing_version_id=sub.store_listing_version_id,+ reviewer_id=sub.reviewer_id,+ review_comments=sub.review_comments,+ # internal_comments omitted for regular users+ reviewed_at=sub.reviewed_at,+ changes_summary=sub.changes_summary,)- for sub in submissions- ]+ submission_models.append(submission_model)logger.debug(f"Found {len(submission_models)} submissions")return backend.server.v2.store.model.StoreSubmissionsResponse(@@ -389,7 +418,7 @@ async def delete_store_submission(submission_id: str,) -> bool:"""- Delete a store listing submission.+ Delete a store listing submission as the submitting user.Args:user_id: ID of the authenticated user@@ -436,9 +465,10 @@ async def create_store_submission(description: str = "",sub_heading: str = "",categories: list[str] = [],+ changes_summary: str = "Initial Submission",) -> backend.server.v2.store.model.StoreSubmission:"""- Create a new store listing submission.+ Create the first (and only) store listing and thus submission as a normal userArgs:user_id: ID of the authenticated user submitting the listing@@ -449,7 +479,9 @@ async def create_store_submission(video_url: Optional URL to video demoimage_urls: List of image URLs for the listingdescription: Description of the agent+ sub_heading: Optional sub-heading for the agentcategories: List of categories for the agent+ changes_summary: Summary of changes made in this submissionReturns:StoreSubmission: The created store submission@@ -491,33 +523,38 @@ async def create_store_submission()# Create the store listing- listing = await prisma.models.StoreListing.prisma().create(- data={- "agentId": agent_id,- "agentVersion": agent_version,- "owningUserId": user_id,- "createdAt": datetime.now(),- "StoreListingVersions": {- "create": {- "agentId": agent_id,- "agentVersion": agent_version,- "slug": slug,- "name": name,- "videoUrl": video_url,- "imageUrls": image_urls,- "description": description,- "categories": categories,- "subHeading": sub_heading,- }- },+ data = prisma.types.StoreListingCreateInput(+ slug=slug,+ agentId=agent_id,+ agentVersion=agent_version,+ owningUserId=user_id,+ createdAt=datetime.now(tz=timezone.utc),+ Versions={+ "create": [+ prisma.types.StoreListingVersionCreateInput(+ agentId=agent_id,+ agentVersion=agent_version,+ name=name,+ videoUrl=video_url,+ imageUrls=image_urls,+ description=description,+ categories=categories,+ subHeading=sub_heading,+ submissionStatus=prisma.enums.SubmissionStatus.PENDING,+ submittedAt=datetime.now(tz=timezone.utc),+ changesSummary=changes_summary,+ )+ ]},- include={"StoreListingVersions": True},+ )+ listing = await prisma.models.StoreListing.prisma().create(+ data=data,+ include=prisma.types.StoreListingInclude(Versions=True),)store_listing_version_id = (- listing.StoreListingVersions[0].id- if listing.StoreListingVersions is not None- and len(listing.StoreListingVersions) > 0+ listing.Versions[0].id+ if listing.Versions is not None and len(listing.Versions) > 0else None)@@ -536,6 +573,7 @@ async def create_store_submission(runs=0,rating=0.0,store_listing_version_id=store_listing_version_id,+ changes_summary=changes_summary,)except (@@ -556,7 +594,20 @@ async def create_store_review(score: int,comments: str | None = None,) -> backend.server.v2.store.model.StoreReview:+ """Create a review for a store listing as a user to detail their experience"""try:+ data = prisma.types.StoreListingReviewUpsertInput(+ update=prisma.types.StoreListingReviewUpdateInput(+ score=score,+ comments=comments,+ ),+ create=prisma.types.StoreListingReviewCreateInput(+ reviewByUserId=user_id,+ storeListingVersionId=store_listing_version_id,+ score=score,+ comments=comments,+ ),+ )review = await prisma.models.StoreListingReview.prisma().upsert(where={"storeListingVersionId_reviewByUserId": {@@ -564,18 +615,7 @@ async def create_store_review("reviewByUserId": user_id,}},- data={- "create": {- "reviewByUserId": user_id,- "storeListingVersionId": store_listing_version_id,- "score": score,- "comments": comments,- },- "update": {- "score": score,- "comments": comments,- },- },+ data=data,)return backend.server.v2.store.model.StoreReview(@@ -597,7 +637,7 @@ async def get_user_profile(try:profile = await prisma.models.Profile.prisma().find_first(- where={"userId": user_id} # type: ignore+ where={"userId": user_id})if not profile:@@ -702,6 +742,7 @@ async def get_my_agents(page: int = 1,page_size: int = 20,) -> backend.server.v2.store.model.MyAgentsResponse:+ """Get the agents for the authenticated user"""logger.debug(f"Getting my agents for user {user_id}, page={page}")try:@@ -780,15 +821,60 @@ async def get_agent(return graph+#####################################################+################## ADMIN FUNCTIONS ##################+#####################################################+++async def _get_missing_sub_store_listing(+ graph: prisma.models.AgentGraph,+) -> list[prisma.models.AgentGraph]:+ """+ Agent graph can have sub-graphs, and those sub-graphs also need to be store listed.+ This method fetches the sub-graphs, and returns the ones not listed in the store.+ """+ sub_graphs = await get_sub_graphs(graph)+ if not sub_graphs:+ return []++ # Fetch all the sub-graphs that are listed, and return the ones missing.+ store_listed_sub_graphs = {+ (listing.agentId, listing.agentVersion)+ for listing in await prisma.models.StoreListingVersion.prisma().find_many(+ where={+ "OR": [+ {"agentId": sub_graph.id, "agentVersion": sub_graph.version}+ for sub_graph in sub_graphs+ ],+ "submissionStatus": prisma.enums.SubmissionStatus.APPROVED,+ "isDeleted": False,+ }+ )+ }++ return [+ sub_graph+ for sub_graph in sub_graphs+ if (sub_graph.id, sub_graph.version) not in store_listed_sub_graphs+ ]++async def review_store_submission(- store_listing_version_id: str, is_approved: bool, comments: str, reviewer_id: str-) -> prisma.models.StoreListingSubmission:- """Review a store listing submission."""+ store_listing_version_id: str,+ is_approved: bool,+ external_comments: str,+ internal_comments: str,+ reviewer_id: str,+) -> backend.server.v2.store.model.StoreSubmission:+ """Review a store listing submission as an admin."""try:store_listing_version = (await prisma.models.StoreListingVersion.prisma().find_unique(where={"id": store_listing_version_id},- include={"StoreListing": True},+ include={+ "StoreListing": True,+ "Agent": {"include": AGENT_GRAPH_INCLUDE}, # type: ignore+ },))@@ -798,10 +884,34 @@ async def review_store_submission(detail=f"Store listing version {store_listing_version_id} not found",)- if is_approved:+ # If approving, update the listing to indicate it has an approved version+ if is_approved and store_listing_version.Agent:+ heading = f"Sub-graph of {store_listing_version.name}v{store_listing_version.agentVersion}"++ sub_store_listing_versions = [+ prisma.types.StoreListingVersionCreateWithoutRelationsInput(+ agentId=sub_graph.id,+ agentVersion=sub_graph.version,+ name=sub_graph.name or heading,+ submissionStatus=prisma.enums.SubmissionStatus.APPROVED,+ subHeading=heading,+ description=f"{heading}: {sub_graph.description}",+ changesSummary=f"This listing is added as a {heading} / #{store_listing_version.agentId}.",+ isAvailable=False, # Hide sub-graphs from the store by default.+ submittedAt=datetime.now(tz=timezone.utc),+ )+ for sub_graph in await _get_missing_sub_store_listing(+ store_listing_version.Agent+ )+ ]+await prisma.models.StoreListing.prisma().update(where={"id": store_listing_version.StoreListing.id},- data={"isApproved": True},+ data={+ "hasApprovedVersion": True,+ "ActiveVersion": {"connect": {"id": store_listing_version_id}},+ "Versions": {"create": sub_store_listing_versions},+ },)submission_status = (@@ -810,36 +920,355 @@ async def review_store_submission(else prisma.enums.SubmissionStatus.REJECTED)- update_data: prisma.types.StoreListingSubmissionUpdateInput = {- "Status": submission_status,- "reviewComments": comments,+ # Update the version with review information+ update_data: prisma.types.StoreListingVersionUpdateInput = {+ "submissionStatus": submission_status,+ "reviewComments": external_comments,+ "internalComments": internal_comments,"Reviewer": {"connect": {"id": reviewer_id}},"StoreListing": {"connect": {"id": store_listing_version.StoreListing.id}},+ "reviewedAt": datetime.now(tz=timezone.utc),}- create_data: prisma.types.StoreListingSubmissionCreateInput = {- **update_data,- "StoreListingVersion": {"connect": {"id": store_listing_version_id}},- }-- submission = await prisma.models.StoreListingSubmission.prisma().upsert(- where={"storeListingVersionId": store_listing_version_id},- data={- "create": create_data,- "update": update_data,- },+ # Update the version+ submission = await prisma.models.StoreListingVersion.prisma().update(+ where={"id": store_listing_version_id},+ data=update_data,+ include={"StoreListing": True},)if not submission:- raise fastapi.HTTPException( # FIXME: don't return HTTP exceptions here- status_code=404,- detail=f"Store listing submission {store_listing_version_id} not found",+ raise backend.server.v2.store.exceptions.DatabaseError(+ f"Failed to update store listing version {store_listing_version_id}")- return submission+ # Convert to Pydantic model for consistency+ return backend.server.v2.store.model.StoreSubmission(+ agent_id=submission.agentId,+ agent_version=submission.agentVersion,+ name=submission.name,+ sub_heading=submission.subHeading,+ slug=(+ submission.StoreListing.slug+ if hasattr(submission, "storeListing") and submission.StoreListing+ else ""+ ),+ description=submission.description,+ image_urls=submission.imageUrls or [],+ date_submitted=submission.submittedAt or submission.createdAt,+ status=submission.submissionStatus,+ runs=0, # Default values since we don't have this data here+ rating=0.0,+ store_listing_version_id=submission.id,+ reviewer_id=submission.reviewerId,+ review_comments=submission.reviewComments,+ internal_comments=submission.internalComments,+ reviewed_at=submission.reviewedAt,+ changes_summary=submission.changesSummary,+ )except Exception as e:logger.error(f"Could not create store submission review: {e}")raise backend.server.v2.store.exceptions.DatabaseError("Failed to create store submission review") from e+++async def get_admin_submissions(+ status: prisma.enums.SubmissionStatus | None = None,+ search_query: str | None = None,+ page: int = 1,+ page_size: int = 20,+) -> backend.server.v2.store.model.StoreSubmissionsResponse:+ """Get store submissions for admins with filtering options.++ Args:+ status: Filter by submission status (PENDING, APPROVED, REJECTED)+ search_query: Search by name, description, or user email+ page: Page number for pagination+ page_size: Number of items per page++ Returns:+ StoreSubmissionsResponse with submissions including internal comments+ """+ logger.debug(+ f"Getting admin store submissions with status={status}, search={search_query}, page={page}"+ )++ try:+ # Build the where clause+ where = prisma.types.StoreSubmissionWhereInput()+ if status:+ where["status"] = status++ sanitized_query = sanitize_query(search_query)+ if sanitized_query:+ # Find users with matching email first+ matching_users = await prisma.models.User.prisma().find_many(+ where={"email": {"contains": sanitized_query, "mode": "insensitive"}},+ )++ user_ids = [user.id for user in matching_users]++ # Set up the OR conditions to search across multiple fields+ where["OR"] = [+ {"name": {"contains": sanitized_query, "mode": "insensitive"}},+ {"description": {"contains": sanitized_query, "mode": "insensitive"}},+ {"sub_heading": {"contains": sanitized_query, "mode": "insensitive"}},+ ]++ # Add user_id condition if any users matched+ if user_ids:+ where["OR"].append({"user_id": {"in": user_ids}})+ logger.debug(+ f"Found {len(user_ids)} users matching query: {sanitized_query}"+ )++ # Calculate pagination+ skip = (page - 1) * page_size++ # Query submissions from database - use the StoreSubmission view+ submissions = await prisma.models.StoreSubmission.prisma().find_many(+ where=where,+ skip=skip,+ take=page_size,+ order=[{"date_submitted": "desc"}],+ )++ # Get total count for pagination+ total = await prisma.models.StoreSubmission.prisma().count(where=where)+ total_pages = (total + page_size - 1) // page_size++ # Convert to response models - using all fields for admins+ submission_models = []+ for sub in submissions:+ submission_model = backend.server.v2.store.model.StoreSubmission(+ agent_id=sub.agent_id,+ agent_version=sub.agent_version,+ name=sub.name,+ sub_heading=sub.sub_heading,+ slug=sub.slug,+ description=sub.description,+ image_urls=sub.image_urls or [],+ date_submitted=sub.date_submitted or datetime.now(tz=timezone.utc),+ status=sub.status,+ runs=sub.runs or 0,+ rating=sub.rating or 0.0,+ store_listing_version_id=sub.store_listing_version_id,+ reviewer_id=sub.reviewer_id,+ review_comments=sub.review_comments,+ internal_comments=sub.internal_comments,+ reviewed_at=sub.reviewed_at,+ changes_summary=sub.changes_summary,+ )+ submission_models.append(submission_model)++ logger.debug(f"Found {len(submission_models)} submissions for admin")+ return backend.server.v2.store.model.StoreSubmissionsResponse(+ submissions=submission_models,+ pagination=backend.server.v2.store.model.Pagination(+ current_page=page,+ total_items=total,+ total_pages=total_pages,+ page_size=page_size,+ ),+ )+ except Exception as e:+ logger.error(f"Error fetching admin store submissions: {e}")+ # Return empty response rather than exposing internal errors+ return backend.server.v2.store.model.StoreSubmissionsResponse(+ submissions=[],+ pagination=backend.server.v2.store.model.Pagination(+ current_page=page,+ total_items=0,+ total_pages=0,+ page_size=page_size,+ ),+ )+++async def get_listing_submissions_history(+ listing_id: str,+ page: int = 1,+ page_size: int = 20,+) -> backend.server.v2.store.model.StoreSubmissionsResponse:+ """Get all submissions for a specific listing for admins.++ Args:+ listing_id: The ID of the store listing+ page: Page number for pagination+ page_size: Number of items per page++ Returns:+ StoreSubmissionsResponse with all versions of a specific listing+ """+ logger.debug(f"Getting submission history for listing {listing_id}")++ try:+ # Query StoreListingVersion directly since we need all versions for a listing+ versions = await prisma.models.StoreListingVersion.prisma().find_many(+ where={"storeListingId": listing_id},+ order=[{"version": "desc"}],+ skip=(page - 1) * page_size,+ take=page_size,+ include={"StoreListing": True},+ )++ # Get total count for pagination+ total = await prisma.models.StoreListingVersion.prisma().count(+ where={"storeListingId": listing_id}+ )+ total_pages = (total + page_size - 1) // page_size++ # Convert to StoreSubmission models+ submissions = []+ for version in versions:+ if not version.StoreListing:+ continue++ submissions.append(+ backend.server.v2.store.model.StoreSubmission(+ agent_id=version.agentId,+ agent_version=version.agentVersion,+ name=version.name,+ sub_heading=version.subHeading,+ slug=version.StoreListing.slug,+ description=version.description,+ image_urls=version.imageUrls or [],+ date_submitted=version.submittedAt or version.createdAt,+ status=version.submissionStatus,+ runs=0, # We don't have this data here+ rating=0.0, # We don't have this data here+ store_listing_version_id=version.id,+ reviewer_id=version.reviewerId,+ review_comments=version.reviewComments,+ internal_comments=version.internalComments,+ reviewed_at=version.reviewedAt,+ changes_summary=version.changesSummary,+ )+ )++ logger.debug(+ f"Found {len(submissions)} version history for listing {listing_id}"+ )+ return backend.server.v2.store.model.StoreSubmissionsResponse(+ submissions=submissions,+ pagination=backend.server.v2.store.model.Pagination(+ current_page=page,+ total_items=total,+ total_pages=total_pages,+ page_size=page_size,+ ),+ )+ except Exception as e:+ logger.error(f"Error fetching listing submission history: {e}")+ return backend.server.v2.store.model.StoreSubmissionsResponse(+ submissions=[],+ pagination=backend.server.v2.store.model.Pagination(+ current_page=page,+ total_items=0,+ total_pages=0,+ page_size=page_size,+ ),+ )+++async def get_pending_submissions(+ page: int = 1,+ page_size: int = 20,+) -> backend.server.v2.store.model.StoreSubmissionsResponse:+ """Convenience function to get pending submissions for the admin dashboard.++ Args:+ page: Page number for pagination+ page_size: Number of items per page++ Returns:+ StoreSubmissionsResponse with submissions that need review+ """+ return await get_admin_submissions(+ status=prisma.enums.SubmissionStatus.PENDING,+ page=page,+ page_size=page_size,+ )+++async def get_submission_details(+ store_listing_version_id: str,+) -> backend.server.v2.store.model.StoreSubmission:+ """Get detailed information about a specific submission for admins.++ Args:+ store_listing_version_id: ID of the submission version++ Returns:+ StoreSubmission with full details including internal comments+ """+ logger.debug(f"Getting submission details for {store_listing_version_id}")++ try:+ # First try getting from the view for efficiency+ submission = await prisma.models.StoreSubmission.prisma().find_first(+ where={"store_listing_version_id": store_listing_version_id}+ )++ if submission:+ return backend.server.v2.store.model.StoreSubmission(+ agent_id=submission.agent_id,+ agent_version=submission.agent_version,+ name=submission.name,+ sub_heading=submission.sub_heading,+ slug=submission.slug,+ description=submission.description,+ image_urls=submission.image_urls or [],+ date_submitted=submission.date_submitted+ or datetime.now(tz=timezone.utc),+ status=submission.status,+ runs=submission.runs or 0,+ rating=submission.rating or 0.0,+ store_listing_version_id=submission.store_listing_version_id,+ reviewer_id=submission.reviewer_id,+ review_comments=submission.review_comments,+ internal_comments=submission.internal_comments,+ reviewed_at=submission.reviewed_at,+ changes_summary=submission.changes_summary,+ )++ # If not found in the view, try getting it directly+ version = await prisma.models.StoreListingVersion.prisma().find_unique(+ where={"id": store_listing_version_id},+ include={"StoreListing": True},+ )++ if not version or not version.StoreListing:+ raise backend.server.v2.store.exceptions.SubmissionNotFoundError(+ f"Submission {store_listing_version_id} not found"+ )++ return backend.server.v2.store.model.StoreSubmission(+ agent_id=version.agentId,+ agent_version=version.agentVersion,+ name=version.name,+ sub_heading=version.subHeading,+ slug=version.StoreListing.slug,+ description=version.description,+ image_urls=version.imageUrls or [],+ date_submitted=version.submittedAt or version.createdAt,+ status=version.submissionStatus,+ runs=0, # We don't have this data here+ rating=0.0, # We don't have this data here+ store_listing_version_id=version.id,+ reviewer_id=version.reviewerId,+ review_comments=version.reviewComments,+ internal_comments=version.internalComments,+ reviewed_at=version.reviewedAt,+ changes_summary=version.changesSummary,+ )++ except backend.server.v2.store.exceptions.SubmissionNotFoundError:+ raise+ except Exception as e:+ logger.error(f"Error fetching submission details: {e}")+ raise backend.server.v2.store.exceptions.DatabaseError(+ "Failed to fetch submission details"+ ) from ediff --git a/autogpt_platform/backend/backend/server/v2/store/db_test.py b/autogpt_platform/backend/backend/server/v2/store/db_test.pyindex 4607318e89..1eb8e389f2 100644--- a/autogpt_platform/backend/backend/server/v2/store/db_test.py+++ b/autogpt_platform/backend/backend/server/v2/store/db_test.py@@ -1,5 +1,6 @@from datetime import datetime+import prisma.enumsimport prisma.errorsimport prisma.modelsimport pytest@@ -83,21 +84,35 @@ async def test_get_store_agent_details(mocker):updated_at=datetime.now(),)- # Mock prisma call+ # Create a mock StoreListing result+ mock_store_listing = mocker.MagicMock()+ mock_store_listing.activeVersionId = "active-version-id"+ mock_store_listing.hasApprovedVersion = True++ # Mock StoreAgent prisma callmock_store_agent = mocker.patch("prisma.models.StoreAgent.prisma")mock_store_agent.return_value.find_first = mocker.AsyncMock(return_value=mock_agent)+ # Mock StoreListing prisma call - this is what was missing+ mock_store_listing_db = mocker.patch("prisma.models.StoreListing.prisma")+ mock_store_listing_db.return_value.find_first = mocker.AsyncMock(+ return_value=mock_store_listing+ )+# Call functionresult = await db.get_store_agent_details("creator", "test-agent")# Verify resultsassert result.slug == "test-agent"assert result.agent_name == "Test Agent"+ assert result.active_version_id == "active-version-id"+ assert result.has_approved_version is True- # Verify mock called correctly+ # Verify mocks called correctlymock_store_agent.return_value.find_first.assert_called_once_with(where={"creator_username": "creator", "slug": "test-agent"})+ mock_store_listing_db.return_value.find_first.assert_called_once()@pytest.mark.asyncio@@ -153,16 +168,16 @@ async def test_create_store_submission(mocker):createdAt=datetime.now(),updatedAt=datetime.now(),isDeleted=False,- isApproved=False,+ hasApprovedVersion=False,+ slug="test-agent",agentId="agent-id",agentVersion=1,owningUserId="user-id",- StoreListingVersions=[+ Versions=[prisma.models.StoreListingVersion(id="version-id",agentId="agent-id",agentVersion=1,- slug="test-agent",name="Test Agent",description="Test description",createdAt=datetime.now(),@@ -173,8 +188,9 @@ async def test_create_store_submission(mocker):isFeatured=False,isDeleted=False,version=1,+ storeListingId="listing-id",+ submissionStatus=prisma.enums.SubmissionStatus.PENDING,isAvailable=True,- isApproved=False,)],)diff --git a/autogpt_platform/backend/backend/server/v2/store/model.py b/autogpt_platform/backend/backend/server/v2/store/model.pyindex 9ed564dc53..eaf3137143 100644--- a/autogpt_platform/backend/backend/server/v2/store/model.py+++ b/autogpt_platform/backend/backend/server/v2/store/model.py@@ -67,6 +67,9 @@ class StoreAgentDetails(pydantic.BaseModel):versions: list[str]last_updated: datetime.datetime+ active_version_id: str | None = None+ has_approved_version: bool = False+class Creator(pydantic.BaseModel):name: str@@ -118,6 +121,12 @@ class StoreSubmission(pydantic.BaseModel):rating: floatstore_listing_version_id: str | None = None+ reviewer_id: str | None = None+ review_comments: str | None = None # External comments visible to creator+ internal_comments: str | None = None # Private notes for admin use only+ reviewed_at: datetime.datetime | None = None+ changes_summary: str | None = None+class StoreSubmissionsResponse(pydantic.BaseModel):submissions: list[StoreSubmission]@@ -134,6 +143,7 @@ class StoreSubmissionRequest(pydantic.BaseModel):image_urls: list[str] = []description: str = ""categories: list[str] = []+ changes_summary: str | None = Noneclass ProfileDetails(pydantic.BaseModel):@@ -158,4 +168,5 @@ class StoreReviewCreate(pydantic.BaseModel):class ReviewSubmissionRequest(pydantic.BaseModel):store_listing_version_id: stris_approved: bool- comments: str+ comments: str # External comments visible to creator+ internal_comments: str | None = None # Private admin notesdiff --git a/autogpt_platform/backend/backend/server/v2/store/routes.py b/autogpt_platform/backend/backend/server/v2/store/routes.pyindex 3b7455f884..7bbd81ea53 100644--- a/autogpt_platform/backend/backend/server/v2/store/routes.py+++ b/autogpt_platform/backend/backend/server/v2/store/routes.py@@ -34,7 +34,7 @@ router = fastapi.APIRouter()async def get_profile(user_id: typing.Annotated[str, fastapi.Depends(autogpt_libs.auth.depends.get_user_id)- ]+ ],):"""Get the profile details for the authenticated user.@@ -338,7 +338,7 @@ async def get_creator(async def get_my_agents(user_id: typing.Annotated[str, fastapi.Depends(autogpt_libs.auth.depends.get_user_id)- ]+ ],):try:agents = await backend.server.v2.store.db.get_my_agents(user_id)@@ -466,7 +466,7 @@ async def create_submission(HTTPException: If there is an error creating the submission"""try:- submission = await backend.server.v2.store.db.create_store_submission(+ return await backend.server.v2.store.db.create_store_submission(user_id=user_id,agent_id=submission_request.agent_id,agent_version=submission_request.agent_version,@@ -477,8 +477,8 @@ async def create_submission(description=submission_request.description,sub_heading=submission_request.sub_heading,categories=submission_request.categories,+ changes_summary=submission_request.changes_summary or "Initial Submission",)- return submissionexcept Exception:logger.exception("Exception occurred whilst creating store submission")return fastapi.responses.JSONResponse(@@ -626,31 +626,3 @@ async def download_agent_file(return fastapi.responses.FileResponse(tmp_file.name, filename=file_name, media_type="application/json")--- "/submissions/review/{store_listing_version_id}",- tags=["store", "private"],-)-async def review_submission(- request: backend.server.v2.store.model.ReviewSubmissionRequest,- user: typing.Annotated[- autogpt_libs.auth.models.User,- fastapi.Depends(autogpt_libs.auth.depends.requires_admin_user),- ],-):- # Proceed with the review submission logic- try:- submission = await backend.server.v2.store.db.review_store_submission(- store_listing_version_id=request.store_listing_version_id,- is_approved=request.is_approved,- comments=request.comments,- reviewer_id=user.user_id,- )- return submission- except Exception as e:- logger.error(f"Could not create store submission review: {e}")- raise fastapi.HTTPException(- status_code=500,- detail="An error occurred while creating the store submission review",- )diff --git a/autogpt_platform/backend/migrations/20250318043016_update_store_submissions_format/migration.sql b/autogpt_platform/backend/migrations/20250318043016_update_store_submissions_format/migration.sqlnew file mode 100644index 0000000000..c8c7edac70--- /dev/null+++ b/autogpt_platform/backend/migrations/20250318043016_update_store_submissions_format/migration.sql@@ -0,0 +1,372 @@+/*+ Warnings:++ - The enum type "SubmissionStatus" will be replaced. The 'DAFT' value is removed, so any data using 'DAFT' will be updated to 'DRAFT'. If there are rows still expecting 'DAFT' after this change, it will fail.+ - You are about to drop the column "isApproved" on the "StoreListing" table. All the data in that column will be lost.+ - You are about to drop the column "slug" on the "StoreListingVersion" table. All the data in that column will be lost.+ - You are about to drop the "StoreListingSubmission" table. Data in that table (beyond what is copied over) will be permanently lost.+ - A unique constraint covering the column "activeVersionId" on the "StoreListing" table will be added. If duplicates already exist, this will fail.+ - A unique constraint covering the columns ("storeListingId","version") on "StoreListingVersion" will be added. If duplicates already exist, this will fail.+ - The "storeListingId" column on "StoreListingVersion" is set to NOT NULL. If any rows currently have a NULL value, this step will fail.+ - The views "StoreSubmission", "StoreAgent", and "Creator" are dropped and recreated. Any usage or references to them will be momentarily disrupted until the views are recreated.+*/++BEGIN;++-- First, drop all views that depend on the columns and types we're modifying+DROP VIEW IF EXISTS "StoreSubmission";+DROP VIEW IF EXISTS "StoreAgent";+DROP VIEW IF EXISTS "Creator";++-- Create the new enum type+CREATE TYPE "SubmissionStatus_new" AS ENUM ('DRAFT', 'PENDING', 'APPROVED', 'REJECTED');++-- Modify the column with the correct casing (Status with capital S)+ALTER TABLE "StoreListingSubmission" ALTER COLUMN "Status" DROP DEFAULT;+ALTER TABLE "StoreListingSubmission"+ ALTER COLUMN "Status" TYPE "SubmissionStatus_new"+ USING (+ CASE WHEN "Status"::text = 'DAFT' THEN 'DRAFT'::text+ ELSE "Status"::text+ END+ )::"SubmissionStatus_new";++-- Rename the enum types+ALTER TYPE "SubmissionStatus" RENAME TO "SubmissionStatus_old";+ALTER TYPE "SubmissionStatus_new" RENAME TO "SubmissionStatus";+DROP TYPE "SubmissionStatus_old";++-- Set default back+ALTER TABLE "StoreListingSubmission" ALTER COLUMN "Status" SET DEFAULT 'PENDING';++-- Drop constraints+ALTER TABLE "StoreListingSubmission" DROP CONSTRAINT IF EXISTS "StoreListingSubmission_reviewerId_fkey";++-- Drop indexes+DROP INDEX IF EXISTS "StoreListing_isDeleted_isApproved_idx";+DROP INDEX IF EXISTS "StoreListingSubmission_storeListingVersionId_key";++-- Modify StoreListing+ALTER TABLE "StoreListing"+ DROP COLUMN IF EXISTS "isApproved",+ ADD COLUMN IF NOT EXISTS "activeVersionId" TEXT,+ ADD COLUMN IF NOT EXISTS "hasApprovedVersion" BOOLEAN NOT NULL DEFAULT false,+ ADD COLUMN IF NOT EXISTS "slug" TEXT;++-- First add ALL columns to StoreListingVersion (including the submissionStatus column)+ALTER TABLE "StoreListingVersion"+ ADD COLUMN IF NOT EXISTS "reviewerId" TEXT,+ ADD COLUMN IF NOT EXISTS "reviewComments" TEXT,+ ADD COLUMN IF NOT EXISTS "internalComments" TEXT,+ ADD COLUMN IF NOT EXISTS "reviewedAt" TIMESTAMP(3),+ ADD COLUMN IF NOT EXISTS "changesSummary" TEXT,+ ADD COLUMN IF NOT EXISTS "submissionStatus" "SubmissionStatus" NOT NULL DEFAULT 'DRAFT',+ ADD COLUMN IF NOT EXISTS "submittedAt" TIMESTAMP(3),+ ALTER COLUMN "storeListingId" SET NOT NULL;++-- NOW copy data from StoreListingSubmission to StoreListingVersion+DO $$+BEGIN+ -- First, check what columns actually exist in the StoreListingSubmission table+ DECLARE+ has_reviewerId BOOLEAN := (+ SELECT EXISTS (+ SELECT FROM information_schema.columns+ WHERE table_name = 'StoreListingSubmission'+ AND column_name = 'reviewerId'+ )+ );++ has_reviewComments BOOLEAN := (+ SELECT EXISTS (+ SELECT FROM information_schema.columns+ WHERE table_name = 'StoreListingSubmission'+ AND column_name = 'reviewComments'+ )+ );++ has_changesSummary BOOLEAN := (+ SELECT EXISTS (+ SELECT FROM information_schema.columns+ WHERE table_name = 'StoreListingSubmission'+ AND column_name = 'changesSummary'+ )+ );+ BEGIN+ -- Only copy fields that we know exist+ IF has_reviewerId THEN+ UPDATE "StoreListingVersion" AS v+ SET "reviewerId" = s."reviewerId"+ FROM "StoreListingSubmission" AS s+ WHERE v."id" = s."storeListingVersionId";+ END IF;++ IF has_reviewComments THEN+ UPDATE "StoreListingVersion" AS v+ SET "reviewComments" = s."reviewComments"+ FROM "StoreListingSubmission" AS s+ WHERE v."id" = s."storeListingVersionId";+ END IF;++ IF has_changesSummary THEN+ UPDATE "StoreListingVersion" AS v+ SET "changesSummary" = s."changesSummary"+ FROM "StoreListingSubmission" AS s+ WHERE v."id" = s."storeListingVersionId";+ END IF;+ END;++ -- Update submission status based on StoreListingSubmission status+ UPDATE "StoreListingVersion" AS v+ SET "submissionStatus" = s."Status"+ FROM "StoreListingSubmission" AS s+ WHERE v."id" = s."storeListingVersionId";++ -- Update reviewedAt timestamps for versions with APPROVED or REJECTED status+ UPDATE "StoreListingVersion" AS v+ SET "reviewedAt" = s."updatedAt"+ FROM "StoreListingSubmission" AS s+ WHERE v."id" = s."storeListingVersionId"+ AND s."Status" IN ('APPROVED', 'REJECTED');+END;+$$;++-- Drop the StoreListingSubmission table+DROP TABLE IF EXISTS "StoreListingSubmission";++-- Copy slugs from StoreListingVersion to StoreListing+WITH latest_versions AS (+ SELECT+ "storeListingId",+ "slug",+ ROW_NUMBER() OVER (PARTITION BY "storeListingId" ORDER BY "version" DESC) as rn+ FROM "StoreListingVersion"+)+UPDATE "StoreListing" sl+SET "slug" = lv."slug"+FROM latest_versions lv+WHERE sl."id" = lv."storeListingId"+ AND lv.rn = 1;++-- Make StoreListing.slug required and unique+ALTER TABLE "StoreListing" ALTER COLUMN "slug" SET NOT NULL;+CREATE UNIQUE INDEX "StoreListing_owningUserId_slug_key" ON "StoreListing"("owningUserId", "slug");+DROP INDEX "StoreListing_owningUserId_idx";++-- Drop the slug column from StoreListingVersion since it's now on StoreListing+ALTER TABLE "StoreListingVersion" DROP COLUMN "slug";++-- Update both sides of the relation from one-to-one to one-to-many+-- The AgentGraph->StoreListingVersion relationship is now one-to-many++-- Drop the unique constraint but add a non-unique index for query performance+ALTER TABLE "StoreListingVersion" DROP CONSTRAINT IF EXISTS "StoreListingVersion_agentId_agentVersion_key";+CREATE INDEX IF NOT EXISTS "StoreListingVersion_agentId_agentVersion_idx"+ ON "StoreListingVersion"("agentId", "agentVersion");++-- Set isApproved based on submissionStatus before removing it+UPDATE "StoreListingVersion"+SET "submissionStatus" = 'APPROVED'+WHERE "isApproved" = true;++-- Drop the isApproved column from StoreListingVersion since it's redundant with submissionStatus+ALTER TABLE "StoreListingVersion" DROP COLUMN "isApproved";++-- Initialize hasApprovedVersion for existing StoreListing rows ***+-- This sets "hasApprovedVersion" = TRUE for any StoreListing+-- that has at least one corresponding version with "APPROVED" status.+UPDATE "StoreListing" sl+SET "hasApprovedVersion" = (+ SELECT COUNT(*) > 0+ FROM "StoreListingVersion" slv+ WHERE slv."storeListingId" = sl.id+ AND slv."submissionStatus" = 'APPROVED'+ AND sl."agentId" = slv."agentId"+ AND sl."agentVersion" = slv."agentVersion"+);++-- Create new indexes+CREATE UNIQUE INDEX IF NOT EXISTS "StoreListing_activeVersionId_key"+ ON "StoreListing"("activeVersionId");++CREATE INDEX IF NOT EXISTS "StoreListing_isDeleted_hasApprovedVersion_idx"+ ON "StoreListing"("isDeleted", "hasApprovedVersion");++CREATE INDEX IF NOT EXISTS "StoreListingVersion_storeListingId_submissionStatus_isAvailable_idx"+ ON "StoreListingVersion"("storeListingId", "submissionStatus", "isAvailable");++CREATE INDEX IF NOT EXISTS "StoreListingVersion_submissionStatus_idx"+ ON "StoreListingVersion"("submissionStatus");++CREATE UNIQUE INDEX IF NOT EXISTS "StoreListingVersion_storeListingId_version_key"+ ON "StoreListingVersion"("storeListingId", "version");++-- Add foreign keys+ALTER TABLE "StoreListing"+ADD CONSTRAINT "StoreListing_activeVersionId_fkey"+FOREIGN KEY ("activeVersionId") REFERENCES "StoreListingVersion"("id")+ON DELETE SET NULL ON UPDATE CASCADE;++-- Add reviewer foreign key+ALTER TABLE "StoreListingVersion"+ADD CONSTRAINT "StoreListingVersion_reviewerId_fkey"+FOREIGN KEY ("reviewerId") REFERENCES "User"("id")+ON DELETE SET NULL ON UPDATE CASCADE;++-- Add index for reviewer+CREATE INDEX IF NOT EXISTS "StoreListingVersion_reviewerId_idx"+ ON "StoreListingVersion"("reviewerId");++-- DropIndex+DROP INDEX "StoreListingVersion_agentId_agentVersion_key";++-- RenameIndex+ALTER INDEX "StoreListingVersion_storeListingId_submissionStatus_isAvailable_idx"+RENAME TO "StoreListingVersion_storeListingId_submissionStatus_isAvail_idx";++-- Recreate the views with updated column references++-- 1. Recreate StoreSubmission view+CREATE VIEW "StoreSubmission" AS+SELECT+ sl.id AS listing_id,+ sl."owningUserId" AS user_id,+ slv."agentId" AS agent_id,+ slv.version AS agent_version,+ sl.slug,+ COALESCE(slv.name, '') AS name,+ slv."subHeading" AS sub_heading,+ slv.description,+ slv."imageUrls" AS image_urls,+ slv."submittedAt" AS date_submitted,+ slv."submissionStatus" AS status,+ COALESCE(ar.run_count, 0::bigint) AS runs,+ COALESCE(avg(sr.score::numeric), 0.0)::double precision AS rating,+ -- Add the additional fields needed by the Pydantic model+ slv.id AS store_listing_version_id,+ slv."reviewerId" AS reviewer_id,+ slv."reviewComments" AS review_comments,+ slv."internalComments" AS internal_comments,+ slv."reviewedAt" AS reviewed_at,+ slv."changesSummary" AS changes_summary+FROM "StoreListing" sl+ JOIN "StoreListingVersion" slv ON slv."storeListingId" = sl.id+ LEFT JOIN "StoreListingReview" sr ON sr."storeListingVersionId" = slv.id+ LEFT JOIN (+ SELECT "AgentGraphExecution"."agentGraphId", count(*) AS run_count+ FROM "AgentGraphExecution"+ GROUP BY "AgentGraphExecution"."agentGraphId"+ ) ar ON ar."agentGraphId" = slv."agentId"+WHERE sl."isDeleted" = false+GROUP BY sl.id, sl."owningUserId", slv.id, slv."agentId", slv.version, sl.slug, slv.name,+ slv."subHeading", slv.description, slv."imageUrls", slv."submittedAt",+ slv."submissionStatus", slv."reviewerId", slv."reviewComments", slv."internalComments",+ slv."reviewedAt", slv."changesSummary", ar.run_count;++-- 2. Recreate StoreAgent view+CREATE VIEW "StoreAgent" AS+WITH reviewstats AS (+ SELECT sl_1.id AS "storeListingId",+ count(sr.id) AS review_count,+ avg(sr.score::numeric) AS avg_rating+ FROM "StoreListing" sl_1+ JOIN "StoreListingVersion" slv_1+ ON slv_1."storeListingId" = sl_1.id+ JOIN "StoreListingReview" sr+ ON sr."storeListingVersionId" = slv_1.id+ WHERE sl_1."isDeleted" = false+ GROUP BY sl_1.id+), agentruns AS (+ SELECT "AgentGraphExecution"."agentGraphId",+ count(*) AS run_count+ FROM "AgentGraphExecution"+ GROUP BY "AgentGraphExecution"."agentGraphId"+)+SELECT sl.id AS listing_id,+ slv.id AS "storeListingVersionId",+ slv."createdAt" AS updated_at,+ sl.slug,+ COALESCE(slv.name, '') AS agent_name,+ slv."videoUrl" AS agent_video,+ COALESCE(slv."imageUrls", ARRAY[]::text[]) AS agent_image,+ slv."isFeatured" AS featured,+ p.username AS creator_username,+ p."avatarUrl" AS creator_avatar,+ slv."subHeading" AS sub_heading,+ slv.description,+ slv.categories,+ COALESCE(ar.run_count, 0::bigint) AS runs,+ COALESCE(rs.avg_rating, 0.0)::double precision AS rating,+ array_agg(DISTINCT slv.version::text) AS versions+ FROM "StoreListing" sl+ JOIN "AgentGraph" a+ ON sl."agentId" = a.id+ AND sl."agentVersion" = a.version+ LEFT JOIN "Profile" p+ ON sl."owningUserId" = p."userId"+ LEFT JOIN "StoreListingVersion" slv+ ON slv."storeListingId" = sl.id+ LEFT JOIN reviewstats rs+ ON sl.id = rs."storeListingId"+ LEFT JOIN agentruns ar+ ON a.id = ar."agentGraphId"+ WHERE sl."isDeleted" = false+ AND sl."hasApprovedVersion" = true+ AND slv."submissionStatus" = 'APPROVED'+ GROUP BY sl.id, slv.id, sl.slug, slv."createdAt", slv.name, slv."videoUrl",+ slv."imageUrls", slv."isFeatured", p.username, p."avatarUrl",+ slv."subHeading", slv.description, slv.categories, ar.run_count,+ rs.avg_rating;++-- 3. Recreate Creator view+CREATE VIEW "Creator" AS+WITH agentstats AS (+ SELECT p_1.username,+ count(DISTINCT sl.id) AS num_agents,+ avg(COALESCE(sr.score, 0)::numeric) AS agent_rating,+ sum(COALESCE(age.run_count, 0::bigint)) AS agent_runs+ FROM "Profile" p_1+ LEFT JOIN "StoreListing" sl+ ON sl."owningUserId" = p_1."userId"+ LEFT JOIN "StoreListingVersion" slv+ ON slv."storeListingId" = sl.id+ LEFT JOIN "StoreListingReview" sr+ ON sr."storeListingVersionId" = slv.id+ LEFT JOIN (+ SELECT "AgentGraphExecution"."agentGraphId",+ count(*) AS run_count+ FROM "AgentGraphExecution"+ GROUP BY "AgentGraphExecution"."agentGraphId"+ ) age ON age."agentGraphId" = sl."agentId"+ WHERE sl."isDeleted" = false+ AND sl."hasApprovedVersion" = true+ AND slv."submissionStatus" = 'APPROVED'+ GROUP BY p_1.username+)+SELECT p.username,+ p.name,+ p."avatarUrl" AS avatar_url,+ p.description,+ array_agg(DISTINCT cats.c) FILTER (WHERE cats.c IS NOT NULL) AS top_categories,+ p.links,+ p."isFeatured" AS is_featured,+ COALESCE(ast.num_agents, 0::bigint) AS num_agents,+ COALESCE(ast.agent_rating, 0.0) AS agent_rating,+ COALESCE(ast.agent_runs, 0::numeric) AS agent_runs+ FROM "Profile" p+ LEFT JOIN agentstats ast+ ON ast.username = p.username+ LEFT JOIN LATERAL (+ SELECT unnest(slv.categories) AS c+ FROM "StoreListing" sl+ JOIN "StoreListingVersion" slv+ ON slv."storeListingId" = sl.id+ WHERE sl."owningUserId" = p."userId"+ AND sl."isDeleted" = false+ AND sl."hasApprovedVersion" = true+ AND slv."submissionStatus" = 'APPROVED'+ ) cats ON true+ GROUP BY p.username, p.name, p."avatarUrl", p.description, p.links,+ p."isFeatured", ast.num_agents, ast.agent_rating, ast.agent_runs;++COMMIT;diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex 6defe1ed5e..5a34024eb9 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -44,14 +44,14 @@ model User {AgentPreset AgentPreset[]LibraryAgent LibraryAgent[]- Profile Profile[]- UserOnboarding UserOnboarding?- StoreListing StoreListing[]- StoreListingReview StoreListingReview[]- StoreListingSubmission StoreListingSubmission[]- APIKeys APIKey[]- IntegrationWebhooks IntegrationWebhook[]- UserNotificationBatch UserNotificationBatch[]+ Profile Profile[]+ UserOnboarding UserOnboarding?+ StoreListing StoreListing[]+ StoreListingReview StoreListingReview[]+ StoreVersionsReviewed StoreListingVersion[]+ APIKeys APIKey[]+ IntegrationWebhooks IntegrationWebhook[]+ UserNotificationBatch UserNotificationBatch[]@@index([id])@@index([email])@@ -71,7 +71,7 @@ model UserOnboarding {isCompleted Boolean @default(false)userId String @unique- user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)@@index([userId])}@@ -86,13 +86,13 @@ model AgentGraph {name String?description String?- isActive Boolean @default(true)+ isActive Boolean @default(true)// Link to User modeluserId String// FIX: Do not cascade delete the agent when the user is deleted// This allows us to delete user data with deleting the agent which maybe in use by other users- user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)AgentNodes AgentNode[]AgentGraphExecution AgentGraphExecution[]@@ -100,7 +100,7 @@ model AgentGraph {AgentPreset AgentPreset[]LibraryAgent LibraryAgent[]StoreListing StoreListing[]- StoreListingVersion StoreListingVersion?+ StoreListingVersion StoreListingVersion[]@@id(name: "graphVersionId", [id, version])@@index([userId, isActive])@@ -175,11 +175,11 @@ model UserNotificationBatch {updatedAt DateTime @default(now()) @updatedAtuserId String- user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)type NotificationType- notifications NotificationEvent[]+ Notifications NotificationEvent[]// Each user can only have one batch of a notification type at a time@@unique([userId, type])@@ -195,7 +195,7 @@ model LibraryAgent {userId StringUser User @relation(fields: [userId], references: [id], onDelete: Cascade)- imageUrl String?+ imageUrl String?agentId StringagentVersion Int@@ -319,7 +319,7 @@ model AgentGraphExecution {// Link to User model -- Executed by this useruserId String- user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)stats Json?AgentPreset AgentPreset? @relation(fields: [agentPresetId], references: [id])@@ -384,7 +384,7 @@ model IntegrationWebhook {updatedAt DateTime? @updatedAtuserId String- user User @relation(fields: [userId], references: [id], onDelete: Restrict) // Webhooks must be deregistered before deleting+ User User @relation(fields: [userId], references: [id], onDelete: Restrict) // Webhooks must be deregistered before deletingprovider String // e.g. 'github'credentialsId String // relation to the credentials that the webhook was created with@@ -411,7 +411,7 @@ model AnalyticsDetails {// Link to User modeluserId String- user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)// Analytics Categorical data used for filtering (indexable w and w/o userId)type String@@ -446,7 +446,7 @@ model AnalyticsMetrics {// Link to User modeluserId String- user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)@@index([userId])}@@ -470,7 +470,7 @@ model CreditTransaction {createdAt DateTime @default(now())userId String- user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)amount Inttype CreditTransactionType@@ -579,19 +579,25 @@ view StoreAgent {}view StoreSubmission {- listing_id String @id- user_id String- slug String- name String- sub_heading String- description String- image_urls String[]- date_submitted DateTime- status SubmissionStatus- runs Int- rating Float- agent_id String- agent_version Int+ listing_id String @id+ user_id String+ slug String+ name String+ sub_heading String+ description String+ image_urls String[]+ date_submitted DateTime+ status SubmissionStatus+ runs Int+ rating Float+ agent_id String+ agent_version Int+ store_listing_version_id String+ reviewer_id String?+ review_comments String?+ internal_comments String?+ reviewed_at DateTime?+ changes_summary String?// Index or unique are not applied to views}@@ -601,11 +607,18 @@ model StoreListing {createdAt DateTime @default(now())updatedAt DateTime @default(now()) @updatedAt- isDeleted Boolean @default(false)- // Not needed but makes lookups faster- isApproved Boolean @default(false)+ isDeleted Boolean @default(false)+ // Whether any version has been approved and is available for display+ hasApprovedVersion Boolean @default(false)++ // URL-friendly identifier for this agent (moved from StoreListingVersion)+ slug String- // The agent link here is only so we can do lookup on agentId, for the listing the StoreListingVersion is used.+ // The currently active version that should be shown to users+ activeVersionId String? @unique+ ActiveVersion StoreListingVersion? @relation("ActiveVersion", fields: [activeVersionId], references: [id])++ // The agent link here is only so we can do lookup on agentIdagentId StringagentVersion IntAgent AgentGraph @relation(fields: [agentId, agentVersion], references: [id, version], onDelete: Cascade)@@ -613,14 +626,14 @@ model StoreListing {owningUserId StringOwningUser User @relation(fields: [owningUserId], references: [id])- StoreListingVersions StoreListingVersion[]- StoreListingSubmission StoreListingSubmission[]+ // Relations+ Versions StoreListingVersion[] @relation("ListingVersions")// Unique index on agentId to ensure only one listing per agent, regardless of number of versions the agent has.@@unique([agentId])- @@index([owningUserId])+ @@unique([owningUserId, slug])// Used in the view query- @@index([isDeleted, isApproved])+ @@index([isDeleted, hasApprovedVersion])}model StoreListingVersion {@@ -634,10 +647,7 @@ model StoreListingVersion {agentVersion IntAgent AgentGraph @relation(fields: [agentId, agentVersion], references: [id, version])- // The details for this version of the agent, this allows the author to update the details of the agent,- // But still allow using old versions of the agent with there original details.- // TODO: Create a database view that shows only the latest version of each store listing.- slug String+ // Content fieldsname StringsubHeading StringvideoUrl String?@@ -647,20 +657,39 @@ model StoreListingVersion {isFeatured Boolean @default(false)- isDeleted Boolean @default(false)+ isDeleted Boolean @default(false)// Old versions can be made unavailable by the author if desired- isAvailable Boolean @default(true)- // Not needed but makes lookups faster- isApproved Boolean @default(false)- StoreListing StoreListing? @relation(fields: [storeListingId], references: [id], onDelete: Cascade)- storeListingId String?- StoreListingSubmission StoreListingSubmission[]+ isAvailable Boolean @default(true)++ // Version workflow state+ submissionStatus SubmissionStatus @default(DRAFT)+ submittedAt DateTime?++ // Relations+ storeListingId String+ StoreListing StoreListing @relation("ListingVersions", fields: [storeListingId], references: [id], onDelete: Cascade)++ // This version might be the active version for a listing+ ActiveFor StoreListing? @relation("ActiveVersion")++ // Submission history+ changesSummary String?- // Reviews are on a specific version, but then aggregated up to the listing.- // This allows us to provide a review filter to current version of the agent.- StoreListingReview StoreListingReview[]+ // Review information+ reviewerId String?+ Reviewer User? @relation(fields: [reviewerId], references: [id])+ internalComments String? // Private notes for admin use only+ reviewComments String? // Comments visible to creator+ reviewedAt DateTime?- @@unique([agentId, agentVersion])+ // Reviews for this specific version+ Reviews StoreListingReview[]++ @@unique([storeListingId, version])+ @@index([storeListingId, submissionStatus, isAvailable])+ @@index([submissionStatus])+ @@index([reviewerId])+ @@index([agentId, agentVersion]) // Non-unique index for efficient lookups}model StoreListingReview {@@ -681,31 +710,10 @@ model StoreListingReview {}enum SubmissionStatus {- DAFT- PENDING- APPROVED- REJECTED-}--model StoreListingSubmission {- id String @id @default(uuid())- createdAt DateTime @default(now())- updatedAt DateTime @default(now()) @updatedAt-- storeListingId String- StoreListing StoreListing @relation(fields: [storeListingId], references: [id], onDelete: Cascade)-- storeListingVersionId String- StoreListingVersion StoreListingVersion @relation(fields: [storeListingVersionId], references: [id], onDelete: Cascade)-- reviewerId String- Reviewer User @relation(fields: [reviewerId], references: [id])-- Status SubmissionStatus @default(PENDING)- reviewComments String?-- @@unique([storeListingVersionId])- @@index([storeListingId])+ DRAFT // Being prepared, not yet submitted+ PENDING // Submitted, awaiting review+ APPROVED // Reviewed and approved+ REJECTED // Reviewed and rejected}enum APIKeyPermission {@@ -732,7 +740,7 @@ model APIKey {// Relation to useruserId String- user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)@@index([key])@@index([prefix])diff --git a/autogpt_platform/backend/test/data/test_graph.py b/autogpt_platform/backend/test/data/test_graph.pyindex f2f133d1ad..6bfc237fd7 100644--- a/autogpt_platform/backend/test/data/test_graph.py+++ b/autogpt_platform/backend/test/data/test_graph.py@@ -242,7 +242,7 @@ async def test_access_store_listing_graph(server: SpinTestServer):store_submission_request = store.StoreSubmissionRequest(agent_id=created_graph.id,agent_version=created_graph.version,- slug="test-slug",+ slug=created_graph.id,name="Test name",sub_heading="Test sub heading",video_url=None,diff --git a/autogpt_platform/backend/test/executor/test_manager.py b/autogpt_platform/backend/test/executor/test_manager.pyindex 6094f4b66b..746691002c 100644--- a/autogpt_platform/backend/test/executor/test_manager.py+++ b/autogpt_platform/backend/test/executor/test_manager.py@@ -492,7 +492,7 @@ async def test_store_listing_graph(server: SpinTestServer):store_submission_request = backend.server.v2.store.model.StoreSubmissionRequest(agent_id=test_graph.id,agent_version=test_graph.version,- slug="test-slug",+ slug=test_graph.id,name="Test name",sub_heading="Test sub heading",video_url=None,diff --git a/autogpt_platform/backend/test/test_data_creator.py b/autogpt_platform/backend/test/test_data_creator.pyindex 8e3441dbfd..52a398eed8 100644--- a/autogpt_platform/backend/test/test_data_creator.py+++ b/autogpt_platform/backend/test/test_data_creator.py@@ -328,12 +328,14 @@ async def main():print(f"Inserting {NUM_USERS} store listings")for graph in agent_graphs:user = random.choice(users)+ slug = faker.slug()listing = await db.storelisting.create(data={"agentId": graph.id,"agentVersion": graph.version,"owningUserId": user.id,- "isApproved": random.choice([True, False]),+ "hasApprovedVersion": random.choice([True, False]),+ "slug": slug,})store_listings.append(listing)@@ -347,7 +349,6 @@ async def main():data={"agentId": graph.id,"agentVersion": graph.version,- "slug": faker.slug(),"name": graph.name or faker.sentence(nb_words=3),"subHeading": faker.sentence(),"videoUrl": faker.url(),@@ -356,8 +357,14 @@ async def main():"categories": [faker.word() for _ in range(3)],"isFeatured": random.choice([True, False]),"isAvailable": True,- "isApproved": random.choice([True, False]),"storeListingId": listing.id,+ "submissionStatus": random.choice(+ [+ prisma.enums.SubmissionStatus.PENDING,+ prisma.enums.SubmissionStatus.APPROVED,+ prisma.enums.SubmissionStatus.REJECTED,+ ]+ ),})store_listing_versions.append(version)@@ -386,10 +393,9 @@ async def main():})- # Insert StoreListingSubmissions- print(f"Inserting {NUM_USERS} store listing submissions")- for listing in store_listings:- version = random.choice(store_listing_versions)+ # Update StoreListingVersions with submission status (StoreListingSubmissions table no longer exists)+ print(f"Updating {NUM_USERS} store listing versions with submission status")+ for version in store_listing_versions:reviewer = random.choice(users)status: prisma.enums.SubmissionStatus = random.choice([@@ -398,14 +404,14 @@ async def main():prisma.enums.SubmissionStatus.REJECTED,])- await db.storelistingsubmission.create(+ await db.storelistingversion.update(+ where={"id": version.id},data={- "storeListingId": listing.id,- "storeListingVersionId": version.id,- "reviewerId": reviewer.id,- "Status": status,+ "submissionStatus": status,+ "Reviewer": {"connect": {"id": reviewer.id}},"reviewComments": faker.text(),- }+ "reviewedAt": datetime.now(),+ },)# Insert APIKeysdiff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.tsindex 26561c889e..e6ad212f6c 100644--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts@@ -1,3 +1,10 @@+export type SubmissionStatus = "DRAFT" | "PENDING" | "APPROVED" | "REJECTED";+export type ReviewSubmissionRequest = {+ store_listing_version_id: string;+ is_approved: boolean;+ comments: string; // External comments visible to creator+ internal_comments?: string; // Admin-only comments+};export type Category = {category: string;description: string;@@ -559,6 +566,11 @@ export type StoreAgentDetails = {runs: number;rating: number;versions: string[];++ // Approval and status fields+ active_version_id?: string;+ has_approved_version?: boolean;+ is_available?: boolean;};export type Creator = {@@ -595,9 +607,21 @@ export type StoreSubmission = {description: string;image_urls: string[];date_submitted: string;- status: string;+ status: SubmissionStatus;runs: number;rating: number;+ slug: string;+ store_listing_version_id?: string;++ // Review information+ reviewer_id?: string;+ review_comments?: string;+ internal_comments?: string; // Admin-only comments+ reviewed_at?: string;+ changes_summary?: string;++ // Approval status+ is_approved?: boolean;};export type StoreSubmissionsResponse = {@@ -615,6 +639,7 @@ export type StoreSubmissionRequest = {image_urls: string[];description: string;categories: string[];+ changes_summary?: string;};export type ProfileDetails = {@@ -770,3 +795,26 @@ export interface OttoQuery {include_graph_data: boolean;graph_id?: string;}++// Admin API Types+export type AdminSubmissionsRequest = {+ status?: SubmissionStatus;+ search?: string;+ page: number;+ page_size: number;+};++export type AdminListingHistoryRequest = {+ listing_id: string;+ page: number;+ page_size: number;+};++export type AdminSubmissionDetailsRequest = {+ store_listing_version_id: string;+};++export type AdminPendingSubmissionsRequest = {+ page: number;+ page_size: number;+};